diff --git a/CHANGELOG.md b/CHANGELOG.md index 59d49408..70e5aff6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,29 @@ ## Unreleased +* **The transformation point, a box that turns with the object, and layer opacity, from user + reports** (ADR 0111, M1). + * **Move the transformation point** (#302, #280, #178, #183): with Free Transform, drag the + white circle to where the object should turn; it snaps to the box's corners, sides and + centre (Alt places it freely) and can sit outside the box. Double-click it to centre it + again. Rotating turns about it, and Alt scales and skews about it. + * **A symbol instance keeps its point**: it is saved with the instance and used by Free + Transform, Rotate 90° and Flip, the Scale and Rotation fields in Properties, and classic + and motion tweens, so an arm keyed at two angles swings from its shoulder. Properties + shows it as **Pivot** with **Reset**; Modify › Transform › Reset Transformation Point. + Shapes, groups, text and several objects have a point while they stay selected with Free + Transform. Files and tweens made before this are unchanged. + * **The box turns with the object** (#175): one selected object shows its own box, turned, + scaled and skewed as it is, and its handles stretch it along its own sides. + * **Layer opacity** (#279): 0 to 100 % in Layer Properties and in the layer's right-click + menu, shown beside the layer's name. The layer fades as one (overlapping shapes don't show + through each other), a folder fades the layers in it, and it is in the movie: the stage, + Test Movie and every export. + * Headless, CLI and MCP: `modify.transformation_point`, `modify.reset_transformation_point`, + `layer.set_opacity`, and `opacity` on `layer.set_properties` and `layer.properties`. + * Changed: with Free Transform, a press on the very centre of the box now takes the + transformation point; drag anywhere else inside the box to move the object. + * **Fixes from your reports: drawing, selection, transform and the timeline** (M1, ADR 0108). * **Fixed: a drawing could vanish under a new brush stroke** (fixes #308). Where a stroke crossed an older one at a shallow angle, the merge could lose the older fill, sometimes diff --git a/crates/doc/src/armature_tests.rs b/crates/doc/src/armature_tests.rs index 79df7fd1..c00d782b 100644 --- a/crates/doc/src/armature_tests.rs +++ b/crates/doc/src/armature_tests.rs @@ -13,7 +13,7 @@ const B2: BoneId = BoneId(21); const SEG: SymbolId = SymbolId(1); fn instance(id: ElementId, x: f32, y: f32) -> Arc { - let kind = ElementKind::Symbol { symbol: SEG, loop_mode: LoopMode::Loop, first_frame: 0, blend: BlendMode::Normal, filters: Vec::new(), events: Vec::new() }; + let kind = ElementKind::Symbol { symbol: SEG, loop_mode: LoopMode::Loop, first_frame: 0, blend: BlendMode::Normal, filters: Vec::new(), events: Vec::new(), pivot: None }; Arc::new(Element { id, name: String::new(), transform: Affine::translate(x, y), color: ColorEffect::default(), kind }) } diff --git a/crates/doc/src/eval.rs b/crates/doc/src/eval.rs index 96437067..01ce642d 100644 --- a/crates/doc/src/eval.rs +++ b/crates/doc/src/eval.rs @@ -537,10 +537,32 @@ fn interpolate(a: &Element, b: &Element, pr: Progress, morph: bool, hints: &[(an (d.rotation, d.skew, d.sx, d.sy) = (r.rotation, r.skew, s.sx, s.sy); } let mut transform = d.compose(); + // An instance with a transformation point (ADR 0111) turns, scales and skews about it: the + // point travels from where the first keyframe has it to where the next does, and the + // instance is placed round it. (A keyframe without one takes the other's.) Without a + // point this is the registration point, as above. + let pivot = match (a.pivot().or(b.pivot()), b.pivot().or(a.pivot())) { + (Some(pa), Some(pb)) => { + let (qa, qb) = (a.transform.apply(pa), b.transform.apply(pb)); + let (q, p) = (qa + (qb - qa) * pr.position, pa + (pb - pa) * pr.position); + let about = Affine { m: [transform.m[0], transform.m[1], transform.m[2], transform.m[3], 0.0, 0.0] }; + let o = about.apply(p); + let placed = Affine::translate(q.x - o.x, q.y - o.y).mul(&about); + if placed.is_finite() { + transform = placed; + } + Some(p) + } + _ => None, + }; if let Some((g, orient)) = guide { transform = follow(g, orient, &a.transform, &b.transform, pr.position, transform); } - Some(Element { id: a.id, name: a.name.clone(), transform, color: a.color.lerp(&b.color, pr.color), kind }) + let mut el = Element { id: a.id, name: a.name.clone(), transform, color: a.color.lerp(&b.color, pr.color), kind }; + if pivot.is_some() { + el.set_pivot(pivot); + } + Some(el) } /// What a timeline is evaluated inside of. @@ -694,6 +716,20 @@ fn eval_timeline(doc: &Document, tl: &Timeline, frame: u32, cx: &Ctx, out: &mut None => cx.xf, }; let lc = LayerCtx { layer, frame, kf_start, clip, masks, guide, outline: layer_outline, xf: layer_xf }; + // A layer below full opacity (its own, or a folder's it is in; ADR 0111) fades as one: + // its artwork composites in a group, and the group blends at the layer's opacity, so + // its overlapping parts don't show through each other. Mask artwork ignores opacity, + // and guide artwork is never in the movie; an empty frame needs no group. + let fade = if masks.is_none() && !guide && !elements.is_empty() { tl.layer_opacity(index) } else { 1.0 }; + let faded; + let cx = if fade < 1.0 - 1e-4 { + let gid = out.groups.len() as u32; + out.groups.push(Group { parent: cx.group, alpha: fade, blend: crate::BlendMode::Normal, filters: Arc::from(Vec::new()), clip }); + faded = Ctx { group: Some(gid), ..*cx }; + &faded + } else { + cx + }; for el in elements.iter() { eval_element(doc, cx, &lc, el, out, play); } @@ -985,3 +1021,7 @@ fn sliced_shape(s: &Shape, own: &Affine, sl: &Slicing) -> (Arc, Affine, Op #[cfg(test)] #[path = "eval_tests.rs"] mod tests; + +#[cfg(test)] +#[path = "pivot_tests.rs"] +mod pivot_tests; diff --git a/crates/doc/src/eval_tests.rs b/crates/doc/src/eval_tests.rs index 13668c84..5c5b3254 100644 --- a/crates/doc/src/eval_tests.rs +++ b/crates/doc/src/eval_tests.rs @@ -81,7 +81,7 @@ fn nested_symbols_compose_transforms_and_cycles_terminate() { name: String::new(), transform: Affine::translate(1.0, 0.0), color: ColorEffect::default(), - kind: ElementKind::Symbol { symbol: sid, loop_mode: Default::default(), first_frame: 0, blend: Default::default(), filters: Vec::new(), events: Vec::new() }, + kind: ElementKind::Symbol { symbol: sid, loop_mode: Default::default(), first_frame: 0, blend: Default::default(), filters: Vec::new(), events: Vec::new(), pivot: None }, }, ); tl.layers.push(Arc::new(layer)); @@ -94,7 +94,7 @@ fn nested_symbols_compose_transforms_and_cycles_terminate() { name: String::new(), transform: Affine::translate(100.0, 0.0), color: ColorEffect::Alpha(0.5), - kind: ElementKind::Symbol { symbol: sid, loop_mode: Default::default(), first_frame: 0, blend: Default::default(), filters: Vec::new(), events: Vec::new() }, + kind: ElementKind::Symbol { symbol: sid, loop_mode: Default::default(), first_frame: 0, blend: Default::default(), filters: Vec::new(), events: Vec::new(), pivot: None }, }, ); let dl = evaluate(&d, 0); @@ -146,7 +146,7 @@ fn masks_inside_symbols_nest_in_the_instance_clip() { name: String::new(), transform: Affine::IDENTITY, color: ColorEffect::default(), - kind: ElementKind::Symbol { symbol: sid, loop_mode: Default::default(), first_frame: 0, blend: Default::default(), filters: Vec::new(), events: Vec::new() }, + kind: ElementKind::Symbol { symbol: sid, loop_mode: Default::default(), first_frame: 0, blend: Default::default(), filters: Vec::new(), events: Vec::new(), pivot: None }, }; push(Arc::make_mut(&mut d.timeline_mut(0).layers[1]), 0, inst); let dl = evaluate(&d, 0); @@ -323,7 +323,7 @@ fn movie_clips_play_their_own_timeline_graphics_keep_step_buttons_hold_up() { name: String::new(), transform: Affine::translate(x, 0.0), color: ColorEffect::default(), - kind: ElementKind::Symbol { symbol: sid, loop_mode: crate::LoopMode::Loop, first_frame: 0, blend: Default::default(), filters: Vec::new(), events: Vec::new() }, + kind: ElementKind::Symbol { symbol: sid, loop_mode: crate::LoopMode::Loop, first_frame: 0, blend: Default::default(), filters: Vec::new(), events: Vec::new(), pivot: None }, }; let (mut k0, mut k1) = (Keyframe::new(0, 5), Keyframe::new(5, 7)); k0.elements.push(Arc::new(inst(0.0))); @@ -561,7 +561,7 @@ fn instance_filters_tween_when_they_pair_up() { let mut d = Document::default(); let sid = SymbolId(90); d.library.push(Arc::new(Symbol { id: sid, name: "Clip".into(), kind: SymbolKind::MovieClip, linkage: None, scale_grid_kept: None, scale_grid: None, timeline: Timeline { layers: vec![Arc::new(Layer::new(LayerId(91), "x"))] } })); - let inst = |filters: Vec| Element { id: ElementId(92), name: String::new(), transform: Affine::IDENTITY, color: ColorEffect::default(), kind: ElementKind::Symbol { symbol: sid, loop_mode: Default::default(), first_frame: 0, blend: Default::default(), filters: filters.into_iter().map(Into::into).collect(), events: Vec::new() } }; + let inst = |filters: Vec| Element { id: ElementId(92), name: String::new(), transform: Affine::IDENTITY, color: ColorEffect::default(), kind: ElementKind::Symbol { symbol: sid, loop_mode: Default::default(), first_frame: 0, blend: Default::default(), filters: filters.into_iter().map(Into::into).collect(), events: Vec::new(), pivot: None } }; let blur = |b: f32| Filter::Blur { blur_x: b, blur_y: b, quality: 1 }; let mut tw = Tween::new(Easing::Linear, TweenKind::Classic); tw.set_ease(crate::EaseGroup::Filters, Some(Easing::QuadIn)); diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index 77d6a277..4454935f 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -575,6 +575,12 @@ pub enum ElementKind { /// ADR 0024), one handler per event. #[serde(default, skip_serializing_if = "Vec::is_empty")] events: Vec, + /// The transformation point (ADR 0111), in the instance's own space: what Free + /// Transform, the Properties fields and tweens turn, scale and skew it about. `None` + /// until the artist moves it: tools then use the centre of its box, and tweens its + /// registration point (as files from before it did). Read through [`Element::pivot`]. + #[serde(default, skip_serializing_if = "Option::is_none")] + pivot: Option, }, /// A block of text (ADR 0012). Text(Arc), @@ -1039,6 +1045,34 @@ pub struct Element { } impl Element { + /// The transformation point the artist set (ADR 0111), in the element's own space: only a + /// symbol instance keeps one. `None` when it was never moved, or isn't finite. + pub fn pivot(&self) -> Option { + match &self.kind { + ElementKind::Symbol { pivot, .. } => pivot.filter(|p| p.is_finite() && p.x.abs() <= MAX_PIVOT && p.y.abs() <= MAX_PIVOT), + _ => None, + } + } + /// Sets or clears the transformation point (own space). Answers whether the element keeps + /// one (a symbol instance does). + pub fn set_pivot(&mut self, at: Option) -> bool { + match &mut self.kind { + ElementKind::Symbol { pivot, .. } => { + *pivot = at.filter(|p| p.is_finite() && p.x.abs() <= MAX_PIVOT && p.y.abs() <= MAX_PIVOT); + true + } + _ => false, + } + } + /// `transform` moved so that the transformation point (when one is set) stays where + /// `self.transform` has it in the parent's space: how a new scale, rotation or skew is + /// applied about the point. Without a point, `transform` as given. + pub fn about_pivot(&self, transform: Affine) -> Affine { + let Some(p) = self.pivot() else { return transform }; + let d = self.transform.apply(p) - transform.apply(p); + let m = Affine::translate(d.x, d.y).mul(&transform); + if m.is_finite() { m } else { transform } + } /// Local-space bounds (control-point bounds for shapes, `None` for symbols). pub fn local_bounds(&self, doc: &Document) -> Rect { element_bounds(doc, self, &Affine::IDENTITY, 0) @@ -1329,6 +1363,11 @@ pub struct Layer { /// masks), or its opacity or brightness (soft masks). Ignored on other kinds of layer. #[serde(default, skip_serializing_if = "MaskMode::is_coverage")] pub mask_mode: MaskMode, + /// The layer's opacity, `0..=1` (ADR 0111): its artwork is drawn together, then shown this + /// strongly, in the movie and every export. A folder's fades the layers in it. Read + /// through [`Layer::shown_opacity`]. + #[serde(default = "full", skip_serializing_if = "is_full")] + pub opacity: f32, } /// How a mask layer's artwork reveals the layers it masks (ADR 0070). @@ -1397,6 +1436,10 @@ fn is_one(v: &u8) -> bool { *v == 1 } +/// Farthest a transformation point may be from its instance's registration point, in the +/// instance's own units (ADR 0111). +pub const MAX_PIVOT: f32 = 1.0e6; + /// Tallest a layer's timeline row gets, in normal rows (300 %). pub const MAX_LAYER_HEIGHT: u8 = 3; @@ -1418,6 +1461,7 @@ impl PartialEq for Layer { && self.volume.to_bits() == o.volume.to_bits() && self.muted == o.muted && self.mask_mode == o.mask_mode + && self.opacity.to_bits() == o.opacity.to_bits() && match (&self.armature, &o.armature) { (Some(a), Some(b)) => arc_eq(a, b), (a, b) => a.is_none() && b.is_none(), @@ -1454,8 +1498,13 @@ impl Layer { muted: false, armature: None, mask_mode: MaskMode::Coverage, + opacity: 1.0, } } + /// The layer's own opacity, `0..=1` whatever a file says (not a number: opaque). + pub fn shown_opacity(&self) -> f32 { + if self.opacity.is_finite() { self.opacity.clamp(0.0, 1.0) } else { 1.0 } + } /// The row height in normal rows, `1..=MAX_LAYER_HEIGHT` whatever a file says. pub fn height(&self) -> u8 { self.height_rows.clamp(1, MAX_LAYER_HEIGHT) @@ -1629,6 +1678,13 @@ impl Timeline { self.folders_of(index).any(|f| !f.visible) } + /// How strongly the layer at `index` shows (ADR 0111): its own opacity times that of every + /// folder it is in. + pub fn layer_opacity(&self, index: usize) -> f32 { + let own = self.layers.get(index).map_or(1.0, |l| l.shown_opacity()); + self.folders_of(index).fold(own, |a, f| a * f.shown_opacity()) + } + /// Whether a folder containing layer `id` is locked (so the layer is too). pub fn locked_by_folder(&self, id: LayerId) -> bool { self.index_of(id).is_some_and(|i| self.folders_of(i).any(|f| f.locked)) diff --git a/crates/doc/src/library_tests.rs b/crates/doc/src/library_tests.rs index d737b7ab..8953e731 100644 --- a/crates/doc/src/library_tests.rs +++ b/crates/doc/src/library_tests.rs @@ -7,7 +7,7 @@ fn instance(d: &mut Document, symbol: SymbolId) -> Arc { name: String::new(), transform: Default::default(), color: Default::default(), - kind: ElementKind::Symbol { symbol, loop_mode: Default::default(), first_frame: 0, blend: Default::default(), filters: Vec::new(), events: Vec::new() }, + kind: ElementKind::Symbol { symbol, loop_mode: Default::default(), first_frame: 0, blend: Default::default(), filters: Vec::new(), events: Vec::new(), pivot: None }, }) } @@ -133,7 +133,7 @@ fn uses_count_every_keyframe_and_unused_follows_reachability() { let b = add_symbol(&mut d, "B", &[a]); if let Some(s) = d.library.iter_mut().find(|s| s.id == a) { let layer = Arc::make_mut(&mut Arc::make_mut(s).timeline.layers[0]); - let e = Arc::new(Element { id: ElementId(5_000_000), name: String::new(), transform: Default::default(), color: Default::default(), kind: ElementKind::Symbol { symbol: b, loop_mode: Default::default(), first_frame: 0, blend: Default::default(), filters: Vec::new(), events: Vec::new() } }); + let e = Arc::new(Element { id: ElementId(5_000_000), name: String::new(), transform: Default::default(), color: Default::default(), kind: ElementKind::Symbol { symbol: b, loop_mode: Default::default(), first_frame: 0, blend: Default::default(), filters: Vec::new(), events: Vec::new(), pivot: None } }); layer.keyframe_mut(0).unwrap().elements.push(e); } assert_eq!(d.unused_items(), vec![LibraryItem::Symbol(a), LibraryItem::Symbol(b)]); diff --git a/crates/doc/src/mixed_tests.rs b/crates/doc/src/mixed_tests.rs index 40181edd..b69d8e07 100644 --- a/crates/doc/src/mixed_tests.rs +++ b/crates/doc/src/mixed_tests.rs @@ -40,7 +40,7 @@ fn shape(id: ElementId, path: Arc, at: Vec2) -> Arc { } fn instance(id: ElementId, at: Vec2) -> Arc { - let kind = ElementKind::Symbol { symbol: SymbolId(1), loop_mode: LoopMode::Loop, first_frame: 0, blend: BlendMode::Normal, filters: Vec::new(), events: Vec::new() }; + let kind = ElementKind::Symbol { symbol: SymbolId(1), loop_mode: LoopMode::Loop, first_frame: 0, blend: BlendMode::Normal, filters: Vec::new(), events: Vec::new(), pivot: None }; Arc::new(Element { id, name: String::new(), transform: Affine::translate(at.x, at.y), color: ColorEffect::default(), kind }) } diff --git a/crates/doc/src/motion.rs b/crates/doc/src/motion.rs index 20cb590b..6f9d18a3 100644 --- a/crates/doc/src/motion.rs +++ b/crates/doc/src/motion.rs @@ -1160,7 +1160,16 @@ impl MotionTween { } } if on_path.is_some() || self.tracks.iter().any(|t| t.property.is_transform()) { - let m = props.transform(); + let mut m = props.transform(); + // With a transformation point (ADR 0111) the position tracks carry the point, and + // the target turns, scales and skews about it. + if let Some(p) = base.pivot() { + let (d0, d1) = (base_props.transform().translation(), m.translation()); + let at = base.transform.apply(p) + (d1 - d0); + let about = Affine { m: [m.m[0], m.m[1], m.m[2], m.m[3], 0.0, 0.0] }; + let o = about.apply(p); + m = Affine::translate(at.x - o.x, at.y - o.y).mul(&about); + } if m.is_finite() { el.transform = m; } @@ -1962,7 +1971,7 @@ mod tests { /// A movie clip instance with `filters`, at (x, 0). fn clip(x: f32, filters: Vec) -> Element { Element { - kind: ElementKind::Symbol { symbol: crate::SymbolId(1), loop_mode: Default::default(), first_frame: 0, blend: Default::default(), filters: filters.into_iter().map(crate::FilterEntry::from).collect(), events: Vec::new() }, + kind: ElementKind::Symbol { symbol: crate::SymbolId(1), loop_mode: Default::default(), first_frame: 0, blend: Default::default(), filters: filters.into_iter().map(crate::FilterEntry::from).collect(), events: Vec::new(), pivot: None }, ..el(1, x, 0.0) } } diff --git a/crates/doc/src/nine_slice_tests.rs b/crates/doc/src/nine_slice_tests.rs index 79029bc3..d181f2c7 100644 --- a/crates/doc/src/nine_slice_tests.rs +++ b/crates/doc/src/nine_slice_tests.rs @@ -11,7 +11,7 @@ fn el(id: u64, transform: Affine, kind: ElementKind) -> Element { } fn instance(of: SymbolId, transform: Affine) -> Element { - el(1, transform, ElementKind::Symbol { symbol: of, loop_mode: Default::default(), first_frame: 0, blend: Default::default(), filters: Vec::new(), events: Vec::new() }) + el(1, transform, ElementKind::Symbol { symbol: of, loop_mode: Default::default(), first_frame: 0, blend: Default::default(), filters: Vec::new(), events: Vec::new(), pivot: None }) } /// A 100×40 rounded rectangle (corner radius 10) at the symbol's origin, guides 10 in from each diff --git a/crates/doc/src/pivot_tests.rs b/crates/doc/src/pivot_tests.rs new file mode 100644 index 00000000..3c4d11d3 --- /dev/null +++ b/crates/doc/src/pivot_tests.rs @@ -0,0 +1,225 @@ +//! The transformation point in tweens and layer opacity in the display list (ADR 0111). + +use super::*; +use crate::{ColorEffect, Document, Keyframe, Symbol, SymbolId, SymbolKind, Tween}; +use anicraft_geom::Vec2; + +fn inst(transform: Affine, pivot: Option) -> Element { + Element { + id: ElementId(10), + name: String::new(), + transform, + color: ColorEffect::default(), + kind: ElementKind::Symbol { symbol: SymbolId(1), loop_mode: Default::default(), first_frame: 0, blend: Default::default(), filters: Vec::new(), events: Vec::new(), pivot }, + } +} + +fn square(id: u64, x: f32, w: f32, h: f32) -> Element { + Element { id: ElementId(id), name: String::new(), transform: Affine::translate(x, 0.0), color: ColorEffect::default(), kind: ElementKind::Shape(Shape::filled(Path::rect(0.0, 0.0, w, h), Paint::Solid(Rgba::BLACK))) } +} + +/// A 40 × 20 arm whose registration point is its top left, tweened from `a` to `b` over ten frames. +fn arm_doc(a: Element, b: Element) -> Document { + let mut d = Document::default(); + let mut tl = Timeline::default(); + let mut l = Layer::new(LayerId(50), "arm"); + l.keyframes = vec![Arc::new(Keyframe { elements: vec![Arc::new(square(2, 0.0, 40.0, 20.0))], ..Keyframe::new(0, 1) })]; + tl.layers.push(Arc::new(l)); + d.library.push(Arc::new(Symbol { id: SymbolId(1), name: "arm".into(), kind: SymbolKind::Graphic, linkage: None, scale_grid_kept: None, scale_grid: None, timeline: tl })); + let mut k0 = Keyframe::new(0, 10); + k0.elements.push(Arc::new(a)); + k0.tween = Some(Tween::default()); + let mut k1 = Keyframe::new(10, 1); + k1.elements.push(Arc::new(b)); + Arc::make_mut(&mut d.timeline_mut(0).layers[0]).keyframes = vec![Arc::new(k0), Arc::new(k1)]; + d +} + +fn at(d: &Document, frame: u32) -> Element { + let (_, els) = evaluate_layer_elements(&d.timeline(0).layers[0], frame).unwrap(); + (*els[0]).clone() +} + +fn near(a: Vec2, b: Vec2) -> bool { + (a - b).length() < 1e-3 +} + +/// `m` turned by `deg` about stage point `c`. +fn turned(m: &Affine, c: Vec2, deg: f32) -> Affine { + Affine::translate(c.x, c.y).mul(&Affine::rotate(deg.to_radians())).mul(&Affine::translate(-c.x, -c.y)).mul(m) +} + +#[test] +fn a_tween_turns_an_instance_about_its_transformation_point() { + // The point is the middle of the arm's far end (40, 10); the arm turns 90° about it. + let p = Vec2::new(40.0, 10.0); + let start = Affine::translate(100.0, 100.0); + let hinge = start.apply(p); + let d = arm_doc(inst(start, Some(p)), inst(turned(&start, hinge, 90.0), Some(p))); + for f in 0..=10 { + let e = at(&d, f); + // The point stays on the hinge on every frame, and the arm has turned 9° a frame. + assert!(near(e.transform.apply(p), hinge), "frame {f}: {:?}", e.transform.apply(p)); + assert!((e.transform.decompose().rotation.to_degrees() - 9.0 * f as f32).abs() < 1e-3, "frame {f}"); + assert_eq!(e.pivot(), Some(p)); + } + // Analytic: halfway, the registration point is the hinge plus (-40, -10) turned 45°. + let (s, c) = 45f32.to_radians().sin_cos(); + let want = hinge + Vec2::new(-40.0 * c + 10.0 * s, -40.0 * s - 10.0 * c); + assert!(near(at(&d, 5).transform.translation(), want)); +} + +#[test] +fn without_a_point_a_tween_turns_about_the_registration_point_as_before() { + let start = Affine::translate(100.0, 100.0); + let end = turned(&start, Vec2::new(140.0, 110.0), 90.0); + let d = arm_doc(inst(start, None), inst(end, None)); + let e = at(&d, 5); + // The registration point goes straight from one key to the other: files from before the + // point keep their motion exactly. + let want = start.decompose().lerp(&end.decompose(), 0.5).compose(); + assert_eq!(e.transform, want); + assert_eq!(e.pivot(), None); +} + +#[test] +fn the_point_travels_and_one_keyframe_lends_it_to_the_other() { + // Only the first key has a point; the arm also moves 60 px right while it turns. + let p = Vec2::new(40.0, 10.0); + let start = Affine::translate(100.0, 100.0); + let hinge = start.apply(p); + let end = Affine::translate(60.0, 0.0).mul(&turned(&start, hinge, 90.0)); + let d = arm_doc(inst(start, Some(p)), inst(end, None)); + for f in 0..=10 { + let want = hinge + Vec2::new(6.0 * f as f32, 0.0); + assert!(near(at(&d, f).transform.apply(p), want), "frame {f}"); + } + // A point that is not a number, or is out of reach, counts as none. + assert_eq!(inst(start, Some(Vec2::new(f32::NAN, 0.0))).pivot(), None); + assert_eq!(inst(start, Some(Vec2::new(crate::MAX_PIVOT * 2.0, 0.0))).pivot(), None); +} + +#[test] +fn a_motion_tween_turns_its_target_about_the_point() { + use crate::motion::{MotionTween, Property}; + let p = Vec2::new(40.0, 10.0); + let start = Affine::translate(100.0, 100.0); + let hinge = start.apply(p); + let base = inst(start, Some(p)); + let mut m = MotionTween::new(ElementId(10)); + m.set_key(Property::Rotation, 0, 0.0, 0.0); + m.set_key(Property::Rotation, 10, 90.0, 0.0); + for f in 0..=10 { + let e = m.apply(&base, f as f32); + assert!(near(e.transform.apply(p), hinge), "frame {f}: {:?}", e.transform.apply(p)); + } + assert!((m.apply(&base, 10.0).transform.decompose().rotation.to_degrees() - 90.0).abs() < 1e-3); + // Position keys carry the point with them. + m.set_key(Property::X, 0, 100.0, 100.0); + m.set_key(Property::X, 10, 150.0, 100.0); + assert!(near(m.apply(&base, 10.0).transform.apply(p), hinge + Vec2::new(50.0, 0.0))); + // Without a point the target is placed as before. + let plain = inst(start, None); + assert!(near(m.apply(&plain, 10.0).transform.translation(), Vec2::new(150.0, 100.0))); +} + +#[test] +fn the_point_is_saved_with_the_instance_and_older_files_have_none() { + let e = inst(Affine::IDENTITY, Some(Vec2::new(3.0, -4.5))); + let json = serde_json::to_string(&e).unwrap(); + assert!(json.contains("\"pivot\""), "{json}"); + let back: Element = serde_json::from_str(&json).unwrap(); + assert_eq!(back, e); + let plain = serde_json::to_string(&inst(Affine::IDENTITY, None)).unwrap(); + assert!(!plain.contains("pivot"), "{plain}"); + assert_eq!(serde_json::from_str::(&plain).unwrap().pivot(), None); + // Only an instance keeps one. + let mut shape = square(2, 0.0, 1.0, 1.0); + assert!(!shape.set_pivot(Some(Vec2::ZERO))); + assert_eq!(shape.pivot(), None); + // A new scale or rotation placed about the point leaves the point where it was. + let e = inst(Affine::translate(10.0, 20.0), Some(Vec2::new(5.0, 5.0))); + let m = e.about_pivot(Affine::translate(10.0, 20.0).mul(&Affine::rotate(1.0)).mul(&Affine::scale(2.0, 3.0))); + assert!(near(m.apply(Vec2::new(5.0, 5.0)), Vec2::new(15.0, 25.0))); +} + +fn two_layers() -> Document { + let mut d = Document::default(); + let tl = d.timeline_mut(0); + let mut top = Layer::new(LayerId(70), "top"); + top.keyframes = vec![Arc::new(Keyframe { elements: vec![Arc::new(square(1, 0.0, 10.0, 10.0)), Arc::new(square(2, 5.0, 10.0, 10.0))], ..Keyframe::new(0, 1) })]; + let mut below = Layer::new(LayerId(71), "below"); + below.keyframes = vec![Arc::new(Keyframe { elements: vec![Arc::new(square(3, 0.0, 10.0, 10.0))], ..Keyframe::new(0, 1) })]; + tl.layers = vec![Arc::new(top), Arc::new(below)]; + d +} + +#[test] +fn a_faded_layer_is_one_group_at_its_opacity() { + let mut d = two_layers(); + assert!(evaluate(&d, 0).groups.is_empty(), "opaque layers need no group"); + Arc::make_mut(&mut d.timeline_mut(0).layers[0]).opacity = 0.4; + for dl in [evaluate(&d, 0), evaluate_scene(&d, 0, 0)] { + assert_eq!(dl.groups.len(), 1); + assert_eq!((dl.groups[0].alpha, dl.groups[0].parent, dl.groups[0].blend), (0.4, None, crate::BlendMode::Normal)); + // Back to front: the layer below (no group), then the faded layer's two shapes in it. + let groups: Vec<_> = dl.items.iter().map(|i| (i.element.0, i.group)).collect(); + assert_eq!(groups, vec![(3, None), (1, Some(0)), (2, Some(0))]); + // Each item is as opaque as before on its own: the group fades them together. + assert!(dl.items.iter().all(|i| i.color.opacity() == 1.0)); + assert!((dl.effective_alpha(&dl.items[1]) - 0.4).abs() < 1e-6); + } +} + +#[test] +fn a_folder_fades_the_layers_in_it_and_bad_values_are_tamed() { + let mut d = two_layers(); + let tl = d.timeline_mut(0); + let mut folder = Layer::new(LayerId(72), "folder"); + folder.kind = LayerKind::Folder; + folder.opacity = 0.5; + tl.layers.insert(0, Arc::new(folder)); + Arc::make_mut(&mut tl.layers[1]).parent = Some(LayerId(72)); + Arc::make_mut(&mut tl.layers[1]).opacity = 0.5; + assert!((d.timeline(0).layer_opacity(1) - 0.25).abs() < 1e-6); + assert_eq!(d.timeline(0).layer_opacity(2), 1.0); + let dl = evaluate(&d, 0); + assert_eq!(dl.groups.len(), 1); + assert!((dl.groups[0].alpha - 0.25).abs() < 1e-6); + // Out of range or not a number: clamped, or opaque. + for (bad, want) in [(7.0, 1.0), (-1.0, 0.0), (f32::NAN, 1.0), (f32::INFINITY, 1.0)] { + let mut l = Layer::new(LayerId(1), "l"); + l.opacity = bad; + assert_eq!(l.shown_opacity(), want); + } +} + +#[test] +fn mask_and_guide_layers_ignore_opacity_and_masked_layers_keep_their_clip() { + let mut d = two_layers(); + let tl = d.timeline_mut(0); + Arc::make_mut(&mut tl.layers[0]).kind = LayerKind::Mask; + Arc::make_mut(&mut tl.layers[0]).opacity = 0.3; + Arc::make_mut(&mut tl.layers[1]).parent = Some(LayerId(70)); + Arc::make_mut(&mut tl.layers[1]).opacity = 0.5; + let dl = evaluate(&d, 0); + assert_eq!(dl.groups.len(), 1, "only the masked layer fades"); + assert_eq!((dl.groups[0].alpha, dl.groups[0].clip), (0.5, Some(0))); + assert!(dl.items.iter().filter(|i| i.masks.is_some()).all(|i| i.group.is_none())); + let mut d = two_layers(); + Arc::make_mut(&mut d.timeline_mut(0).layers[0]).kind = LayerKind::Guide; + Arc::make_mut(&mut d.timeline_mut(0).layers[0]).opacity = 0.3; + assert!(evaluate_scene(&d, 0, 0).groups.is_empty()); +} + +#[test] +fn layer_opacity_is_saved_only_when_set_and_older_files_are_opaque() { + let mut l = Layer::new(LayerId(1), "l"); + let plain = serde_json::to_string(&l).unwrap(); + assert!(!plain.contains("opacity"), "{plain}"); + assert_eq!(serde_json::from_str::(&plain).unwrap().opacity, 1.0); + l.opacity = 0.25; + let json = serde_json::to_string(&l).unwrap(); + assert!(json.contains("\"opacity\":0.25"), "{json}"); + assert_eq!(serde_json::from_str::(&json).unwrap(), l); +} diff --git a/crates/doc/src/player_tests.rs b/crates/doc/src/player_tests.rs index 170f4839..5a8b9185 100644 --- a/crates/doc/src/player_tests.rs +++ b/crates/doc/src/player_tests.rs @@ -14,7 +14,7 @@ fn inst(id: u64, symbol: u64, name: &str, x: f32, y: f32, events: Vec A } fn instance(symbol: SymbolId) -> ElementKind { - ElementKind::Symbol { symbol, loop_mode: LoopMode::Loop, first_frame: 0, blend: crate::BlendMode::Normal, filters: Vec::new(), events: Vec::new() } + ElementKind::Symbol { symbol, loop_mode: LoopMode::Loop, first_frame: 0, blend: crate::BlendMode::Normal, filters: Vec::new(), events: Vec::new(), pivot: None } } fn pose(tx: f32, ty: f32, sx: f32, sy: f32, rotation_deg: f32) -> Affine { diff --git a/crates/doc/src/sound_tests.rs b/crates/doc/src/sound_tests.rs index 8cd0c68a..1d19851b 100644 --- a/crates/doc/src/sound_tests.rs +++ b/crates/doc/src/sound_tests.rs @@ -205,7 +205,7 @@ fn nested(kind: SymbolKind, len: u32, inner: &[(u32, u32, Option)], name: String::new(), transform: Default::default(), color: Default::default(), - kind: ElementKind::Symbol { symbol: SymbolId(50), loop_mode, first_frame, blend: Default::default(), filters: Vec::new(), events: Vec::new() }, + kind: ElementKind::Symbol { symbol: SymbolId(50), loop_mode, first_frame, blend: Default::default(), filters: Vec::new(), events: Vec::new(), pivot: None }, })); Arc::new(k) }) diff --git a/crates/doc/src/spring_tests.rs b/crates/doc/src/spring_tests.rs index 9bd6b4a4..75041e4e 100644 --- a/crates/doc/src/spring_tests.rs +++ b/crates/doc/src/spring_tests.rs @@ -14,7 +14,7 @@ const B2: BoneId = BoneId(21); const SEG: SymbolId = SymbolId(1); fn instance(id: ElementId, x: f32, y: f32) -> Arc { - let kind = ElementKind::Symbol { symbol: SEG, loop_mode: LoopMode::Loop, first_frame: 0, blend: BlendMode::Normal, filters: Vec::new(), events: Vec::new() }; + let kind = ElementKind::Symbol { symbol: SEG, loop_mode: LoopMode::Loop, first_frame: 0, blend: BlendMode::Normal, filters: Vec::new(), events: Vec::new(), pivot: None }; Arc::new(Element { id, name: String::new(), transform: Affine::translate(x, y), color: ColorEffect::default(), kind }) } diff --git a/crates/doc/src/templates.rs b/crates/doc/src/templates.rs index 988308f2..84444cd9 100644 --- a/crates/doc/src/templates.rs +++ b/crates/doc/src/templates.rs @@ -233,7 +233,7 @@ fn lip_sync() -> Document { name: "mouth".into(), transform: Affine::translate(cx, cy + 130.0), color: ColorEffect::default(), - kind: ElementKind::Symbol { symbol: sym_id, loop_mode: LoopMode::SingleFrame, first_frame: 0, blend: crate::BlendMode::Normal, filters: Vec::new(), events: Vec::new() }, + kind: ElementKind::Symbol { symbol: sym_id, loop_mode: LoopMode::SingleFrame, first_frame: 0, blend: crate::BlendMode::Normal, filters: Vec::new(), events: Vec::new(), pivot: None }, }); let layers = vec![ layer(&mut d, "Face guide", LayerKind::Guide, GUIDE, FRAMES, guides), diff --git a/crates/engine/src/cmds_draw.rs b/crates/engine/src/cmds_draw.rs index 182ff8c6..747f7a9f 100644 --- a/crates/engine/src/cmds_draw.rs +++ b/crates/engine/src/cmds_draw.rs @@ -26,7 +26,7 @@ pub fn specs() -> Vec { c("element.select", "Select Elements", "", None, "{ids: [..], add?: bool, toggle?: bool, layer?} selects elements on any visible, unlocked layer at the playhead (ids are unique; `layer` looks only there); `toggle` takes each one that is selected out of the selection and adds the others (Shift+Space on a stage element); the active layer becomes the first one's unless it has some of them", false, select), c("element.pick", "Select at Point", "", None, "{x, y, add?: bool, view?: stage|camera} the topmost element there on a visible, unlocked layer; `add` (Shift) adds it to the selection, or lets go of it, on any layer; with `view: camera` the point is on the movie's picture as the camera shows it (each layer through its depth)", false, pick), c("element.translate", "Move", "", None, "{dx, dy, snap?, from?: [x, y]} moves the selection, on every layer; with `snap` (a distance) one of its corners or ends, or its box's corners or centre (the nearest to `from`), then snaps within that distance by the snap engine's priority (ADR 0076): a point, guide, line or fill edge of the rest, the grid, a whole pixel", true, translate), - c("element.set_transform", "Transform", "", None, "{x?, y?, sx?, sy?, rotation? (degrees)}", true, |s, p| s.each_layer(true, |s| set_transform(s, p))), + c("element.set_transform", "Transform", "", None, "{x?, y?, sx?, sy?, rotation? (degrees)} x and y place the registration point. A new scale or rotation alone is applied about a symbol instance's transformation point when it has one (modify.transformation_point), else about the registration point", true, |s, p| s.each_layer(true, |s| set_transform(s, p))), c("element.set_fill", "Fill Colour", "", None, "{color: \"#rrggbb\" | \"#rrggbbaa\" | null, or on: true | false} (the alpha is the fill's own; 00 is a clear fill, not the same as null. on: false turns the fill off like null; on: true puts back the fill each shape had before, else the tool's fill colour. With only raw lines selected the fill goes to what they surround)", true, |s, p| s.each_layer(false, |s| set_fill(s, p))), c("element.set_stroke", "Stroke", "", None, "{on?: true | false (false removes the stroke like color: null; true puts back the stroke each shape had before, else the tool's), color?: \"#rrggbb\" | \"#rrggbbaa\" | null, width?, profile?: uniform|taper_both|taper_start|taper_end|bulge|pinch | [[t, left, right], ..], cap?, join?, miter?, style?, dash?, dash_offset?, dot_spacing? (as stroke.set_style)}", true, |s, p| s.each_layer(false, |s| set_stroke(s, p))), c("element.set_alpha", "Alpha", "", None, "{alpha: 0..1} sets the alpha multiplier and keeps the rest of the colour effect (None becomes Alpha; Brightness and Tint become Advanced below 1)", true, |s, p| s.each_layer(true, |s| set_alpha(s, p))), @@ -377,7 +377,10 @@ fn set_transform(s: &mut Session, p: &Value) -> Result { if let Some(v) = rot { d.rotation = v.to_radians(); } - e.transform = d.compose(); + // A new scale or rotation turns an instance about its transformation point (ADR + // 0111); a position given places the registration point, as always. + let m = d.compose(); + e.transform = if x.is_none() && y.is_none() { e.about_pivot(m) } else { m }; } // A raw drawing turns and scales as one shape, about the centre of its pieces (#297): every // piece takes the change that gives its first piece the values asked for. @@ -979,7 +982,7 @@ pub(crate) fn convert_to_symbol(s: &mut Session, p: &Value) -> Result { name: String::new(), transform: Affine::translate(center.x, center.y), color: ColorEffect::default(), - kind: ElementKind::Symbol { symbol: sym_id, loop_mode: LoopMode::Loop, first_frame: 0, blend: anicraft_doc::BlendMode::Normal, filters: Vec::new(), events: Vec::new() }, + kind: ElementKind::Symbol { symbol: sym_id, loop_mode: LoopMode::Loop, first_frame: 0, blend: anicraft_doc::BlendMode::Normal, filters: Vec::new(), events: Vec::new(), pivot: None }, }; // Children are stored relative to the registration point (the selection centre). let to_local = Affine::translate(-center.x, -center.y); @@ -1203,7 +1206,7 @@ fn place_symbol(s: &mut Session, sym: SymbolId, x: f32, y: f32) -> Result Vec { ), c("layer.set_color", "Layer Colour", "", None, "{color: \"#rrggbb\", layer?} the layer's colour: its outlines in outline mode and its bar on the timeline", true, set_color), c("layer.set_height", "Layer Height", "", None, "{height: 100 | 200 | 300 (percent of a normal row), layer?} the layer's row height on the timeline", true, set_height), + c( + "layer.set_opacity", + "Layer Opacity", + "", + None, + "{opacity: 0..100 (percent), layer?} how strongly the layer shows, in the movie and every export: its artwork is drawn together and then faded, so its overlapping parts don't show through each other. A folder's opacity fades the layers in it; mask and guide artwork ignore it (ADR 0111) → {layer, opacity}", + true, + set_opacity, + ), c( "layer.set_mask", "Mask Type", @@ -45,11 +54,11 @@ pub fn specs() -> Vec { "Layer Properties", "Modify/Timeline", None, - "{layer?, name?, type?: normal|mask|masked|guide|guided, mask?: coverage|alpha|luminance (a mask layer's mask type), color?, outline?: bool (view as outlines), height?: 100|200|300, visible?, locked?, onion?} sets several at once, as one undo step; answers with the layer's properties", + "{layer?, name?, type?: normal|mask|masked|guide|guided, mask?: coverage|alpha|luminance (a mask layer's mask type), color?, outline?: bool (view as outlines), height?: 100|200|300, opacity?: 0..100 (percent), visible?, locked?, onion?} sets several at once, as one undo step; answers with the layer's properties", true, set_properties, ), - c("layer.properties", "Get Layer Properties", "", None, "{layer?} the layer's name, type, mask type (mask layers), colour, outline, height (percent), visible, locked and onion", false, |s, p| properties(s, layer_id(s, p)?)), + c("layer.properties", "Get Layer Properties", "", None, "{layer?} the layer's name, type, mask type (mask layers), colour, outline, height (percent), opacity (percent), visible, locked and onion", false, |s, p| properties(s, layer_id(s, p)?)), ] } @@ -112,6 +121,28 @@ fn set_height(s: &mut Session, p: &Value) -> Result { Ok(json!({"height": u32::from(l.height()) * 100})) } +/// `opacity` in percent (0 to 100) as a fraction. +fn opacity_param(p: &Value) -> Result> { + match opt_f32(p, "opacity")? { + None => Ok(None), + Some(o) if o.is_finite() && (0.0..=100.0).contains(&o) => Ok(Some(o / 100.0)), + Some(_) => Err(EngineError::Param("param 'opacity' must be between 0 and 100 (percent)".into())), + } +} + +/// A layer's opacity in percent, as commands answer it (rounded to a hundredth of a percent). +fn opacity_percent(l: &Layer) -> f64 { + (f64::from(l.shown_opacity()) * 10_000.0).round() / 100.0 +} + +fn set_opacity(s: &mut Session, p: &Value) -> Result { + let opacity = opacity_param(p)?.ok_or_else(|| EngineError::Param("param 'opacity' (0 to 100, percent) is required".into()))?; + let id = layer_id(s, p)?; + let l = s.layer_mut(Some(id))?; + l.opacity = opacity; + Ok(json!({"layer": id.0, "opacity": opacity_percent(l)})) +} + /// `mask`: a mask type's key. fn mask_param(p: &Value) -> Result> { opt_str(p, "mask")?.map(|k| MaskMode::from_key(k).ok_or_else(|| EngineError::Param(format!("'mask' is coverage, alpha or luminance, not '{k}'")))).transpose() @@ -139,6 +170,7 @@ fn set_properties(s: &mut Session, p: &Value) -> Result { let color = opt_color(p, "color")?; let outline = opt_bool(p, "outline")?; let height = height_param(p)?; + let opacity = opacity_param(p)?; let mask = mask_param(p)?; let (visible, locked, onion) = (opt_bool(p, "visible")?, opt_bool(p, "locked")?, opt_bool(p, "onion")?); if let Some(ty) = ty { @@ -166,6 +198,9 @@ fn set_properties(s: &mut Session, p: &Value) -> Result { if let Some(h) = height { l.height_rows = h; } + if let Some(o) = opacity { + l.opacity = o; + } if let Some(v) = visible { l.visible = v; } @@ -189,6 +224,7 @@ fn properties(s: &Session, id: LayerId) -> Result { "color": l.color.to_hex(), "outline": l.outline, "height": u32::from(l.height()) * 100, + "opacity": opacity_percent(l), "visible": l.visible, "locked": l.locked, "onion": l.onion, diff --git a/crates/engine/src/cmds_layer_tests.rs b/crates/engine/src/cmds_layer_tests.rs index 92006344..2f0084f9 100644 --- a/crates/engine/src/cmds_layer_tests.rs +++ b/crates/engine/src/cmds_layer_tests.rs @@ -154,7 +154,7 @@ fn layer_properties_set_everything_as_one_step_or_nothing() { let (mut s, top, bottom) = two_walks(); let undo = s.history.undo_len(); let r = run(&mut s, "layer.set_properties", json!({"layer": bottom.0, "name": "Sky", "color": "#123456", "outline": true, "height": 200, "locked": true, "visible": false, "onion": false, "type": "guide"})); - assert_eq!(r, json!({"layer": bottom.0, "name": "Sky", "type": "guide", "mask": null, "color": "#123456", "outline": true, "height": 200, "visible": false, "locked": true, "onion": false})); + assert_eq!(r, json!({"layer": bottom.0, "name": "Sky", "type": "guide", "mask": null, "color": "#123456", "outline": true, "height": 200, "opacity": 100.0, "visible": false, "locked": true, "onion": false})); assert_eq!(s.history.undo_len(), undo + 1, "one undo step"); assert_eq!(run(&mut s, "layer.properties", json!({"layer": bottom.0})), r); // The same type again changes nothing (a masked layer stays masked by the same mask). diff --git a/crates/engine/src/cmds_modify.rs b/crates/engine/src/cmds_modify.rs index 22fc6eac..14e5ddcb 100644 --- a/crates/engine/src/cmds_modify.rs +++ b/crates/engine/src/cmds_modify.rs @@ -29,6 +29,24 @@ pub fn specs() -> Vec { false, transform_origin, ), + c( + "modify.transformation_point", + "Set Transformation Point", + "", + None, + "{x, y} (stage space, as modify.transform) moves the selected symbol instances' transformation point there (the white circle Free Transform shows): what each then turns, scales and skews about with Free Transform, the Modify › Transform commands, the Properties fields and in tweens. It is kept with the instance, in the instance's own space, so it travels with it. Anything else has no point of its own to keep (ADR 0111) → {set, x, y}", + true, + set_transformation_point, + ), + c( + "modify.reset_transformation_point", + "Reset Transformation Point", + "Modify/Transform", + None, + "{} puts the selected symbol instances' transformation point back at the centre (none kept: tools use the centre of the box, tweens the registration point) → {reset}", + true, + reset_transformation_point, + ), c("modify.remove_transform", "Remove Transform", "Modify/Transform", Some("Ctrl+Shift+Z"), "{}", true, |s, p| s.each_layer(true, |s| remove_transform(s, p))), c("align.left", "Left", "Modify/Align", Some("Ctrl+Alt+1"), "{to_stage?}", true, |s, p| align(s, p, Edge::Left)), c("align.hcenter", "Horizontal Center", "Modify/Align", Some("Ctrl+Alt+2"), "{to_stage?}", true, |s, p| align(s, p, Edge::HCenter)), @@ -393,11 +411,105 @@ fn about_center(s: &mut Session, p: &Value, m: Affine) -> Result { if b.is_empty() { return Err(EngineError::State("nothing is selected".into())); } - let c = b.center(); + // One instance with a transformation point of its own turns about it (ADR 0111). + let c = s.transformation_point().filter(|(_, own)| *own).map_or(b.center(), |(at, _)| at); let full = Affine::translate(c.x, c.y).mul(&m).mul(&Affine::translate(-c.x, -c.y)); s.each_layer(true, |s| Ok(json!({"transformed": apply(s, &full)?}))) } +/// `modify.transformation_point`: the selected instances' point, given in stage space, kept in +/// each instance's own. +fn set_transformation_point(s: &mut Session, p: &Value) -> Result { + let at = Vec2::new(f32_req(p, "x")?, f32_req(p, "y")?); + if !at.is_finite() { + return Err(EngineError::Param("params 'x' and 'y' must be numbers".into())); + } + change_transformation_point(s, Some(at)).map(|n| json!({"set": n, "x": at.x, "y": at.y})) +} + +fn reset_transformation_point(s: &mut Session, _: &Value) -> Result { + change_transformation_point(s, None).map(|n| json!({"reset": n})) +} + +/// Sets (stage space) or clears the transformation point of every selected instance, on every +/// layer the selection is on; answers how many. +fn change_transformation_point(s: &mut Session, at: Option) -> Result { + let keeps = |e: &Element| matches!(e.kind, ElementKind::Symbol { .. }); + if s.selection.is_empty() { + return Err(EngineError::State("nothing is selected".into())); + } + if !s.selected_elements().iter().any(|(_, e)| keeps(e)) { + return Err(EngineError::State("only a symbol instance keeps a transformation point: select one (Modify › Convert to Symbol makes one)".into())); + } + let mut n = 0; + s.each_layer(false, |s| { + if !s.selected_elements().iter().any(|(_, e)| keeps(e)) { + return Ok(Value::Null); + } + for e in s.selected_elements_mut()?.into_iter().filter(|e| keeps(e)) { + let own = match at { + None => None, + Some(at) => { + let inv = e.transform.inverse().ok_or_else(|| EngineError::State("the instance is flattened to nothing: it has no point to place".into()))?; + let own = inv.apply(at); + if !own.is_finite() || own.x.abs() > anicraft_doc::MAX_PIVOT || own.y.abs() > anicraft_doc::MAX_PIVOT { + return Err(EngineError::Param("the point is too far from the instance".into())); + } + Some(own) + } + }; + e.set_pivot(own); + n += 1; + } + Ok(Value::Null) + })?; + Ok(n) +} + +impl Session { + /// The point Free Transform shows and turns the selection about (stage space), and whether + /// it is one the selected instance keeps (ADR 0111): a single selected element's own + /// transformation point when it has one, else the centre of its box (which its transform + /// carries); for several elements, the centre of the selection's bounds. `None` with + /// nothing selected. + pub fn transformation_point(&self) -> Option<(Vec2, bool)> { + let (frame, bounds) = self.transform_frame()?; + if let [(_, e)] = self.selected_elements().as_slice() + && let Some(p) = e.pivot() + { + let at = e.transform.apply(p); + if at.is_finite() { + return Some((at, true)); + } + } + Some((frame.apply(bounds.center()), false)) + } + + /// The selection's box as Free Transform draws it (ADR 0111): a box and the transform that + /// places it on the stage. One selected element shows its own box, turned, scaled and + /// skewed as it is (the box of what it draws at the playhead, in its own space, under its + /// transform); anything else (several elements, raw pieces, a flattened element) the + /// upright bounds of the selection under the identity. `None` with nothing to show. + pub fn transform_frame(&self) -> Option<(Affine, Rect)> { + let selected = self.selected_elements(); + if let [(layer, e)] = selected.as_slice() + && !matches!(e.kind, ElementKind::Camera) + && let Some(inv) = e.transform.inverse() + { + let mut own = Rect::EMPTY; + for item in self.display_list().items.iter().filter(|i| i.layer == *layer && i.element == e.id) { + let pad = item.stroke.as_ref().map_or(0.0, anicraft_doc::Stroke::reach); + own = own.union(&item.path.bounds().inflate(pad).transformed(&inv.mul(&item.transform))); + } + if !own.is_empty() && own.min.is_finite() && own.max.is_finite() { + return Some((e.transform, own)); + } + } + let b = self.selection_bounds(); + (!b.is_empty()).then_some((Affine::IDENTITY, b)) + } +} + /// `modify.transform_origin`: sets the mode, or moves to the next one. fn transform_origin(s: &mut Session, p: &Value) -> Result { let mode = match opt_str(p, "mode")? { diff --git a/crates/engine/src/editing.rs b/crates/engine/src/editing.rs index f7db5935..43a6c919 100644 --- a/crates/engine/src/editing.rs +++ b/crates/engine/src/editing.rs @@ -384,7 +384,7 @@ fn placed(doc: &mut Document, timeline: Timeline, transform: Affine, frame: u32, name: String::new(), transform, color, - kind: ElementKind::Symbol { symbol, loop_mode: LoopMode::SingleFrame, first_frame: frame, blend: Default::default(), filters: Vec::new(), events: Vec::new() }, + kind: ElementKind::Symbol { symbol, loop_mode: LoopMode::SingleFrame, first_frame: frame, blend: Default::default(), filters: Vec::new(), events: Vec::new(), pivot: None }, })); let mut layer = Layer::new(LayerId(doc.alloc_id()), ""); layer.keyframes.push(Arc::new(k)); diff --git a/crates/engine/src/find_tests.rs b/crates/engine/src/find_tests.rs index 543f0fc5..2fdb7bc8 100644 --- a/crates/engine/src/find_tests.rs +++ b/crates/engine/src/find_tests.rs @@ -54,7 +54,7 @@ impl Build { name: name.into(), transform: Affine::translate(100.0, 50.0), color: ColorEffect::default(), - kind: ElementKind::Symbol { symbol, loop_mode: LoopMode::Loop, first_frame: 0, blend: Default::default(), filters: Vec::new(), events: Vec::new() }, + kind: ElementKind::Symbol { symbol, loop_mode: LoopMode::Loop, first_frame: 0, blend: Default::default(), filters: Vec::new(), events: Vec::new(), pivot: None }, } } /// A layer with keyframes `(start, duration, label, elements)`. diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index c4ceea2a..9ccb657d 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -23,6 +23,8 @@ mod cmds_group; mod cmds_modify; #[cfg(test)] mod origin_tests; +#[cfg(test)] +mod pivot_tests; mod cmds_motion; mod cmds_retime; mod cmds_hints; diff --git a/crates/engine/src/pivot_tests.rs b/crates/engine/src/pivot_tests.rs new file mode 100644 index 00000000..086bdd52 --- /dev/null +++ b/crates/engine/src/pivot_tests.rs @@ -0,0 +1,239 @@ +//! The transformation point an instance keeps, the box Free Transform draws round one +//! element, and layer opacity (ADR 0111; issues #302, #280, #178, #183, #175, #279). + +use crate::Session; +use anicraft_doc::{ElementId, evaluate_layer_elements}; +use anicraft_geom::{Affine, Rect, 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}")) +} + +/// A 100 × 20 arm as a symbol instance, its box from (100, 100) to (200, 120), selected. Its +/// registration point is the box's centre (150, 110). +fn arm() -> (Session, ElementId) { + let mut s = Session::new(anicraft_doc::Document::default()); + run(&mut s, "draw.rect", json!({"x": 100, "y": 100, "w": 100, "h": 20, "fill": "#222222", "stroke": null, "object": true})); + let id = ElementId(run(&mut s, "modify.convert_to_symbol", json!({"name": "Arm"}))["instance"].as_u64().unwrap()); + assert_eq!(s.element_bounds(id), Rect::new(100.0, 100.0, 200.0, 120.0)); + (s, id) +} + +fn el(s: &Session, id: ElementId) -> std::sync::Arc { + s.visible_elements().into_iter().find(|e| e.id == id).expect("the element is there") +} + +/// Where the instance's kept point is on the stage. +fn point(s: &Session, id: ElementId) -> Vec2 { + let e = el(s, id); + e.transform.apply(e.pivot().expect("the instance keeps a point")) +} + +fn near(a: Vec2, b: Vec2) -> bool { + a.distance(b) < 0.01 +} + +#[test] +fn the_point_starts_at_the_centre_and_is_kept_in_the_instances_own_space() { + let (mut s, id) = arm(); + assert_eq!(s.transformation_point(), Some((Vec2::new(150.0, 110.0), false)), "the centre of the box until it is moved"); + assert_eq!(run(&mut s, "modify.transformation_point", json!({"x": 100, "y": 110})), json!({"set": 1, "x": 100.0, "y": 110.0})); + assert_eq!(s.transformation_point(), Some((Vec2::new(100.0, 110.0), true))); + // Kept relative to the registration point (150, 110), so it travels with the instance. + assert_eq!(el(&s, id).pivot(), Some(Vec2::new(-50.0, 0.0))); + run(&mut s, "element.translate", json!({"dx": 30, "dy": -10})); + assert!(near(point(&s, id), Vec2::new(130.0, 100.0))); + // Outside the box is fine (#178), and a scaled, turned instance still gets the stage point asked for. + run(&mut s, "modify.transform", json!({"a": 0.0, "b": 2.0, "c": -2.0, "d": 0.0, "e": 400.0, "f": 0.0})); + run(&mut s, "modify.transformation_point", json!({"x": -500, "y": 900})); + assert!(near(point(&s, id), Vec2::new(-500.0, 900.0))); + // Back to the centre. + assert_eq!(run(&mut s, "modify.reset_transformation_point", json!({})), json!({"reset": 1})); + assert_eq!(el(&s, id).pivot(), None); + assert!(!s.transformation_point().unwrap().1); + // Every change is one undo step. + run(&mut s, "edit.undo", json!({})); + assert!(near(point(&s, id), Vec2::new(-500.0, 900.0))); +} + +#[test] +fn only_an_instance_keeps_a_point_and_bad_points_are_refused() { + let mut s = Session::new(anicraft_doc::Document::default()); + assert!(s.execute("modify.transformation_point", &json!({"x": 1, "y": 2})).is_err(), "nothing selected"); + assert!(s.execute("modify.reset_transformation_point", &json!({})).is_err()); + run(&mut s, "draw.rect", json!({"x": 0, "y": 0, "w": 50, "h": 50, "object": true})); + let e = s.execute("modify.transformation_point", &json!({"x": 1, "y": 2})).unwrap_err().to_string(); + assert!(e.contains("symbol instance"), "{e}"); + let (mut s, id) = arm(); + for bad in [json!({}), json!({"x": 1}), json!({"x": "a", "y": 2}), json!({"x": 1e30, "y": 0}), json!({"x": null, "y": null})] { + assert!(s.execute("modify.transformation_point", &bad).is_err(), "{bad}"); + } + assert_eq!(el(&s, id).pivot(), None, "a refused point changes nothing"); + assert!(!s.can_undo() || el(&s, id).pivot().is_none()); +} + +#[test] +fn rotating_turns_the_instance_about_its_point() { + // The point at the arm's left end (100, 110): Rotate 90° CW swings the arm down from it. + let (mut s, id) = arm(); + run(&mut s, "modify.transformation_point", json!({"x": 100, "y": 110})); + run(&mut s, "modify.rotate_cw", json!({})); + assert!(near(point(&s, id), Vec2::new(100.0, 110.0)), "the point stays put"); + let b = s.element_bounds(id); + assert!((b.min.x - 90.0).abs() < 0.01 && (b.max.x - 110.0).abs() < 0.01 && (b.min.y - 110.0).abs() < 0.01 && (b.max.y - 210.0).abs() < 0.01, "{b:?}"); + // Flipping mirrors it across the point. + run(&mut s, "modify.flip_v", json!({})); + let b = s.element_bounds(id); + assert!((b.min.y - 10.0).abs() < 0.01 && (b.max.y - 110.0).abs() < 0.01, "{b:?}"); + // Without a point of its own it turns about the centre of its box, as before. + let (mut s, id) = arm(); + run(&mut s, "modify.rotate_cw", json!({})); + assert!(near(s.element_bounds(id).center(), Vec2::new(150.0, 110.0))); +} + +#[test] +fn the_properties_fields_turn_and_scale_about_the_point() { + let (mut s, id) = arm(); + run(&mut s, "modify.transformation_point", json!({"x": 100, "y": 110})); + // Rotation 30°: analytic, the registration point (50 px along the arm) swings round the point. + run(&mut s, "element.set_transform", json!({"rotation": 30})); + let (sin, cos) = 30f32.to_radians().sin_cos(); + assert!(near(point(&s, id), Vec2::new(100.0, 110.0))); + assert!(near(el(&s, id).transform.translation(), Vec2::new(100.0 + 50.0 * cos, 110.0 + 50.0 * sin))); + assert!((el(&s, id).transform.decompose().rotation.to_degrees() - 30.0).abs() < 1e-3); + // Scale: the point stays, the rotation is kept. + run(&mut s, "element.set_transform", json!({"sx": 2, "sy": 0.5})); + assert!(near(point(&s, id), Vec2::new(100.0, 110.0))); + let d = el(&s, id).transform.decompose(); + assert!((d.sx - 2.0).abs() < 1e-4 && (d.sy - 0.5).abs() < 1e-4 && (d.rotation.to_degrees() - 30.0).abs() < 1e-3); + // A position places the registration point, as always. + run(&mut s, "element.set_transform", json!({"x": 10, "y": 20})); + assert!(near(el(&s, id).transform.translation(), Vec2::new(10.0, 20.0))); + // No point: about the registration point, as before. + let (mut s, id) = arm(); + run(&mut s, "element.set_transform", json!({"rotation": 90})); + assert!(near(el(&s, id).transform.translation(), Vec2::new(150.0, 110.0))); +} + +#[test] +fn dragging_the_point_is_one_undo_step() { + let (mut s, id) = arm(); + s.begin_gesture("Move Transformation Point"); + for i in 0..30 { + run(&mut s, "modify.transformation_point", json!({"x": 150.0 - i as f32, "y": 110.0 + i as f32})); + } + s.end_gesture(); + assert!(near(point(&s, id), Vec2::new(121.0, 139.0))); + run(&mut s, "edit.undo", json!({})); + assert_eq!(el(&s, id).pivot(), None, "one undo takes the whole drag back"); + assert!(!s.can_undo() || s.execute("edit.undo", &json!({})).is_ok()); +} + +#[test] +fn a_tween_made_with_the_tools_swings_about_the_point() { + // Key the arm at frame 0, turn it 90° about its left end at frame 10, tween between. + let (mut s, id) = arm(); + run(&mut s, "modify.transformation_point", json!({"x": 100, "y": 110})); + run(&mut s, "timeline.insert_frame", json!({"count": 10})); + run(&mut s, "timeline.goto", json!({"frame": 10})); + run(&mut s, "timeline.insert_keyframe", json!({})); + run(&mut s, "element.select", json!({"ids": [id.0]})); + run(&mut s, "modify.rotate_cw", json!({})); + run(&mut s, "timeline.goto", json!({"frame": 0})); + run(&mut s, "timeline.create_tween", json!({})); + let layer = s.doc.timeline(s.scene).layer(s.layer).unwrap().clone(); + for f in 0..=10 { + let (_, els) = evaluate_layer_elements(&layer, f).unwrap(); + let e = els.iter().find(|e| e.id == id).unwrap(); + let at = e.transform.apply(e.pivot().unwrap()); + assert!(near(at, Vec2::new(100.0, 110.0)), "frame {f}: the hinge is at {at:?}"); + assert!((e.transform.decompose().rotation.to_degrees() - 9.0 * f as f32).abs() < 0.01, "frame {f}"); + } +} + +#[test] +fn one_element_shows_its_own_box_turned_and_several_show_an_upright_one() { + let (mut s, id) = arm(); + assert_eq!(s.transform_frame(), Some((Affine::translate(150.0, 110.0), Rect::new(-50.0, -10.0, 50.0, 10.0)))); + // Turned 30° about its centre: the same box, under the instance's transform (#175). + let turn = Affine::translate(150.0, 110.0).mul(&Affine::rotate(30f32.to_radians())).mul(&Affine::translate(-150.0, -110.0)); + let [a, b, c, d, e, f] = turn.m; + run(&mut s, "modify.transform", json!({"a": a, "b": b, "c": c, "d": d, "e": e, "f": f})); + let (frame, own) = s.transform_frame().unwrap(); + assert_eq!(frame, el(&s, id).transform); + assert!(near(own.min, Vec2::new(-50.0, -10.0)) && near(own.max, Vec2::new(50.0, 10.0)), "{own:?}"); + assert!((frame.decompose().rotation.to_degrees() - 30.0).abs() < 1e-3); + // The upright bounds are bigger: the turned box hugs the arm. + let upright = s.selection_bounds(); + assert!(upright.max.y - upright.min.y > 60.0); + // A stretch along the box's own x axis (what its side handle does) keeps the turn and + // changes only the arm's length: no skew appears. + let along = frame.mul(&Affine::scale(1.5, 1.0)).mul(&frame.inverse().unwrap()); + let [a, b, c, d, e, f] = along.m; + run(&mut s, "modify.transform", json!({"a": a, "b": b, "c": c, "d": d, "e": e, "f": f})); + let dec = el(&s, id).transform.decompose(); + assert!((dec.sx - 1.5).abs() < 1e-4 && (dec.sy - 1.0).abs() < 1e-4 && dec.skew.abs() < 1e-4 && (dec.rotation.to_degrees() - 30.0).abs() < 1e-3, "{dec:?}"); + // Two elements: the upright bounds of both, and their centre as the point. + run(&mut s, "draw.rect", json!({"x": 300, "y": 300, "w": 40, "h": 40, "object": true})); + run(&mut s, "edit.select_all", json!({})); + let (frame, b) = s.transform_frame().unwrap(); + assert_eq!((frame, b), (Affine::IDENTITY, s.selection_bounds())); + assert_eq!(s.transformation_point(), Some((b.center(), false))); + run(&mut s, "edit.deselect", json!({})); + assert_eq!((s.transform_frame(), s.transformation_point()), (None, None)); +} + +#[test] +fn the_point_survives_a_save_and_copies_with_the_instance() { + let dir = std::env::temp_dir().join(format!("anicraft-pivot-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("arm.anicraft"); + let (mut s, id) = arm(); + run(&mut s, "modify.transformation_point", json!({"x": 100, "y": 110})); + run(&mut s, "layer.set_opacity", json!({"opacity": 40})); + run(&mut s, "file.save", json!({"path": path.display().to_string()})); + let mut t = Session::default(); + run(&mut t, "file.open", json!({"path": path.display().to_string()})); + assert_eq!(s.doc, t.doc); + assert_eq!(el(&t, id).pivot(), Some(Vec2::new(-50.0, 0.0))); + assert_eq!(t.doc.timeline(0).layers[0].opacity, 0.4); + let _ = std::fs::remove_dir_all(&dir); + // A copy keeps the point. + run(&mut s, "edit.copy", json!({})); + run(&mut s, "edit.paste_in_place", json!({})); + let copy = s.selected_elements().into_iter().map(|(_, e)| e).find(|e| e.id != id).expect("the pasted instance is selected"); + assert_eq!(copy.pivot(), Some(Vec2::new(-50.0, 0.0))); +} + +#[test] +fn layer_opacity_is_set_read_checked_and_undone() { + let (mut s, _) = arm(); + let layer = s.layer; + assert_eq!(run(&mut s, "layer.properties", json!({}))["opacity"], json!(100.0)); + assert_eq!(run(&mut s, "layer.set_opacity", json!({"opacity": 37.5})), json!({"layer": layer.0, "opacity": 37.5})); + assert_eq!(s.doc.timeline(0).layers[0].opacity, 0.375); + assert_eq!(run(&mut s, "layer.properties", json!({}))["opacity"], json!(37.5)); + // What the stage and every export draw: the layer is one group at that opacity. + let dl = s.display_list(); + assert_eq!(dl.groups.len(), 1); + assert_eq!(dl.groups[0].alpha, 0.375); + assert!(anicraft_doc::evaluate(&s.doc, 0).groups.iter().any(|g| g.alpha == 0.375)); + // With the other Layer Properties, as one step. + let v = run(&mut s, "layer.set_properties", json!({"opacity": 80, "name": "Faded"})); + assert_eq!((v["opacity"].clone(), v["name"].clone()), (json!(80.0), json!("Faded"))); + run(&mut s, "edit.undo", json!({})); + assert_eq!(s.doc.timeline(0).layers[0].opacity, 0.375); + run(&mut s, "edit.undo", json!({})); + assert_eq!(s.doc.timeline(0).layers[0].opacity, 1.0); + for bad in [json!({}), json!({"opacity": -1}), json!({"opacity": 100.5}), json!({"opacity": "half"}), json!({"opacity": 50, "layer": 999_999})] { + assert!(s.execute("layer.set_opacity", &bad).is_err(), "{bad}"); + } + assert!(s.execute("layer.set_properties", &json!({"opacity": 500})).is_err()); + assert_eq!(s.doc.timeline(0).layers[0].opacity, 1.0); + // 0 and 100 are the ends. + run(&mut s, "layer.set_opacity", json!({"opacity": 0})); + assert_eq!(s.display_list().groups[0].alpha, 0.0); + run(&mut s, "layer.set_opacity", json!({"opacity": 100})); + assert!(s.display_list().groups.is_empty()); +} diff --git a/crates/engine/src/tests_bone.rs b/crates/engine/src/tests_bone.rs index a5c4ce4f..ae46e6a8 100644 --- a/crates/engine/src/tests_bone.rs +++ b/crates/engine/src/tests_bone.rs @@ -32,7 +32,7 @@ pub(crate) fn three_bars() -> Session { k }); d.library.push(Arc::new(Symbol { id: bar, name: "Bar".into(), kind: SymbolKind::Graphic, linkage: None, scale_grid_kept: None, scale_grid: None, timeline: Timeline { layers: vec![Arc::new(inner)] } })); - let inst = |id: u64, x: f32| Arc::new(Element { id: ElementId(id), name: String::new(), transform: Affine::translate(x, 100.0), color: ColorEffect::default(), kind: ElementKind::Symbol { symbol: bar, loop_mode: LoopMode::Loop, first_frame: 0, blend: BlendMode::Normal, filters: Vec::new(), events: Vec::new() } }); + let inst = |id: u64, x: f32| Arc::new(Element { id: ElementId(id), name: String::new(), transform: Affine::translate(x, 100.0), color: ColorEffect::default(), kind: ElementKind::Symbol { symbol: bar, loop_mode: LoopMode::Loop, first_frame: 0, blend: BlendMode::Normal, filters: Vec::new(), events: Vec::new(), pivot: None } }); let shape = Arc::new(Element { id: ElementId(SHAPE), name: String::new(), transform: Affine::translate(100.0, 250.0), color: ColorEffect::default(), kind: ElementKind::Shape(Shape::filled(Path::rect(0.0, 0.0, 20.0, 20.0), Paint::Solid(Rgba::BLACK))) }); let l = Arc::make_mut(&mut d.timeline_mut(0).layers[0]); l.keyframes = vec![Arc::new({ diff --git a/crates/engine/src/tests_mixed_bone.rs b/crates/engine/src/tests_mixed_bone.rs index 754bacbe..0eb03f72 100644 --- a/crates/engine/src/tests_mixed_bone.rs +++ b/crates/engine/src/tests_mixed_bone.rs @@ -53,7 +53,7 @@ pub(crate) fn parts() -> Session { let shape = Shape { merge: true, ..Shape::filled(path, Paint::Solid(Rgba::hex(color))) }; Arc::new(Element { id: ElementId(id), name: String::new(), transform: Affine::translate(x, y), color: ColorEffect::default(), kind: ElementKind::Shape(shape) }) }; - let inst = Arc::new(Element { id: ElementId(HEAD), name: String::new(), transform: Affine::translate(200.0, 110.0), color: ColorEffect::default(), kind: ElementKind::Symbol { symbol: head, loop_mode: LoopMode::Loop, first_frame: 0, blend: BlendMode::Normal, filters: Vec::new(), events: Vec::new() } }); + let inst = Arc::new(Element { id: ElementId(HEAD), name: String::new(), transform: Affine::translate(200.0, 110.0), color: ColorEffect::default(), kind: ElementKind::Symbol { symbol: head, loop_mode: LoopMode::Loop, first_frame: 0, blend: BlendMode::Normal, filters: Vec::new(), events: Vec::new(), pivot: None } }); let l = Arc::make_mut(&mut d.timeline_mut(0).layers[0]); l.keyframes = vec![Arc::new({ let mut k = Keyframe::new(0, 20); diff --git a/crates/engine/src/tests_sound.rs b/crates/engine/src/tests_sound.rs index 0947853b..105aa473 100644 --- a/crates/engine/src/tests_sound.rs +++ b/crates/engine/src/tests_sound.rs @@ -310,7 +310,7 @@ fn sounds_inside_symbols_are_in_the_exported_soundtrack_at_their_offset_and_loop inner.keyframes = vec![Arc::new(Keyframe::new(0, 1)), Arc::new(k)]; s.doc.library.push(Arc::new(Symbol { linkage: None, scale_grid_kept: None, scale_grid: None, id: SymbolId(501), name: "Talk".into(), kind: SymbolKind::Graphic, timeline: Timeline { layers: vec![Arc::new(inner)] } })); let mut k = Keyframe::new(1, 8); - k.elements.push(Arc::new(Element { id: ElementId(502), name: String::new(), transform: Default::default(), color: Default::default(), kind: ElementKind::Symbol { symbol: SymbolId(501), loop_mode: LoopMode::Loop, first_frame: 0, blend: Default::default(), filters: Vec::new(), events: Vec::new() } })); + k.elements.push(Arc::new(Element { id: ElementId(502), name: String::new(), transform: Default::default(), color: Default::default(), kind: ElementKind::Symbol { symbol: SymbolId(501), loop_mode: LoopMode::Loop, first_frame: 0, blend: Default::default(), filters: Vec::new(), events: Vec::new(), pivot: None } })); let mut outer = Layer::new(LayerId(503), "puppet"); outer.keyframes = vec![Arc::new(Keyframe::new(0, 1)), Arc::new(k)]; outer.volume = 0.5; diff --git a/crates/gpu/src/tests.rs b/crates/gpu/src/tests.rs index bfe7f82a..dcac054a 100644 --- a/crates/gpu/src/tests.rs +++ b/crates/gpu/src/tests.rs @@ -557,7 +557,7 @@ fn nine_slice_sample() -> anicraft_doc::Document { let mut l = Layer::new(LayerId(3), "art"); l.keyframes = vec![std::sync::Arc::new(k)]; d.library.push(std::sync::Arc::new(Symbol { id: SymbolId(4), name: "Panel".into(), kind: SymbolKind::MovieClip, linkage: None, scale_grid_kept: None, scale_grid: Some(ScaleGrid { left: 8.0, right: 52.0, top: 8.0, bottom: 22.0 }), timeline: Timeline { layers: vec![std::sync::Arc::new(l)] } })); - let inst = |id, xf| el(id, xf, ElementKind::Symbol { symbol: SymbolId(4), loop_mode: Default::default(), first_frame: 0, blend: Default::default(), filters: Vec::new(), events: Vec::new() }); + let inst = |id, xf| el(id, xf, ElementKind::Symbol { symbol: SymbolId(4), loop_mode: Default::default(), first_frame: 0, blend: Default::default(), filters: Vec::new(), events: Vec::new(), pivot: None }); let mut k = Keyframe::new(0, 1); k.elements.push(inst(5, Affine::translate(10.0, 10.0).mul(&Affine::scale(4.5, 1.2)))); k.elements.push(inst(6, Affine::translate(30.0, 70.0).mul(&Affine::scale(2.0, 3.5)))); @@ -1316,3 +1316,44 @@ fn gpu_binned_frames_match_the_oracle() { assert!(compare_premul8(&f.premul8, &oracle.to_premul_rgba8()).unwrap().max <= 2, "{name}"); } } + +/// The sample with faded layers (ADR 0111): every scene layer at its own opacity, one of them +/// in a faded folder, and the layers inside every symbol at 70 %. +fn faded_layers_sample() -> anicraft_doc::Document { + let mut doc = sample::demo(); + for sym in doc.library.iter_mut() { + for l in Arc::make_mut(sym).timeline.layers.iter_mut() { + Arc::make_mut(l).opacity = 0.7; + } + } + let tl = doc.timeline_mut(0); + for (i, layer) in tl.layers.iter_mut().enumerate() { + Arc::make_mut(layer).opacity = [0.35, 0.8, 0.5, 0.65][i % 4]; + } + let mut folder = anicraft_doc::Layer::new(LayerId(9_100), "Folder"); + folder.kind = LayerKind::Folder; + folder.opacity = 0.5; + if let Some(first) = tl.layers.first_mut() { + Arc::make_mut(first).parent = Some(LayerId(9_100)); + } + tl.layers.insert(0, Arc::new(folder)); + doc +} + +#[test] +fn faded_layers_are_groups_the_binner_takes() { + let doc = faded_layers_sample(); + let dl = anicraft_doc::evaluate(&doc, 7); + assert!(dl.groups.len() >= 4 && dl.groups.iter().any(|g| g.parent.is_some()), "{} groups", dl.groups.len()); + assert!(dl.groups.iter().any(|g| (g.alpha - 0.175).abs() < 1e-6), "the folder's opacity multiplies in"); +} + +#[test] +fn gpu_matches_the_oracle_on_faded_layers() { + let Some(g) = gpu() else { return }; + let doc = faded_layers_sample(); + for (f, s) in [(0u32, 1.0f32), (7, 0.5), (24, 1.5), (40, 0.37)] { + let d = assert_parity(g, "faded layers", &anicraft_doc::evaluate(&doc, f), &View::stage(&doc, s)); + eprintln!("faded layers {f} at {s}: mean {:.5} / max {} / {} of {} px differ", d.mean, d.max, d.differing, d.pixels); + } +} diff --git a/crates/render/src/html.rs b/crates/render/src/html.rs index ae7012ac..0c582cfa 100644 --- a/crates/render/src/html.rs +++ b/crates/render/src/html.rs @@ -675,7 +675,7 @@ impl<'a> Bake<'a> { } } }, - ElementKind::Symbol { symbol, loop_mode, first_frame, blend, filters, events } => { + ElementKind::Symbol { symbol, loop_mode, first_frame, blend, filters, events, .. } => { let (Some(&y), Some(sym)) = (self.symbols.get(symbol), self.doc.symbol(*symbol)) else { return }; let len = sym.timeline.frame_count(); // The page's player places symbols itself and doesn't slice them yet (ADR 0055). @@ -778,6 +778,12 @@ impl<'a> Bake<'a> { if layer.sound_gain() != 1.0 { entry.insert("sg".into(), num(layer.sound_gain(), 10_000.0)); } + // The layer's opacity (its own times its folders'; ADR 0111): the page fades + // the layer as one group. Mask artwork ignores it. + let fade = tl.layer_opacity(index); + if fade < 1.0 - 1e-4 && layer.kind != LayerKind::Mask { + entry.insert("o".into(), num(fade, 10_000.0)); + } if layer.kind == LayerKind::Mask { entry.insert("mk".into(), json!(slots.get(&layer.id.0).copied().unwrap_or(0))); // A soft mask (ADR 0070): 1 alpha, 2 luminance. @@ -795,12 +801,16 @@ impl<'a> Bake<'a> { } let walk = layer.parent.and_then(|p| tl.layer(p)).filter(|g| g.kind == LayerKind::Guide).and_then(|g| guide_walk(g, f)); let mut items = Vec::new(); + let mut any = false; if let Some((start, els)) = evaluate_shown(layer, f, walk.as_ref(), self.doc.stage.fps) { + any = !els.is_empty(); for el in els.iter() { self.element(el, layer, f, start, &mut items); } } - if items.is_empty() && layer.kind != LayerKind::Mask { + // (A faded layer with elements stays, drawing or not: it is a group in the + // evaluator's list, and the page's groups are numbered the same.) + if items.is_empty() && layer.kind != LayerKind::Mask && !(any && entry.contains_key("o")) { continue; } entry.insert("e".into(), Value::Array(items)); diff --git a/crates/render/src/html/player.js b/crates/render/src/html/player.js index 221fa434..2a0d13ec 100644 --- a/crates/render/src/html/player.js +++ b/crates/render/src/html/player.js @@ -339,8 +339,17 @@ var AniCraft = (function () { } } if (v && isMask) v.maskBegin(masks, L.mm || 0); - const lcx = L.v ? Object.assign({}, cx, { xf: L.v }) : cx; + let lcx = L.v ? Object.assign({}, cx, { xf: L.v }) : cx; + // A layer below full opacity (ADR 0111) fades as one group, as eval.rs draws it. + let faded = null; + if (L.o !== undefined && cx.masks === null && !isMask) { + faded = dl.groups.length; + dl.groups.push({ parent: cx.group, alpha: Math.min(Math.max(L.o, 0), 1), blend: "normal", clip: clip, filters: null, margin: 0 }); + lcx = Object.assign({}, lcx, { group: faded }); + if (v) v.groupBegin(faded, dl.groups[faded]); + } for (const e of L.e) evalElement(M, e, lcx, clip, masks, dl, play, v); + if (faded !== null && v) v.groupEnd(faded, dl.groups[faded]); if (v && isMask) { v.maskEnd(masks, open === masks); if (open === masks) open = null; diff --git a/crates/render/src/html_tests.rs b/crates/render/src/html_tests.rs index 66446503..c1301d36 100644 --- a/crates/render/src/html_tests.rs +++ b/crates/render/src/html_tests.rs @@ -12,7 +12,7 @@ fn rect(id: u64, x: f32, y: f32, w: f32, h: f32, c: u32) -> Arc { } fn inst(id: u64, symbol: u64, name: &str, m: Affine, events: Vec) -> Arc { - Arc::new(Element { id: ElementId(id), name: name.into(), transform: m, color: ColorEffect::default(), kind: ElementKind::Symbol { symbol: SymbolId(symbol), loop_mode: LoopMode::Loop, first_frame: 0, blend: BlendMode::Normal, filters: Vec::new(), events } }) + Arc::new(Element { id: ElementId(id), name: name.into(), transform: m, color: ColorEffect::default(), kind: ElementKind::Symbol { symbol: SymbolId(symbol), loop_mode: LoopMode::Loop, first_frame: 0, blend: BlendMode::Normal, filters: Vec::new(), events, pivot: None } }) } fn kf(start: u32, duration: u32, elements: Vec>, actions: Vec, label: &str) -> Arc { @@ -622,7 +622,7 @@ fn sounds_carry_their_envelopes_and_volumes_and_start_in_graphics_and_clips_as_i l.volume = volume; Arc::new(l) }; - let inst = |id, symbol| Arc::new(Element { id: ElementId(id), name: String::new(), transform: Affine::IDENTITY, color: Default::default(), kind: ElementKind::Symbol { symbol: SymbolId(symbol), loop_mode: Default::default(), first_frame: 0, blend: Default::default(), filters: Vec::new(), events: Vec::new() } }); + let inst = |id, symbol| Arc::new(Element { id: ElementId(id), name: String::new(), transform: Affine::IDENTITY, color: Default::default(), kind: ElementKind::Symbol { symbol: SymbolId(symbol), loop_mode: Default::default(), first_frame: 0, blend: Default::default(), filters: Vec::new(), events: Vec::new(), pivot: None } }); // A graphic with a fading sound on its frame 1 (of 2), a clip with a left-channel one on its // frame 0 (of 3), both on a layer at half volume; a sound of the main timeline's own. doc.library.push(Arc::new(Symbol { linkage: None, scale_grid_kept: None, scale_grid: None, id: SymbolId(20), name: "g".into(), kind: SymbolKind::Graphic, timeline: Timeline { layers: vec![layer(21, vec![key(0, 1, None, vec![]), key(1, 1, snd(SoundSync::Event, SoundEffect::FadeOut), vec![])], 1.0)] } })); @@ -1541,3 +1541,36 @@ fn filters_on_text_reach_the_page_and_group_as_in_the_renderer() { same_display_list(&mut js, &m, &masked, &r.state, "masking"); assert!(evaluate_player(&masked, &r.state).groups.is_empty()); } + +#[test] +fn layer_opacity_comes_across_as_one_fade_group_a_layer() { + // The fixture with every layer faded (in the symbols too) and the bottom layer in a faded + // folder: the page's display list has the same groups as the evaluator's on every frame + // (ADR 0111). + let mut doc = fixture(); + for sym in doc.library.iter_mut() { + for l in Arc::make_mut(sym).timeline.layers.iter_mut() { + Arc::make_mut(l).opacity = 0.75; + } + } + let tl = doc.timeline_mut(0); + for l in tl.layers.iter_mut() { + Arc::make_mut(l).opacity = 0.4; + } + let n = tl.layers.len(); + let mut folder = Layer::new(LayerId(7100), "Folder"); + folder.kind = LayerKind::Folder; + folder.opacity = 0.5; + Arc::make_mut(&mut tl.layers[n - 1]).parent = Some(LayerId(7100)); + tl.layers.insert(n - 1, Arc::new(folder)); + doc.sanitize(); + assert!((doc.timeline(0).layer_opacity(n) - 0.2).abs() < 1e-6, "the folder link survives"); + let m = movie(&doc, &HtmlOptions::default()); + let faded: Vec = m.json["contents"].as_array().unwrap().iter().flat_map(|c| c["l"].as_array().unwrap().iter()).filter_map(|l| l["o"].as_f64()).collect(); + for want in [0.4, 0.2, 0.75] { + assert!(faded.iter().any(|o| (o - want).abs() < 1e-3), "{want} in {faded:?}"); + } + let dl = evaluate_player(&doc, &PlayerState::seeded(1)); + assert!(dl.groups.iter().any(|g| (g.alpha - 0.2).abs() < 1e-6) && dl.groups.iter().any(|g| g.parent.is_some()), "{:?}", dl.groups); + compare(&doc, &vec![(vec![], vec![]); 12]); +} diff --git a/crates/render/src/layer_opacity_tests.rs b/crates/render/src/layer_opacity_tests.rs new file mode 100644 index 00000000..fe4d537a --- /dev/null +++ b/crates/render/src/layer_opacity_tests.rs @@ -0,0 +1,63 @@ +//! Layer opacity (ADR 0111) in the CPU oracle and the exports that draw evaluated frames: a +//! faded layer's artwork is drawn together, then shown at the layer's opacity. + +use crate::{View, render}; +use anicraft_doc::{ColorEffect, Document, Element, ElementId, ElementKind, Keyframe, Layer, LayerId, LayerKind, Paint, Rgba, Shape, Stage, evaluate}; +use anicraft_geom::{Affine, Path}; +use std::sync::Arc; + +fn square(id: u64, x: f32, colour: Rgba) -> Arc { + Arc::new(Element { id: ElementId(id), name: String::new(), transform: Affine::translate(x, 0.0), color: ColorEffect::default(), kind: ElementKind::Shape(Shape::filled(Path::rect(0.0, 0.0, 8.0, 4.0), Paint::Solid(colour))) }) +} + +/// A 12 × 4 white stage: a red square under a blue one, overlapping from x = 4 to 8, on one +/// layer at `opacity`. +fn overlap(opacity: f32) -> Document { + let mut d = Document { stage: Stage { width: 12, height: 4, background: Rgba::WHITE, ..Stage::default() }, ..Document::default() }; + let mut k = Keyframe::new(0, 1); + k.elements = vec![square(1, 0.0, Rgba::new(1.0, 0.0, 0.0, 1.0)), square(2, 4.0, Rgba::new(0.0, 0.0, 1.0, 1.0))]; + let l = Arc::make_mut(&mut d.timeline_mut(0).layers[0]); + l.keyframes = vec![Arc::new(k)]; + l.opacity = opacity; + d +} + +fn near(p: [f32; 4], q: [f32; 4]) -> bool { + p.iter().zip(q).all(|(a, b)| (a - b).abs() < 1e-4) +} + +#[test] +fn a_faded_layer_shows_its_artwork_as_one() { + for (opacity, red, both, blue) in [(1.0, [1.0, 0.0, 0.0, 1.0], [0.0, 0.0, 1.0, 1.0], [0.0, 0.0, 1.0, 1.0]), (0.5, [1.0, 0.5, 0.5, 1.0], [0.5, 0.5, 1.0, 1.0], [0.5, 0.5, 1.0, 1.0]), (0.25, [1.0, 0.75, 0.75, 1.0], [0.75, 0.75, 1.0, 1.0], [0.75, 0.75, 1.0, 1.0]), (0.0, [1.0; 4], [1.0; 4], [1.0; 4])] { + let d = overlap(opacity); + let (pm, _) = render(&evaluate(&d, 0), &View::stage(&d, 1.0)).unwrap(); + // Where the squares overlap only the top one shows, at the layer's opacity: no red. + assert!(near(pm.pixel(1, 1).unwrap(), red), "{opacity}: {:?}", pm.pixel(1, 1)); + assert!(near(pm.pixel(6, 1).unwrap(), both), "{opacity}: {:?}", pm.pixel(6, 1)); + assert!(near(pm.pixel(10, 1).unwrap(), blue), "{opacity}: {:?}", pm.pixel(10, 1)); + } +} + +#[test] +fn a_folder_fades_its_layers_and_layers_fade_on_top_of_each_other() { + // Two layers at 50 %, each a full black cover, the top one in a folder at 50 %. + let mut d = Document { stage: Stage { width: 4, height: 4, background: Rgba::WHITE, ..Stage::default() }, ..Document::default() }; + let cover = |id: u64| Arc::new(Element { id: ElementId(id), name: String::new(), transform: Affine::IDENTITY, color: ColorEffect::default(), kind: ElementKind::Shape(Shape::filled(Path::rect(0.0, 0.0, 4.0, 4.0), Paint::Solid(Rgba::BLACK))) }); + let layer = |id: u64, el: u64, parent: Option| { + let mut l = Layer::new(LayerId(id), "l"); + l.keyframes = vec![Arc::new(Keyframe { elements: vec![cover(el)], ..Keyframe::new(0, 1) })]; + l.opacity = 0.5; + l.parent = parent; + Arc::new(l) + }; + let mut folder = Layer::new(LayerId(30), "folder"); + folder.kind = LayerKind::Folder; + folder.opacity = 0.5; + d.timeline_mut(0).layers = vec![Arc::new(folder), layer(31, 1, Some(LayerId(30))), layer(32, 2, None)]; + let (pm, _) = render(&evaluate(&d, 0), &View::stage(&d, 1.0)).unwrap(); + // White under 50 % black is 0.5; under a further 25 % black (50 % of 50 %) it is 0.375. + assert!(near(pm.pixel(2, 2).unwrap(), [0.375, 0.375, 0.375, 1.0]), "{:?}", pm.pixel(2, 2)); + // The SVG export wraps the faded layers in opacity groups. + let svg = crate::svg::to_svg(&evaluate(&d, 0), &d.stage); + assert!(svg.contains("opacity=\"0.25\"") && svg.contains("opacity=\"0.5\""), "{svg}"); +} diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index 900da316..4de35a98 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -951,6 +951,9 @@ fn composite(cov: &Coverage, op: &Prepared, b: IRect, band_y0: i32, w: usize, ro #[cfg(test)] mod nine_slice_tests; +#[cfg(test)] +mod layer_opacity_tests; + #[cfg(test)] mod tests { use super::*; diff --git a/crates/render/src/nine_slice_tests.rs b/crates/render/src/nine_slice_tests.rs index 2ebc5801..6267401c 100644 --- a/crates/render/src/nine_slice_tests.rs +++ b/crates/render/src/nine_slice_tests.rs @@ -22,7 +22,7 @@ fn panel(sx: f32, sy: f32, guides: bool) -> Document { name: String::new(), transform: Affine::translate(20.0, 20.0).mul(&Affine::scale(sx, sy)), color: ColorEffect::default(), - kind: ElementKind::Symbol { symbol: SymbolId(4), loop_mode: Default::default(), first_frame: 0, blend: Default::default(), filters: Vec::new(), events: Vec::new() }, + kind: ElementKind::Symbol { symbol: SymbolId(4), loop_mode: Default::default(), first_frame: 0, blend: Default::default(), filters: Vec::new(), events: Vec::new(), pivot: None }, }; let mut k = Keyframe::new(0, 1); k.elements.push(Arc::new(inst)); diff --git a/crates/xfl/src/import.rs b/crates/xfl/src/import.rs index 50334917..229adf48 100644 --- a/crates/xfl/src/import.rs +++ b/crates/xfl/src/import.rs @@ -658,7 +658,7 @@ impl<'a> Builder<'a> { // Blend modes by Animate's names; unknown ones stay Normal. let blend = el.attr("blendMode").and_then(BlendMode::from_key).unwrap_or_default(); let filters = self.filters(el); - let mut e = Element { id: ElementId(self.doc.alloc_id()), name: String::new(), transform: m, color: fx, kind: ElementKind::Symbol { symbol, loop_mode, first_frame, blend, filters, events: Vec::new() } }; + let mut e = Element { id: ElementId(self.doc.alloc_id()), name: String::new(), transform: m, color: fx, kind: ElementKind::Symbol { symbol, loop_mode, first_frame, blend, filters, events: Vec::new(), pivot: None } }; // The instance name actions address it by (ADR 0024); one they couldn't is reported. if let Some(name) = el.attr("name").map(str::trim).filter(|n| !n.is_empty()) { if anicraft_doc::actions::valid_instance_name(name) { diff --git a/docs/adr/0111-the-transformation-point-a-turning-box-and-layer-opacity.md b/docs/adr/0111-the-transformation-point-a-turning-box-and-layer-opacity.md new file mode 100644 index 00000000..ba9286fc --- /dev/null +++ b/docs/adr/0111-the-transformation-point-a-turning-box-and-layer-opacity.md @@ -0,0 +1,151 @@ +# ADR 0111: The transformation point, a turning box and layer opacity + +* Status: accepted (2026-11-17) +* Relates to: ADR 0109 (transformation origins, which left the draggable point out), ADR 0073 + (groups), ADR 0029 (fade groups on the GPU stage), ADR 0028 (HTML canvas export), ADR 0061 + (Layer Properties), ADR 0004 (destructive actions); issues #302, #280, #178, #183, #175, #279 + +## Context + +Six reports from artists coming from Animate: + +* The **transformation point** (they call it the anchor or pivot point) could not be moved: + not with the Selection tool, not with Free Transform, not in Properties (#302, #280, #178, + #183). In Animate it is the white circle Free Transform shows; you drag it, even outside the + box, and the object then turns about it. A limb hinged at the shoulder needs it. +* A rotated symbol showed an upright box, so you could not see that it was rotated, and its + handles stretched it along the stage's axes, which skews it (#175). +* There was no **layer opacity** (#279). + +ADR 0109 rejected a stored point because that slice only needed modes for several objects. +These reports need the point itself. + +Behaviour was learned from Adobe's public help pages on transforming objects and on layers, +from the public tutorial video linked in #280, and from watching the program; nothing was +copied. + +## Decision + +### 1. A symbol instance keeps its transformation point; everything else has one while the tool is held + +`ElementKind::Symbol` gains `pivot: Option`, in the instance's own space (so it travels +with the instance, as Animate's does), read through `Element::pivot()`. It is saved only when +set; older files open with none. Points that are not finite, or more than 10⁶ units out, count +as none. + +* `None` means "never moved". Tools then use the **centre of the instance's box**, and tweens + the **registration point**, exactly as before this ADR, so no existing file changes. +* `modify.transformation_point {x, y}` (stage space) sets it on the selected instances; + `modify.reset_transformation_point` (Modify › Transform) clears it. Both are ordinary + undoable commands, and a drag of the circle is one gesture, so one undo step. +* A raw shape, a drawing object, a group, text, a bitmap or several elements have **one point + for the selection while Free Transform is the tool** (shell state in `src/xform.rs`, like a + marquee). It goes with the selection when a Free Transform change or a move carries the + artwork, and is dropped when the tool or the selection changes. Raw pieces are cut and + joined by every merge, so there is no lasting element to keep a point on; groups and the + rest could keep one later (the accessor leaves room), and Animate itself forgets a group's + point when it is deselected. + +*Rejected:* a field on `Element` for every kind. It is the more general model, but only an +instance needs a lasting point today, the field would touch over a hundred element literals +across parallel tracks, and `Element::pivot()` hides where it lives, so widening it later is +not a file-format break (a new optional key). + +### 2. What turns about the point + +One rule, everywhere: **a new scale, rotation or skew leaves the point where it is.** + +* **Free Transform**: a rotation turns about the point; Alt scales and skews about it + (without Alt the opposite handle or edge stays put, as before and as in Animate). +* **Modify › Transform** (Rotate 90°, Flip) in the default origin mode turn one selected + instance about its own point. +* **Properties** (`element.set_transform`): a new Scale or Rotation is applied about the + point; a Position still places the registration point. Properties shows the point as + **Pivot** X and Y with **Reset**, which is also the keyboard and screen-reader way to set it. +* **Classic tweens** (`doc::evaluate`, pure): when either keyframe's instance has a point, the + point travels in a straight line from where the first keyframe has it to where the next + does (by the position ease), and the instance's scale, rotation and skew are interpolated + as before and placed round it. A keyframe without a point takes the other's. So an arm + keyed at two angles swings on its shoulder instead of sliding between two placements. +* **Motion tweens**: the position tracks carry the point, and the rotation, scale and skew + tracks turn the target about it. + +Every renderer and export draws evaluated frames, so the swing is the same in the PNG, GIF, +video, SVG, Lottie and HTML exports and on both stages with no change to them. + +ADR 0109's modes are unchanged. With *each object about its own point* the circle shows each +object's point and is not draggable. + +### 3. One element shows its own box + +`Session::transform_frame()` answers a box and the transform that places it. For one selected +element it is the box of what the element draws at the playhead, in the element's own space, +under the element's transform: turned, scaled and skewed as the element is. For several +elements, raw pieces or Edit Multiple Frames it is the upright bounds under the identity, as +before. + +Free Transform draws that box and works in it (`xform::Frame`): handles are hit where the box +is, a handle's scale and an edge's skew are computed in the box's own space and conjugated back +(`M · L · M⁻¹`), so a turned instance stretches along its own axes and stays unskewed; a +rotation is computed on the stage (a turn is a turn however the box is scaled); the resize +arrows follow the box's direction; snapping uses the handles' real positions. The Selection +tool's plain box stays upright, as Animate's does. + +The dragged point snaps to the box's eight handles and its centre within 8 screen pixels (Alt: +freely) and may leave the box (#178). A double-click on it puts it back at the centre. + +The point is grabbed before the box, as in Animate: a press on the white circle moves the +point, not the object. Dragging an object by its exact centre therefore moves the point; any +other place inside the box moves the object. + +### 4. Layer opacity is in the movie, and a layer fades as one + +`Layer::opacity` (`0..=1`, saved only below 1). In `doc::evaluate` a layer below full opacity +puts its artwork in a **fade group** (`DisplayList::groups`, the mechanism a translucent +instance already uses): the layer is composited together and then shown at its opacity, so +overlapping parts do not show through each other. A folder's opacity multiplies into the +layers in it. Mask artwork ignores opacity (as it ignores an instance's) and guide artwork is +never in the movie. Because it is a group in the display list, the CPU oracle, the GPU stage, +SVG and Lottie needed no change; the HTML canvas export writes each layer's opacity and its +player opens the same group (`player.js`), checked item for item against the Rust evaluator. + +`layer.set_opacity {opacity: 0..100}` and `opacity` on `layer.set_properties` / +`layer.properties`; Layer Properties has a slider and a field; the layer's right-click menu +has **Opacity ›** 100, 75, 50, 25, 0 %; a faded layer shows its percentage beside its name +and says it to screen readers. + +**Not Animate's meaning, on purpose.** Animate's Layer Properties offers *Visibility › +Transparent*, an authoring aid that is not published. The report asks for layer opacity as +other animation and paint programs have it, and an opacity that silently disappears in the +export would be a trap, so AniCraft's is part of the movie. *Rejected:* multiplying the +opacity into each element's alpha (cheaper, but overlapping artwork on the layer shows +through itself, which is not what "the layer at 50 %" means), and an authoring-only +transparency (a second, similar-looking setting can come later if artists ask for a tracing +aid). + +## Consequences + +* Measured (the sample scene, 1280 × 720, frame 7; RTX 5090 for the GPU): seven faded layers + cost the CPU oracle 2.0 ms a frame (2.9 → 4.9 ms); the GPU stage is unchanged (1.8 and + 1.4 ms, within noise). GPU against the oracle on faded layers and a faded folder, four + frames at four scales: at most 6 of 2,073,600 pixels differ, by 1/255. +* Analytic tests: a tween about a moved point keeps the point within 0.001 px on every frame + and turns 9° a frame over a 90° span; Properties' rotation and scale keep it fixed; a turned + box's side handle changes one scale only (no skew, rotation kept); layer opacity pixels + match `1 − a` over white exactly, and the overlap of two shapes on a faded layer shows only + the top one. +* Files: two optional keys (`pivot` on an instance, `opacity` on a layer). Older files open + unchanged; older versions ignore both. +* A press on the exact centre of Free Transform's box now moves the point (see 3). +* Not yet: the point of an Animate file's instances (XFL `transformationPoint`: importing it + changes how imported classic tweens move, so it needs the corpus goldens checked first); + a kept point for groups, text and drawing objects; the point with Edit Multiple Frames and + inside ADR 0109's each-object modes; motion guides carrying the point (they carry the + registration point); Alt-rotate about the opposite corner; a turned box for the Selection + tool; opacity keyed over time; an authoring-only layer transparency; layer opacity from + Animate files. + +## Questions for the lead + +* Layer opacity is published (4). If the project would rather match Animate's + authoring-only transparency, the model stays and only `evaluate`'s movie path changes. diff --git a/docs/guide/coming-from-animate.md b/docs/guide/coming-from-animate.md index 492991d9..152a517a 100644 --- a/docs/guide/coming-from-animate.md +++ b/docs/guide/coming-from-animate.md @@ -45,7 +45,7 @@ Each tool has the key you already know. |---|---|---| | Selection | **V** | Selects raw strokes and fills with the dot pattern; drag an edge to bend it. | | Subselection | **A** | Points and handles, on raw drawings and drawing objects. | -| Free Transform | **Q** | Scale, skew (drag the line between two handles), rotate and move; Shift and Alt as you'd expect. | +| Free Transform | **Q** | Scale, skew (drag the line between two handles), rotate and move; Shift and Alt as you'd expect. Drag the white circle to move the transformation point, double-click it to centre it; a rotated instance's box turns with it. | | Gradient Transform | **F** | Its own button (no flyouts yet). Gradient and bitmap fills, with Lock Fill. | | Width | **U** | Variable-width strokes, with profiles in Properties. | | Bone | **M** | Joins symbol instances into an armature, or draws bones inside a shape. | diff --git a/docs/guide/drawing.md b/docs/guide/drawing.md index 20dcb462..64be1c59 100644 --- a/docs/guide/drawing.md +++ b/docs/guide/drawing.md @@ -395,15 +395,44 @@ Both dialogs remember what you entered. Each command is one undo step. ## Transforming artwork With the **Free Transform** tool (**Q**), drag a handle (a corner or the middle of an edge) to -**scale** (**Shift** keeps the proportions, **Alt** scales from the centre), the line between -two handles to **skew** (the opposite edge stays where it is; **Alt** skews about the centre), -just outside a corner to **rotate** (the pointer turns into a curved arrow there; **Shift** -snaps to 15°), or inside the box to **move**. +**scale** (**Shift** keeps the proportions, **Alt** scales about the transformation point), +the line between two handles to **skew** (the opposite edge stays where it is; **Alt** skews +about the transformation point), just outside a corner to **rotate** (the pointer turns +into a curved arrow there; **Shift** snaps to 15°), or inside the box to **move**. + +One selected object shows **its own box**: turn a symbol, a group, text or a drawing object +and its box turns with it, so you can see how it stands, and its handles stretch it along its +own sides instead of slanting it. Several objects together, and merged drawing, show one +upright box round them all. You can also type exact **Position**, **Size**, **Scale** and **Rotation** values in Properties. **Size** is the width (**W**) and height (**H**) of the selection's box in stage pixels: a new value stretches the artwork from the box's top-left corner, which stays where it is. The lock beside **Scale** keeps width and height in proportion. +### The transformation point + +The **white circle** in Free Transform's box is the transformation point: what the selection +rotates about, and what **Alt** scales and skews about. It starts at the centre. + +* **Drag the circle** to move it. It snaps to the box's corners, the middles of its sides and + its centre (hold **Alt** to place it freely), and it can sit outside the box. +* **Double-click the circle** to put it back at the centre. +* A **symbol instance keeps its point**. It travels with the instance, is saved in the file, + and is used everywhere the instance turns or scales: Free Transform, **Rotate 90°** and + **Flip**, the **Scale** and **Rotation** fields in Properties, and **tweens**. Put an arm's + point on its shoulder and a tween between two angles swings the arm from the shoulder. + Properties shows the point as **Pivot** (X and Y on the stage, and **Reset**), and **Modify › + Transform › Reset Transformation Point** puts it back. +* Anything else (a shape, a drawing object, a group, text, a bitmap, or several objects) has + a point **for as long as it stays selected with Free Transform**: move it, then rotate and + scale about it as often as you like. Picking another tool or another selection lets it go. + Convert the artwork to a symbol when you want a point that lasts. + +A press on the circle moves the circle, not the object: to move a small object, drag it by +any other part of its box. Moving the circle is one undo step. + +### Several objects + With several objects selected, **Transform about** in the Free Transform tool's options chooses what they turn, scale and skew about: @@ -418,7 +447,8 @@ chooses what they turn, scale and skew about: The stage marks the point, or each object's point, with a crosshair. The choice stays as you change the selection, and **Rotate 90°** and **Flip** in **Modify › Transform** follow it -too. Moving the selection always moves everything by the same amount. To change the choice +too. The circle can be dragged only with **The whole selection**; in the other two it shows +where each object's point is. Moving the selection always moves everything by the same amount. To change the choice from the keyboard, give **Modify › Transform › Next Transformation Origin** a key in the shortcut editor. A merged drawing (a fill and the lines on its edges) counts as one object. @@ -429,6 +459,7 @@ shortcut editor. A merged drawing (a fill and the lines on its edges) counts as | Flip Horizontal, Flip Vertical | **Modify › Transform** | none | | Remove Transform | **Modify › Transform** | **Ctrl+Shift+Z** | | Next Transformation Origin | **Modify › Transform** | none | +| Reset Transformation Point | **Modify › Transform** | none | | Break Apart | **Modify** | **Ctrl+B** | **Break Apart** turns text into shapes, a symbol instance into the artwork inside it, and a @@ -616,8 +647,9 @@ without snapping. Rulers, the grid and guides never show in Test Movie or in exp ## Not there yet -Not in AniCraft yet: gradient and bitmap strokes; a transformation point you can drag to -anywhere on an object, and transformation origins with Edit Multiple Frames; picking a colour +Not in AniCraft yet: gradient and bitmap strokes; a transformation point that a group, text +or a drawing object keeps after it is deselected, the transformation point of instances in +Animate files, and transformation points and origins with Edit Multiple Frames; picking a colour from outside the AniCraft window; previews in the Expand Fill and Soften Fill Edges dialogs; swatch folders, bitmap swatches and the swatches inside Animate files; moving the Envelope's handles from the keyboard; reading a pen's tilt on Windows, macOS and Linux (the brushes' tilt settings are ready for it); bitmap diff --git a/docs/guide/reference/commands.md b/docs/guide/reference/commands.md index 8d65e289..338198d4 100644 --- a/docs/guide/reference/commands.md +++ b/docs/guide/reference/commands.md @@ -1,6 +1,6 @@ # Command reference -Everything you can do in AniCraft is a command: the menus, the shortcuts, the command palette (**Ctrl+K**, macOS **⌘K**), `anicraft-cli` and AI assistants over MCP all run the same 370 commands, listed here by menu. The id is what scripts and [working headless](../working-headless.md) use; the parameters are what a command takes as JSON. Commands that change the document are one undo step each. Your own shortcuts (**Help › Keyboard Shortcuts**) replace the defaults shown here; see the [shortcut reference](shortcuts.md). +Everything you can do in AniCraft is a command: the menus, the shortcuts, the command palette (**Ctrl+K**, macOS **⌘K**), `anicraft-cli` and AI assistants over MCP all run the same 373 commands, listed here by menu. The id is what scripts and [working headless](../working-headless.md) use; the parameters are what a command takes as JSON. Commands that change the document are one undo step each. Your own shortcuts (**Help › Keyboard Shortcuts**) replace the defaults shown here; see the [shortcut reference](shortcuts.md). This page is generated from the command registry, so it always matches the version of AniCraft it came with. @@ -161,7 +161,7 @@ This page is generated from the command registry, so it always matches the versi - **Mask** `layer.toggle_mask` · Modify › Timeline · changes the document Parameters: `{layer?}` - **Layer Properties** `layer.set_properties` · Modify › Timeline · changes the document - Parameters: `{layer?, name?, type?: normal|mask|masked|guide|guided, mask?: coverage|alpha|luminance (a mask layer's mask type), color?, outline?: bool (view as outlines), height?: 100|200|300, visible?, locked?, onion?} sets several at once, as one undo step; answers with the layer's properties` + Parameters: `{layer?, name?, type?: normal|mask|masked|guide|guided, mask?: coverage|alpha|luminance (a mask layer's mask type), color?, outline?: bool (view as outlines), height?: 100|200|300, opacity?: 0..100 (percent), visible?, locked?, onion?} sets several at once, as one undo step; answers with the layer's properties` - **Remove Camera** `camera.remove` · Modify › Timeline · changes the document Parameters: `{} (removes the camera layer and its moves; asks first when the camera is animated)` - **Add Warp Mesh** `warp.add` · Modify › Asset Warp · changes the document @@ -220,6 +220,8 @@ This page is generated from the command registry, so it always matches the versi Parameters: `{origin?: selection|registration|center (default: the mode set with modify.transform_origin; selection unless changed)} about the centre of the whole selection, or each selected object about its own point` - **Next Transformation Origin** `modify.transform_origin` · Modify › Transform Parameters: `{mode?: selection|registration|center (default: the next one)} what several selected objects turn, scale and skew about with Free Transform and Modify › Transform: selection (one point for them all, as one arrangement; the default), registration (each about its own point: a symbol instance's or group's registration point, the centre of anything else) or center (each about the centre of its own box). Tool state, not part of the document → {mode}` +- **Reset Transformation Point** `modify.reset_transformation_point` · Modify › Transform · changes the document + Parameters: `{} puts the selected symbol instances' transformation point back at the centre (none kept: tools use the centre of the box, tweens the registration point) → {reset}` - **Remove Transform** `modify.remove_transform` · Modify › Transform · **Ctrl+Shift+Z** (macOS **⇧⌘Z**) · changes the document Parameters: `{}` - **Left** `align.left` · Modify › Align · **Ctrl+Alt+1** (macOS **⌥⌘1**) · changes the document @@ -355,10 +357,12 @@ These commands have no menu item: the panels, the stage and the timeline use the Parameters: `{color: "#rrggbb", layer?} the layer's colour: its outlines in outline mode and its bar on the timeline` - **Layer Height** `layer.set_height` · changes the document Parameters: `{height: 100 | 200 | 300 (percent of a normal row), layer?} the layer's row height on the timeline` +- **Layer Opacity** `layer.set_opacity` · changes the document + Parameters: `{opacity: 0..100 (percent), layer?} how strongly the layer shows, in the movie and every export: its artwork is drawn together and then faded, so its overlapping parts don't show through each other. A folder's opacity fades the layers in it; mask and guide artwork ignore it (ADR 0111) → {layer, opacity}` - **Mask Type** `layer.set_mask` · changes the document Parameters: `{mask: coverage|alpha|luminance, layer?} how a mask layer reveals the layers it masks: coverage (its fills' area), alpha (its artwork's opacity: gradients and faded shapes make soft edges) or luminance (its brightness: white shows, black hides; SVG's mask) (ADR 0070)` - **Get Layer Properties** `layer.properties` - Parameters: `{layer?} the layer's name, type, mask type (mask layers), colour, outline, height (percent), visible, locked and onion` + Parameters: `{layer?} the layer's name, type, mask type (mask layers), colour, outline, height (percent), opacity (percent), visible, locked and onion` - **Camera** `camera.set` · changes the document Parameters: `{x?, y? (camera centre, stage px), dx?, dy? (pan by), zoom? (%, 5–2000), zoom_by? (factor), rotation? (°), rotate_by? (°), reset?: bool, frame?, and the colour effect as element.set_color_effect takes it: style?: none|brightness|tint|advanced, brightness? (%), tint? (#rrggbb), tint_amount? (%), red_multiplier? … blue_offset? (the camera has no opacity: no alpha values)}` - **Camera Info** `camera.info` @@ -508,7 +512,7 @@ These commands have no menu item: the panels, the stage and the timeline use the - **Move** `element.translate` · changes the document Parameters: ``{dx, dy, snap?, from?: [x, y]} moves the selection, on every layer; with `snap` (a distance) one of its corners or ends, or its box's corners or centre (the nearest to `from`), then snaps within that distance by the snap engine's priority (ADR 0076): a point, guide, line or fill edge of the rest, the grid, a whole pixel`` - **Transform** `element.set_transform` · changes the document - Parameters: `{x?, y?, sx?, sy?, rotation? (degrees)}` + Parameters: `{x?, y?, sx?, sy?, rotation? (degrees)} x and y place the registration point. A new scale or rotation alone is applied about a symbol instance's transformation point when it has one (modify.transformation_point), else about the registration point` - **Fill Colour** `element.set_fill` · changes the document Parameters: `{color: "#rrggbb" | "#rrggbbaa" | null, or on: true | false} (the alpha is the fill's own; 00 is a clear fill, not the same as null. on: false turns the fill off like null; on: true puts back the fill each shape had before, else the tool's fill colour. With only raw lines selected the fill goes to what they surround)` - **Stroke** `element.set_stroke` · changes the document @@ -567,6 +571,8 @@ These commands have no menu item: the panels, the stage and the timeline use the Parameters: `{x, y, add?, slop?} a raw stroke and the strokes joined to it, or a raw fill and the strokes on and in it` - **Transform** `modify.transform` · changes the document Parameters: `{a, b, c, d, e, f, origin?: selection|registration|center (default selection)} affine applied in stage space (free transform), to the selection on every layer. With origin registration or center, the matrix's scale, rotation and skew are applied to each selected object about its own point instead (see modify.transform_origin) and its move (e, f) is left out` +- **Set Transformation Point** `modify.transformation_point` · changes the document + Parameters: `{x, y} (stage space, as modify.transform) moves the selected symbol instances' transformation point there (the white circle Free Transform shows): what each then turns, scales and skews about with Free Transform, the Modify › Transform commands, the Properties fields and in tweens. It is kept with the instance, in the instance's own space, so it travels with it. Anything else has no point of its own to keep (ADR 0111) → {set, x, y}` - **Pen Path** `draw.path` · changes the document Parameters: `{d: SVG path data (stage space), fill?, stroke?, stroke_width?, object?}` - **Pencil Stroke** `draw.freehand` · changes the document diff --git a/docs/guide/timeline.md b/docs/guide/timeline.md index d5bafe8c..21bee7f0 100644 --- a/docs/guide/timeline.md +++ b/docs/guide/timeline.md @@ -83,8 +83,22 @@ row taller. This is handy for layers you work on a lot, or for seeing sound wave Double-click a layer's icon (or right-click it and choose **Properties…**, or choose **Modify › Timeline › Layer Properties**) to open the Layer Properties window. Here you can set, all at once, the layer's name, whether it shows and is locked, its type (Normal, Mask, Masked, Guide -or Guided), its outline colour, outlines, onion skin and height. **OK** applies everything as -one undo step; **Cancel** changes nothing. +or Guided), its outline colour, outlines, onion skin, opacity and height. **OK** applies +everything as one undo step; **Cancel** changes nothing. + +### Layer opacity + +**Opacity** in Layer Properties sets how strongly a layer shows, from 0 to 100 %. For the usual +values, right-click the layer and choose **Opacity** › **100 %**, **75 %**, **50 %**, **25 %** +or **0 %**. A faded layer shows its percentage beside its name. + +The layer fades **as one**: its artwork is drawn together first, so where two of its shapes +overlap you don't see one through the other. A folder's opacity fades every layer in it, on +top of each layer's own. Mask and guide layers ignore it. + +Layer opacity is part of your movie: you see it on the stage, in Test Movie and in every +export. (Animate's *Transparent* layer setting is only a view while you work; to see through +a layer while tracing without changing the movie, use **View as Outlines** instead.) Layer Properties works on one layer at a time. Editing several layers at once isn't there yet. diff --git a/docs/roadmap.md b/docs/roadmap.md index 8d79acb0..27f98e26 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -15,7 +15,7 @@ This integration depends on craft-libs #1962 and still requires hosted parity va | 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 (with reflect/repeat, focal points, elliptical radials and linear RGB, ADR 0074), 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. **Soft masks** (ADR 0070): a mask layer's mask type is Shape (coverage), Alpha (its artwork's opacity as drawn: gradients, faded shapes, strokes, bitmaps) or Luminance (brightness × opacity, SVG's coefficients), in the CPU oracle (analytic tests), the GPU stage (parity: mean 0.00006, worst 1 step of 255), SVG export (`` with `mask-type`), Lottie (alpha and luma track mattes) and the HTML canvas; Layer Properties › Mask type. **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 ``. **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. Filters apply in list order and may be switched off (ADR 0091): `evaluate` leaves switched-off ones out, so every renderer and export draws them as absent. **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). **Fourth slice** (ADR 0048): **tile binning on the GPU** for heavy frames without masks or groups (count, prefix sum, scatter and tile-list passes, no atomics, no readback; the CPU binning stays the reference and does the rest; one tile format for both: an integer backdrop per tile and steps on the tiles' left edges): on Vulkan, 10k shapes at 4K in one texture 21.7 → 4.7 ms, 50k shapes 122 → 22.5 ms, the 50k-shape 4K stage 75 → 37 ms (Direct3D 12 keeps CPU binning: slower there in stage tiles); and **hairlines** for outline mode in both renderers (coverage by distance, one edge per segment): onion outlines on the 2,000-item stress scene as fast as tinted (GPU stage 73 → 10 ms, CPU stage 34–39 → 17 ms at 1080p). **Mid-session failures** (ADR 0092): a broken GPU stage hands the stage to the CPU at once with a status-bar notice and a log line, and is retried with a bounded backoff; driver errors on the window's device are logged instead of panicking (the #255 `Surface::configure` panic), and a lost window device autosaves and reopens the window on a safer way. Not yet: sharing a filtered layer across a frame's tiles, more than 16 images per tile, GPU binning inside masks and groups, flattening and stroking on the GPU, buffer reuse and fewer dispatches across tiles, hairlines for sub-pixel strokes, 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, icon buttons and right-click menu) act on the whole selection; with no frame selection F5 extends every layer with frames at or after the playhead, and F5/F6/F7 move the playhead on as in Animate (F6/F7 on a keyframe key the next frame; `all_layers`/`advance` headless); drag selected keyframes left or right to move them, and up or down onto other layers (the source keeps empty frames) (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; a motion tween's keys stretch in proportion, ADR 0083). Side dock tab strips never run under the panel menu (names shrink with an ellipsis, then the strip scrolls). Headless: `layers`/`count` on the frame commands, `timeline.move_keyframes`, `timeline.cut_frames/copy_frames/paste_frames`. Layers (show/lock/outline), **timeline polish** (ADR 0061): a per-layer **onion skin toggle** column (Alt-click solos; left-out layers aren't onion-skinned; Edit Multiple Frames unaffected), the colour square toggles **View as Outlines** in the layer colour **on the stage only** (exports, Test Movie and the player draw the artwork as it is), the **colour chip** opens the layer colour (swatches, hex, More…), **onion frames of the parent timeline** dimmed around a symbol edited in place, **Layer Height** 100/200/300 %, **Layer Properties** (double-click the layer icon; name, show/lock, type, outline colour, outlines, onion, height; one undo step), **Frame View** (Tiny/Small/Normal/Medium/Large, Short rows) with the frame zoom in the timeline's bottom bar (the header fits at the default window size, tested); headless `layer.set_onion/set_color/set_height/set_properties/properties`; XFL `heightMultiplier`. Not yet: folder onion toggles, onion of deeper parent timelines, multi-layer Layer Properties and layer transparency, frame thumbnails (Preview). **Layers by drag and all at once** (M8, from the issue tracker): drag a layer by its name to reorder it or drop it on a folder (a line shows where it lands; folders, masks and guides move whole; one undo step; `layer.move {before | after | into}`), the eye, padlock and outline square above the layer names act on every layer (`all` on the three toggles), and the line between the layer names and the frames drags (150–600 pt, kept in the preferences). Not yet: several selected layers dragged together, dragging a layer onto another scene. Keyframes, blank keyframes, insert/remove frames, classic tweens with **ease presets and custom eases** (ADR 0081: Classic Ease with a strength and Quad, Cubic, Quart, Quint, Sine, Back, Circ, Bounce and Elastic In/Out/In Out; custom eases of up to 64 Bézier points in the Custom Ease window, x kept monotonic, overshoot allowed, keyboard operable, **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, looping playback. **Onion skin and Edit Multiple Frames** (ADR 0047): onion markers on the frame ruler (drag the start and end brackets; Always Show Markers, Anchor Markers, Onion 2 / Onion 5 / Onion All, also on a right-click on the ruler), frames before and after the playhead tinted in their own colours (theme blue and green, changeable in the onion menu, Reset) and fading with distance, Outlines, Keyframes Only, locked layers left out as in Animate, each layer's onion frames under its own artwork and over the layers below; options saved in the preferences; the stage's frame cache keys every look apart. **Edit Multiple Frames** shows every keyframe within the markers at full strength and selects (click, Shift-click, marquee, Select All) and moves (drag, arrow keys) artwork across them, one undo step, motion tween paths moving with their objects. Headless: `frames.artwork`, `frames.edit_multiple`. **Edit Multiple Frames, complete** (ADR 0051): Cut, Copy, Paste (current frame), Paste in Place (back keyframe by keyframe, or a one-frame copy onto every keyframe between the markers), Clear, Align (Ctrl+Alt+1…6, To Stage), Rotate 90° and Flip, and **Free Transform** of the selection on every keyframe about one shared pivot (one box, one undo step per drag); raw shapes moved, transformed or pasted merge again on their own keyframe; **onion skin and Edit Multiple Frames inside a symbol edited in place**, on its own timeline and markers. Headless: `frames.transform`, `frames.align`, `frames.delete`, `frames.copy`, `frames.cut`, `frames.paste`, `frames.merge`, `merge` on `frames.edit_multiple`. Not yet: Duplicate/Distribute/Arrange and recolouring across keyframes, scaling a motion tween's object on several frames, a draggable pivot. **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, colour, filters, and instance filters tween; XFL custom and per-property eases import exactly; `ease.*` headless) + curve preview, rotation, skew, alpha, tint), each property its own curve of property keyframes with a per-segment ease (any preset, saved ease or custom ease of several segments, ADR 0081; 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. **Retiming** (ADR 0083): keys drag sideways in time (snapped to frames, never past a neighbour), Shift-click picks keys across properties, an All lane picks a frame's keys, Left/Right move picked keys with the curve focused; dragging a span's end stretches a motion tween's keys in proportion (Shift keeps them); a click picks a whole motion span and dragging (or a selection of whole tween spans) moves it at its length, Alt-drag copies; **Split Motion** / **Join Motion** (split then join is exact). Headless: `motion.move_keys`, `timeline.resize_span`, `timeline.move_spans`, `motion.split`, `motion.join`. Not yet: joining two independent motion paths, retiming from a span's left edge. **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. **Path points** (ADR 0038): with Subselection, double-click the path to add a point (shape and motion unchanged), Shift-click to select several anchors, Delete to remove them (the path refits through the rest; the ends stay), right-click for smooth/corner and Straighten; the Pen's Alt-click adds a point to a motion path or a selected shape; Ctrl-drag (⌘-drag) the path or its object, or edit Properties › Path start, to move the whole path with its timing exact. **Anchors pinned to frames** (ADR 0049): moving the object at a frame pins a path point there (a new anchor where it was put; after the last position key the path carries on), and the object passes every pinned point exactly on its frame, the X/Y eases timing it between pins; pinned points are diamonds with their frame number on the stage, blue keys in the Motion Editor's X/Y (dragging one moves its point) and holed diamonds on the timeline; Subselection's right-click pins to the playhead's frame or unpins, Properties › Frame has Pin Here / Unpin, F6 pins where the object is; point edits keep pins on their anchors; files without pins evaluate exactly as before. Headless: `timeline.create_motion_tween`, `motion.*` (`motion.set_path/clear_path/orient/add_point/delete_points/convert_point/move_path/pin_point/unpin_point`; `motion.info` reports `pins`). Not yet: retiming a pin by dragging its key in time, two pins on one anchor, XFL motion path keyframes, a marquee over path anchors, nudging or transforming a whole path, retiming keys, rescaling keys with the span, XFL motion-tween import. **Bones and IK, first slice** (ADR 0043): the Bone tool (M) drags from one symbol instance to another to join them with a bone on an armature layer (chains join end to start: a bone from a chained instance always starts at its joint; branches allowed, up to 256 bones); bones show as wedges in the layer colour; the Selection tool drags a bone (the grabbed point follows) or a posed instance to pose by cyclic coordinate descent (joint limits, pinned bones, one undo step per drag) and the root to move it all; poses are joint angles keyed per frame and tweened with the span's easing; Properties › Bone (angle, constrain min/max, pin, remove); `bone.*` headless; every export sees the pose. **Shape armatures** (ADR 0071): the Bone tool draws bones inside a shape (it moves to an armature layer as an object, outside merge drawing); its points are bound to the nearest bones automatically (weights by distance to each bone, up to four, summing to 1) and bend by linear blend skinning (handles with their anchors, strokes keep their width, the rest pose exact); the **Bind tool** (Shift+M) shows the points (squares, triangles where shared) and binds them by click, Shift/Ctrl-click or box; the same IK, poses and tweens; `bone.add_in_shape`, `bone.bind`, `bone.info {points}`. **Painted weights and reshaping** (ADR 0090): the Bind tool's **Paint Weights** brush (Add, Subtract, Smooth; size with `[`/`]`, strength; soft falloff) paints a bone's share onto the points under it, shown live as a heat map (blue none to red all) on the outline and points; weights stay normalised per point (the other bones share the rest, a point's only bone gives way to its nearest other bones), painted points are hand-bound, one undo step per stroke (1.15 ms for 32 dabs over 20,000 points); a focused point's weights as numbers in Properties › Bone (keyboard); Subselection edits a bound shape's outline at the rest pose (move, add, delete, smooth/corner) keeping the binding: moved points keep their weights, new points blend their neighbours', deleted points drop theirs, the rest pose exact; `bone.paint_weights`, `bone.set_weight`. **Springs, joint translation and members in place** (ADR 0084): joints slide along X/Y of what they start on, freely or within pixel limits, as part of each pose (IK slides only where turning can't reach); per-bone Spring and Damping swing bones after the motion and settle, evaluated as a pure replay of up to six seconds of motion (seeking equals playing bit for bit; 0.33 ms a frame for 16 sprung bones), shown on the stage, in Test Movie and every export, switched off per armature for posing; a picked bone's instance takes colour effect, blending and filters in place on every pose; `bone.set_translation`, `bone.set_spring`, `bone.enable_springs`. Not yet: runtime armatures, XFL import, mixing instances and shapes in one armature (proposed in ADR 0084 and 0090), reshaping at a posed frame, gravity and wind. **Asset Warp** (ADR 0079): the **Asset Warp tool** (Shift+Q) pins a shape or a bitmap (the first pin covers it with a warp mesh: a grid over its bounds, 2–48 cells along the longer side, Properties › Asset Warp); dragging a pin bends the artwork around the other pins by rigid moving least squares (Schaefer et al. 2006) at the mesh's vertices, live, one undo step per drag; Delete removes a pin; pins are added to every keyframe holding the artwork and their poses tween with classic tweens and easing; shapes bend through the mesh (straight edges exactly, curves split), bitmaps are drawn through its triangles by the CPU oracle (bilinear) and the GPU stage takes the same prepared fill (parity exact); the rest pose is the drawing bit for bit; every raster export, SVG (a bent bitmap baked as an image), Lottie and HTML (a bent bitmap reported) go through `evaluate`; `warp.add`, `warp.pin_add`, `warp.pin_move`, `warp.pin_remove`, `warp.remove`, `warp.info`. Not yet: as-rigid-as-possible solving on a mesh that follows the outline, symbols and text, binding warp pins to bones, a GPU textured-triangle path, bent bitmaps in HTML and Lottie, XFL import of warped assets. eases saved in the document and offered everywhere; copy/paste of an ease; classic tweens eased per property group: position, **Camera layer** (ADR 0027): the camera button in the timeline header or the Camera tool (C) adds a Camera layer on top; its frame shows on the stage in orange; drag to pan, turn with the round handle, wheel to zoom (one undo step per drag); Properties › Camera (position, zoom, rotation, tint, reset); keyframes and classic or motion tweens animate it; layer Depth gives pan parallax; View › Preview Through Camera shows the movie's picture (artwork tools pause there); hiding the camera layer turns it off; every export, Test Movie and the GPU stage see it. Headless: `camera.add/remove/set/info`, `layer.set_depth`. **Camera, second slice** (ADR 0082): layer depth in a pinhole perspective (deeper layers move and zoom less, draw behind nearer ones; depth 0 bit-exact), depth keyed over time (linear between keys), **Window › Layer Depth** (layers by depth, drag nearer or farther, key, attach), **Attach Layer to Camera** (timeline toggle; HUDs stay on screen), camera colour effects (Brightness, Tint, Advanced), and the Selection tool picking and moving artwork while previewing through the camera; headless `layer.set_depth {key, frame}`, `layer.remove_depth_key`, `layer.set_attached`, `layer.depths`, `element.pick {view: camera}`. Not yet: other tools while previewing, depth inside symbols, depth keys moving with inserted frames, XFL camera and layer-depth import (no public format description). **Motion guides**: guided layers (children of a guide through `Layer.parent`) have their classic tweens follow the guide's first path by arc length, from the point nearest each start keyframe to the point nearest its end (`geom::walk::PathWalk`), optionally orienting to the path; guide artwork is listed for picking and editing, drawn on the stage as a line, and never rendered or exported. | -| Drawing | Selection (click, shift-add, marquee, drag-move, arrow nudge; **across layers**, ADR 0044: a selection holds artwork on several visible, unlocked layers, the timeline marks them, Properties shows mixed values), **Free Transform (Q)**: scale from corner/edge handles (Shift proportional, Alt from centre), **skew** by dragging the line between two handles (the opposite edge stays, Alt about the centre; outside PR #176), 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; pasted raw shapes float, selected, until they are deselected, and Paste takes a picture copied in another app as a bitmap, ADR 0108; not yet: vectors copied in other apps). Free Transform: not yet a transformation point you can move (it is the box's centre) or a box that turns with a rotated object. **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, under or over the artwork, snap accuracy up to Always); Snap to Pixels; one snap engine for every drawing tool, the Selection tool's moves and Free Transform's handles (point › guide › line › grid › pixel, guides and grid per axis); stage only, never exported, on the CPU and GPU stage. Headless: `view.rulers`, `view.grid_show/grid_snap/grid_set`, `view.guides_show/guides_lock/guides_snap/guides_set`, `view.guide_add/guide_move/guide_delete/guides_clear`, `view.snap_pixels`, `view.aids`, `moving` on `draw.snap`. *Not yet:* units other than px, a movable ruler origin, a symbol's own guides, guides and grid from Animate files, Snap Align and Edit Snapping, snapping while rotating. 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. **Stroke styles** (ADR 0046): Properties › Style (Solid, Dashed with dash and gap, Dotted with spacing), Cap (None, Round, Square), Join (Miter, Round, Bevel) and Miter limit, also in the drawing tools' options for new strokes; drawn exactly by the oracle (butt and square caps, miters bevelled past the limit, dashes by arc length restarting per subpath, round dots, dashes keeping a width profile's widths; sub-pixel patterns solid and faded) and so by the GPU stage; the Ink Bottle carries the style and the Eyedropper picks it; merge drawing keeps it on cut pieces; shape tweens blend miter limits and dash lengths; SVG, HTML canvas and Lottie export write it. Headless: `stroke.set_style`, and `cap`, `join`, `miter`, `style`, `dash`, `dash_offset`, `dot_spacing` on `element.set_stroke`, the drawing commands and `paint.ink`. Not yet: Animate's ragged, stipple and hatched styles, multi-dash patterns in Properties (kept and editable by command), stroke scale modes and hairlines. **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`. **Selection tool on raw shapes** (ADR 0041): drag an unselected segment or fill edge to bend it through the pointer (every shape sharing the edge bends with it), an unselected corner or end to move it with every raw shape that shares it, a fill to move only that fill; points and selections snap to points, strokes and fill edges within 10 screen px (snap ring), and arrow nudges join ends within 0.2 px at their midpoint or onto a line that stays put; a corner or curve mark by the pointer shows what a drag does; the marquee selects the parts of raw fills and strokes under it, cut at its edges (taken back if nothing uses them, no undo step), and objects wholly inside; each drag one undo step, merged on release. Headless: `path.bend_segment`, `raw.move_point`, `raw.select_rect`, `raw.merge`, `raw.hit`, `snap` on `element.translate`. **Subselection on raw shapes and merging everywhere** (ADR 0042): with Subselection (A), a click on a raw line or fill shows the anchors of everything connected to it (once per shared point; hollow, selected ones solid) and the handles of the selected anchors' curves and of the clicked edge; drag an anchor to move it with the other selected ones and every shape on them, a handle to change the curve in every shape that has the edge, a line or fill to move everything connected; Shift adds or removes anchors; the marquee takes whole shapes on the active layer and selects the anchors inside; arrows nudge 1 screen px (Shift 10); one undo step per gesture, merged on release. **Snap to Objects** (View › Snapping, a magnet under the tools, the selection tools' options) switches the Selection and Subselection tools' snapping. The Paint Bucket's raw fills are exact (up to the lines and fill edges, from the planar merge) and join fills of their colour; pasted raw shapes cut what they land on; raw shapes from Animate files open raw and merged; gradient and bitmap fills take part in the merge. Headless: `raw.subselect`, `raw.subselect_rect`, `raw.points`, `raw.move_handle`, `with` on `raw.move_point`, `draw.snap_to_objects`, `object` on `paint.bucket`. Width profiles take part in the merge since ADR 0093. **Raw points and symbols in place** (ADR 0045): add a point on a raw edge (Pen Alt-click, Subselection double-click; every shape on the edge gets it, the curve unchanged), delete raw points (Delete; the shapes on each are joined across it so the drawing stays connected; points where three edges meet are kept), Make Smooth / Corner on raw points, smooth handle pairs (Alt breaks them; drawing objects too); the Line, Rectangle, Oval, PolyStar and Pen tools snap their points within 10 screen px (Snap to Objects, Ctrl+Shift+/); a double-click on an instance (or Ctrl+E, or a double-click in the Library) opens the symbol in place, the stage dimmed around it, the edit bar showing the path back, and every tool and command works on its timeline. Headless: `raw.add_point`, `raw.delete_points`, `raw.convert_points`, `draw.snap`, `smooth` on `raw.move_handle` and `path.move_points`, `symbol.edit`, `symbol.exit`. Not yet: rotated instances in place (they open upright). Onion skin and Edit Multiple Frames work inside a symbol since ADR 0051. **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`. **Paint Selection and Paint Inside** (ADR 0080): the paint is clipped to the selected fills' union, or to the fill (or closed-off empty area) the stroke starts in, exactly on the planar map, then merged under the lines; Paint Selection keeps the selection for the next stroke. Not yet: the live preview clipped as it paints. **Brush library, pressure curves and the Paint Brush (Y)** (ADR 0068, first slice): Window › Brush Library with seven built-in brushes made only of parameters (Pencil, Ink Pen, Flat Calligraphy, Round Taper, Marker, Chalk with a deterministic worn edge, Dotted stamps), each with a stroke preview drawn by the renderer; brushes of your own saved by name in your preferences, renamed, deleted (asks first) and moved between computers as a JSON brush set; a pressure curve editor (Linear, Soft, Firm, or your own points) driving size and, optionally, the stroke's opacity; tapers, dab spacing and a rough edge in Properties; Velocity (mouse speed as pressure, off by default); the Paint Brush draws a width-profiled stroke in the stroke colour that the Width tool edits. Headless: `brush.preset_list/save/rename/delete/export/import`, `preset`, `curve`, `as_stroke` and the shaping params on `draw.brush`. **Tilt, texture and scatter** (ADR 0093): per-sample pen tilt (Pointer Events altitude and azimuth in `draw.brush` points) turns the tip by the azimuth and widens it up to 2× as the pen leans (Brush › Tilt: Angle, Width, shown once a pen reports tilt; the Paint Brush's width too), a fixed paper grain of holes (Texture) and dabs thrown either side (Scatter), all vector fills; built-in Charcoal and Spatter (nine brushes). Not yet: reading tilt from the pen on desktop systems (winit 0.30 reports it only on iOS), opacity varying along a stroke, bitmap or art brushes, Eraser presets and pressure. **Eraser (E)** (ADR 0034, first slice): sweeps the Brush's tip and takes what it covers out of the raw shapes on the active layer (the sweep is a fill in the planar merge that comes out empty); Erase Normal, Erase Fills, Erase Lines, Erase Selected Fills and Erase Inside; the Faucet deletes a whole fill or line with a click; drawing objects, symbols and text are kept; a stroke that erases nothing leaves no undo step; live preview, `[` and `]` sizes, one undo step per stroke; double-clicking the tool (or Erase Everything… in its options) clears the visible, unlocked layers at this frame after asking. **Eyedropper (I)** (first slice): a click on a fill picks its paint (solid, or a gradient or bitmap kept where it is on the stage, as Lock Fill) into the fill swatch, a click on a line picks its colour, width and profile; with shapes selected it applies the style to them; then it becomes the Paint Bucket or the Ink Bottle; Shift-click picks into the other swatch only. Headless: `draw.erase`, `draw.faucet`, `draw.erase_all`, `paint.pick`, `paint.apply_style`. Since ADR 0093: width-profiled lines erase and merge, each piece keeping its widths; gradient pieces keep their gradient where it was; inside an open symbol or drawing object the Eraser erases its shapes, and on the stage the status bar says how. Not yet: eraser pressure, picking text styles, an eyedropper cursor (a bitmap's pixel colour comes from the colour picker's eyedropper, ADR 0109). **Modify › Shape, the picker's eyedropper and transformation origins** (ADR 0109, M1; #179, #288, #296): Convert Lines to Fills (a line's exact outline as curves, with caps, joins, dashes and width profile, within a pixel of what the renderer strokes; raw fills join the drawing, objects stay objects), Expand Fill (exact offsets in stage pixels: expanding rounds corners, insetting keeps them) and Soften Fill Edges (1 to 50 bands, alpha stepping down, expand or inset, on colours and gradients), each with Animate's dialog; while a colour picker is open a click on the stage takes the colour drawn there (`paint.sample`: gradients, bitmaps, lines, effects), with a preview chip and Esc to cancel; Free Transform's Transform about (the whole selection, each object's registration point, each object's centre), marked on the stage, followed by Rotate 90° and Flip, with a bindable command to cycle. Not yet: a draggable transformation point, origins with Edit Multiple Frames and in Properties' fields, previews in the two dialogs, miter corners for Expand Fill, picking from outside the window. **Colour picker and drawing-tool fixes from user reports** (M1): every colour swatch (the Tools panel's fill and stroke squares too) opens one picker with Animate's web-safe swatches (216 colours, greys and primaries), the colours mixed or typed this session, a hex field, an alpha (a solid fill's own, and a different one on each gradient stop) and the full mixer; the Tools squares offer No Colour and recolour selected shapes; drawing tools leave nothing selected after a stroke and the Selection tool's box has no handles (they are Free Transform's); Break Apart turns drawing objects into merged drawing; Ctrl-drag on a raw edge adds a corner point; the Pencil and Line show no fill. **Swatches panel** (ADR 0078): Window › Swatches, the document's saved colours and gradients (in the `.anicraft` file; a default set for new documents and older files); click applies to the selection and the tool colour, to the stroke or fill that is active (Tools squares, Colour panel or the panel's toggle; gradients always to the fill); + adds the active colour or gradient, Duplicate, Delete, drag (or Alt+arrows) to reorder, names on hover, Clear (keeps black and white) and Load Default Swatches (ask first, undoable); import and export as a JSON swatch file, GIMP `.gpl` import; the colour picker shows the document's swatches and the fill picker its gradient swatches. Headless: `swatch.list/add/remove/move/duplicate/rename/apply/clear/reset/import/export`. Not yet: swatch folders, sorting by colour, bitmap swatches, Save as Default, XFL swatch import (no public description), Adobe `.aco`/`.ase`/`.clr` (proprietary). The layer footer is icon buttons (New Layer, Delete, New Folder, Up, Down) that fit at any size and language. **Groups and Combine Objects** (ADR 0073): Modify › Group (Ctrl+G) / Ungroup (Ctrl+Shift+G), a group element whose members are a one-layer, one-frame timeline, opened in place by a double-click like a symbol (every tool works inside; raw shapes merge only with each other); nested groups; exports, player, sounds and the Library see inside; XFL `DOMGroup` imports as groups. Combine Objects › Union, Intersect, Punch, Crop on the planar map (analytic area tests). Selection tool: Alt-drag copies, Shift constrains to 45° (Ctrl/⌘-drag corners: #257). **Drawing parity leftovers** (ADR 0080): PolyStar's Shape (Polygon or Star), sides 3–32 and star point size 0–1 in its options (`shape`, `sides`, `point_size` on `draw.star`); a double-click (or Ctrl+E) opens a drawing object in place, its raw shapes merging only with each other, and it closes as one object again (a group of the pieces when an edit leaves several); **Modify › Transform › Envelope**: a Bézier mesh of corner and tangent handles bends the selected shapes and drawing objects, one undo step per drag, baked like Animate's (no Delete Envelope needed), undo restoring the mesh; headless `modify.envelope`, `modify.envelope_move`, `modify.envelope_close`. *Not yet:* gradient and bitmap strokes (proposed in ADR 0080), envelope handles from the keyboard, an envelope on symbols, text or groups, drawing objects edited without opening them (#181), Combine across layers. **Rulers, grid and guides** (ADR 0076): View › Rulers (stage pixels, following zoom and pan, pointer marked); guides per scene saved in the document, dragged from a ruler, moved with the Selection tool, dragged back to delete, Show/Lock/Snap/Edit/Add/Clear (Edit Guides lists and adds them from the keyboard); a grid (spacing, | +| Drawing | Selection (click, shift-add, marquee, drag-move, arrow nudge; **across layers**, ADR 0044: a selection holds artwork on several visible, unlocked layers, the timeline marks them, Properties shows mixed values), **Free Transform (Q)**: scale from corner/edge handles (Shift proportional, Alt from centre), **skew** by dragging the line between two handles (the opposite edge stays, Alt about the centre; outside PR #176), 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; pasted raw shapes float, selected, until they are deselected, and Paste takes a picture copied in another app as a bitmap, ADR 0108; not yet: vectors copied in other apps). Free Transform: not yet a transformation point you can move (it is the box's centre) or a box that turns with a rotated object. **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, under or over the artwork, snap accuracy up to Always); Snap to Pixels; one snap engine for every drawing tool, the Selection tool's moves and Free Transform's handles (point › guide › line › grid › pixel, guides and grid per axis); stage only, never exported, on the CPU and GPU stage. Headless: `view.rulers`, `view.grid_show/grid_snap/grid_set`, `view.guides_show/guides_lock/guides_snap/guides_set`, `view.guide_add/guide_move/guide_delete/guides_clear`, `view.snap_pixels`, `view.aids`, `moving` on `draw.snap`. *Not yet:* units other than px, a movable ruler origin, a symbol's own guides, guides and grid from Animate files, Snap Align and Edit Snapping, snapping while rotating. 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. **Stroke styles** (ADR 0046): Properties › Style (Solid, Dashed with dash and gap, Dotted with spacing), Cap (None, Round, Square), Join (Miter, Round, Bevel) and Miter limit, also in the drawing tools' options for new strokes; drawn exactly by the oracle (butt and square caps, miters bevelled past the limit, dashes by arc length restarting per subpath, round dots, dashes keeping a width profile's widths; sub-pixel patterns solid and faded) and so by the GPU stage; the Ink Bottle carries the style and the Eyedropper picks it; merge drawing keeps it on cut pieces; shape tweens blend miter limits and dash lengths; SVG, HTML canvas and Lottie export write it. Headless: `stroke.set_style`, and `cap`, `join`, `miter`, `style`, `dash`, `dash_offset`, `dot_spacing` on `element.set_stroke`, the drawing commands and `paint.ink`. Not yet: Animate's ragged, stipple and hatched styles, multi-dash patterns in Properties (kept and editable by command), stroke scale modes and hairlines. **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`. **Selection tool on raw shapes** (ADR 0041): drag an unselected segment or fill edge to bend it through the pointer (every shape sharing the edge bends with it), an unselected corner or end to move it with every raw shape that shares it, a fill to move only that fill; points and selections snap to points, strokes and fill edges within 10 screen px (snap ring), and arrow nudges join ends within 0.2 px at their midpoint or onto a line that stays put; a corner or curve mark by the pointer shows what a drag does; the marquee selects the parts of raw fills and strokes under it, cut at its edges (taken back if nothing uses them, no undo step), and objects wholly inside; each drag one undo step, merged on release. Headless: `path.bend_segment`, `raw.move_point`, `raw.select_rect`, `raw.merge`, `raw.hit`, `snap` on `element.translate`. **Subselection on raw shapes and merging everywhere** (ADR 0042): with Subselection (A), a click on a raw line or fill shows the anchors of everything connected to it (once per shared point; hollow, selected ones solid) and the handles of the selected anchors' curves and of the clicked edge; drag an anchor to move it with the other selected ones and every shape on them, a handle to change the curve in every shape that has the edge, a line or fill to move everything connected; Shift adds or removes anchors; the marquee takes whole shapes on the active layer and selects the anchors inside; arrows nudge 1 screen px (Shift 10); one undo step per gesture, merged on release. **Snap to Objects** (View › Snapping, a magnet under the tools, the selection tools' options) switches the Selection and Subselection tools' snapping. The Paint Bucket's raw fills are exact (up to the lines and fill edges, from the planar merge) and join fills of their colour; pasted raw shapes cut what they land on; raw shapes from Animate files open raw and merged; gradient and bitmap fills take part in the merge. Headless: `raw.subselect`, `raw.subselect_rect`, `raw.points`, `raw.move_handle`, `with` on `raw.move_point`, `draw.snap_to_objects`, `object` on `paint.bucket`. Width profiles take part in the merge since ADR 0093. **Raw points and symbols in place** (ADR 0045): add a point on a raw edge (Pen Alt-click, Subselection double-click; every shape on the edge gets it, the curve unchanged), delete raw points (Delete; the shapes on each are joined across it so the drawing stays connected; points where three edges meet are kept), Make Smooth / Corner on raw points, smooth handle pairs (Alt breaks them; drawing objects too); the Line, Rectangle, Oval, PolyStar and Pen tools snap their points within 10 screen px (Snap to Objects, Ctrl+Shift+/); a double-click on an instance (or Ctrl+E, or a double-click in the Library) opens the symbol in place, the stage dimmed around it, the edit bar showing the path back, and every tool and command works on its timeline. Headless: `raw.add_point`, `raw.delete_points`, `raw.convert_points`, `draw.snap`, `smooth` on `raw.move_handle` and `path.move_points`, `symbol.edit`, `symbol.exit`. Not yet: rotated instances in place (they open upright). Onion skin and Edit Multiple Frames work inside a symbol since ADR 0051. **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`. **Paint Selection and Paint Inside** (ADR 0080): the paint is clipped to the selected fills' union, or to the fill (or closed-off empty area) the stroke starts in, exactly on the planar map, then merged under the lines; Paint Selection keeps the selection for the next stroke. Not yet: the live preview clipped as it paints. **Brush library, pressure curves and the Paint Brush (Y)** (ADR 0068, first slice): Window › Brush Library with seven built-in brushes made only of parameters (Pencil, Ink Pen, Flat Calligraphy, Round Taper, Marker, Chalk with a deterministic worn edge, Dotted stamps), each with a stroke preview drawn by the renderer; brushes of your own saved by name in your preferences, renamed, deleted (asks first) and moved between computers as a JSON brush set; a pressure curve editor (Linear, Soft, Firm, or your own points) driving size and, optionally, the stroke's opacity; tapers, dab spacing and a rough edge in Properties; Velocity (mouse speed as pressure, off by default); the Paint Brush draws a width-profiled stroke in the stroke colour that the Width tool edits. Headless: `brush.preset_list/save/rename/delete/export/import`, `preset`, `curve`, `as_stroke` and the shaping params on `draw.brush`. **Tilt, texture and scatter** (ADR 0093): per-sample pen tilt (Pointer Events altitude and azimuth in `draw.brush` points) turns the tip by the azimuth and widens it up to 2× as the pen leans (Brush › Tilt: Angle, Width, shown once a pen reports tilt; the Paint Brush's width too), a fixed paper grain of holes (Texture) and dabs thrown either side (Scatter), all vector fills; built-in Charcoal and Spatter (nine brushes). Not yet: reading tilt from the pen on desktop systems (winit 0.30 reports it only on iOS), opacity varying along a stroke, bitmap or art brushes, Eraser presets and pressure. **Eraser (E)** (ADR 0034, first slice): sweeps the Brush's tip and takes what it covers out of the raw shapes on the active layer (the sweep is a fill in the planar merge that comes out empty); Erase Normal, Erase Fills, Erase Lines, Erase Selected Fills and Erase Inside; the Faucet deletes a whole fill or line with a click; drawing objects, symbols and text are kept; a stroke that erases nothing leaves no undo step; live preview, `[` and `]` sizes, one undo step per stroke; double-clicking the tool (or Erase Everything… in its options) clears the visible, unlocked layers at this frame after asking. **Eyedropper (I)** (first slice): a click on a fill picks its paint (solid, or a gradient or bitmap kept where it is on the stage, as Lock Fill) into the fill swatch, a click on a line picks its colour, width and profile; with shapes selected it applies the style to them; then it becomes the Paint Bucket or the Ink Bottle; Shift-click picks into the other swatch only. Headless: `draw.erase`, `draw.faucet`, `draw.erase_all`, `paint.pick`, `paint.apply_style`. Since ADR 0093: width-profiled lines erase and merge, each piece keeping its widths; gradient pieces keep their gradient where it was; inside an open symbol or drawing object the Eraser erases its shapes, and on the stage the status bar says how. Not yet: eraser pressure, picking text styles, an eyedropper cursor (a bitmap's pixel colour comes from the colour picker's eyedropper, ADR 0109). **Modify › Shape, the picker's eyedropper and transformation origins** (ADR 0109, M1; #179, #288, #296): Convert Lines to Fills (a line's exact outline as curves, with caps, joins, dashes and width profile, within a pixel of what the renderer strokes; raw fills join the drawing, objects stay objects), Expand Fill (exact offsets in stage pixels: expanding rounds corners, insetting keeps them) and Soften Fill Edges (1 to 50 bands, alpha stepping down, expand or inset, on colours and gradients), each with Animate's dialog; while a colour picker is open a click on the stage takes the colour drawn there (`paint.sample`: gradients, bitmaps, lines, effects), with a preview chip and Esc to cancel; Free Transform's Transform about (the whole selection, each object's registration point, each object's centre), marked on the stage, followed by Rotate 90° and Flip, with a bindable command to cycle. Not yet: origins with Edit Multiple Frames, previews in the two dialogs, miter corners for Expand Fill, picking from outside the window. **The transformation point, a turning box and layer opacity** (ADR 0111, M1; #302, #280, #178, #183, #175, #279): Free Transform's white circle is dragged (snapping to the box's handles and centre, free with Alt, also outside the box) and double-clicked back to the centre; a symbol instance keeps its point in the file (`pivot`, in its own space) and Free Transform, Rotate 90° and Flip, Properties' Scale and Rotation (a Pivot row with Reset) and classic and motion tweens turn and scale it about it (an arm swings on its shoulder); raw shapes, groups, text and several objects have a point for the selection while the tool is held; one selected element shows its own box, turned, scaled and skewed with it, its handles acting along its own axes; **layer opacity** (Layer Properties, the layer's right-click menu, a percentage beside the name): the layer fades as one group in `evaluate`, a folder fades its layers, in every export and on the CPU and GPU stage. Headless: `modify.transformation_point`, `modify.reset_transformation_point`, `layer.set_opacity`, `opacity` on `layer.set_properties`. Not yet: the transformation point of Animate files' instances, a kept point for groups, text and drawing objects, the point with Edit Multiple Frames and on motion guides, opacity keyed over time, an authoring-only layer transparency. **Colour picker and drawing-tool fixes from user reports** (M1): every colour swatch (the Tools panel's fill and stroke squares too) opens one picker with Animate's web-safe swatches (216 colours, greys and primaries), the colours mixed or typed this session, a hex field, an alpha (a solid fill's own, and a different one on each gradient stop) and the full mixer; the Tools squares offer No Colour and recolour selected shapes; drawing tools leave nothing selected after a stroke and the Selection tool's box has no handles (they are Free Transform's); Break Apart turns drawing objects into merged drawing; Ctrl-drag on a raw edge adds a corner point; the Pencil and Line show no fill. **Swatches panel** (ADR 0078): Window › Swatches, the document's saved colours and gradients (in the `.anicraft` file; a default set for new documents and older files); click applies to the selection and the tool colour, to the stroke or fill that is active (Tools squares, Colour panel or the panel's toggle; gradients always to the fill); + adds the active colour or gradient, Duplicate, Delete, drag (or Alt+arrows) to reorder, names on hover, Clear (keeps black and white) and Load Default Swatches (ask first, undoable); import and export as a JSON swatch file, GIMP `.gpl` import; the colour picker shows the document's swatches and the fill picker its gradient swatches. Headless: `swatch.list/add/remove/move/duplicate/rename/apply/clear/reset/import/export`. Not yet: swatch folders, sorting by colour, bitmap swatches, Save as Default, XFL swatch import (no public description), Adobe `.aco`/`.ase`/`.clr` (proprietary). The layer footer is icon buttons (New Layer, Delete, New Folder, Up, Down) that fit at any size and language. **Groups and Combine Objects** (ADR 0073): Modify › Group (Ctrl+G) / Ungroup (Ctrl+Shift+G), a group element whose members are a one-layer, one-frame timeline, opened in place by a double-click like a symbol (every tool works inside; raw shapes merge only with each other); nested groups; exports, player, sounds and the Library see inside; XFL `DOMGroup` imports as groups. Combine Objects › Union, Intersect, Punch, Crop on the planar map (analytic area tests). Selection tool: Alt-drag copies, Shift constrains to 45° (Ctrl/⌘-drag corners: #257). **Drawing parity leftovers** (ADR 0080): PolyStar's Shape (Polygon or Star), sides 3–32 and star point size 0–1 in its options (`shape`, `sides`, `point_size` on `draw.star`); a double-click (or Ctrl+E) opens a drawing object in place, its raw shapes merging only with each other, and it closes as one object again (a group of the pieces when an edit leaves several); **Modify › Transform › Envelope**: a Bézier mesh of corner and tangent handles bends the selected shapes and drawing objects, one undo step per drag, baked like Animate's (no Delete Envelope needed), undo restoring the mesh; headless `modify.envelope`, `modify.envelope_move`, `modify.envelope_close`. *Not yet:* gradient and bitmap strokes (proposed in ADR 0080), envelope handles from the keyboard, an envelope on symbols, text or groups, drawing objects edited without opening them (#181), Combine across layers. **Rulers, grid and guides** (ADR 0076): View › Rulers (stage pixels, following zoom and pan, pointer marked); guides per scene saved in the document, dragged from a ruler, moved with the Selection tool, dragged back to delete, Show/Lock/Snap/Edit/Add/Clear (Edit Guides lists and adds them from the keyboard); a grid (spacing, | | 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 `/plugins` or `ANICRAFT_PLUGINS`; CLI `--plugins`. Samples in Rust (Star Field, Jitter Selection, guest SDK) in `examples/plugins`. Frame scripts: see Interactivity. **Exporter and ease plug-ins** (ADR 0088): `kind: "exporter"` declares a format (name, extension, options) and gets evaluated frames (`movie`, `frame`: the flattened display list, never the document), returning the file's bytes from `ac_export` (64 MiB cap, 5·10¹⁰ instructions, 10 min); File › Export lists it with an Export window (options, frames, file, progress bar and Cancel on a worker thread); `file.export_plugin`, `file.export_formats`, `anicraft-cli export --format ` and `formats`. `kind: "ease"` declares named eases, `ac_ease(i, t)` sampled into 257 values at load (NaN, unbounded or end-missing eases refused); `Easing::Sampled` keeps the table in the document, so it plays the same without the plug-in; the ease menus list them under Plug-in eases; `{plugin, ease}` easing params. Samples: Plain Text Frames and Stepped Eases, built and run in CI. Not yet: plug-in formats in Publish, bitmaps' pixels and sounds for exporters, ease plug-ins with parameters, background runs of command plug-ins, 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. **A window of its own on the desktop** (ADR 0062): sized to the stage at 100 % (smaller to fit the screen), titled with the document, back where it was last (not on Wayland, where the desktop places windows), with the keyboard when it opens; Esc or Ctrl+W (⌘W) closes it, Ctrl+Enter restarts it in place, and the editor's Ctrl/Alt shortcuts work from it; floating inside the editor in the web build, where the system can't open windows (it says so), or by choice in Preferences › Test Movie. Not yet: full screen, zoom in the movie window, remembering its size. 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; **filters and Subtract/Invert in the page** (ADR 0072: `filters.js`, a port of the renderer's filters run over the group's pixels on a layer that reaches past the canvas by the filters' reach, Subtract and Invert composited per pixel, results kept while the group is unchanged; equal to the oracle's pixels within 9.3e-4 in Boa; 3.4 ms a frame for the demo's filters at 1080p while they change); Web Audio for Event/Start/Stop/Stream sounds; bitmap tints, 9-slice scaling and plug-in frame scripts reported. Not yet: 9-slice in the page, keeping a moving filtered group's pixels, filters off the main thread. **Kept frame scripts** (ADR 0013 tier 1): scripts written in another language (an Animate document's ActionScript) kept verbatim on keyframes with their language, symbol linkage classes and the document class; the Actions panel's **Script** view (monospace editor with line numbers, language, live and undoable), the same "a" marker, Class rows in Properties; `script.set/clear/list/set_class`; **ActionScript timeline subset runs** (ADR 0013 tier 2): a hand-written, bounded lexer and parser (`anicraft_actions::as3`) lower stop/play/go to/next and previous frame and scene on instance-name paths, mouse listeners (click, down, up, roll over and out; named or inline functions, `currentTarget`), `trace` and property settings to the action IR, compiled once per script; anything else is reported with line and column and the script doesn't run (never half-run), `navigateToURL` and the like are ignored and noted; the player keeps listeners per instance, Test Movie's Output says which scripts run and which don't and why, the Script view lists problems in place, the XFL report and `script.list/check` say what runs, and the HTML page runs the same steps (`player.js` checked against the Rust player). **ActionScript small logic** (ADR 0052): scripts compile to a small typed script IR evaluated by the player with fuel (100,000 per script or listener call, 1,000,000 per step; an endless loop or a run-time error stops its script with an Output line and the movie plays on): typed variables (Number, int, uint, Boolean, String, untyped) kept per timeline instance across its frame scripts, expressions as ECMA-262 has them, `if`/`else`, `for`/`while`/`do`, functions with parameters, results and recursion, called from any frame of the same timeline (a timeline-level link step; names that aren't there keep the script from running, said in place), property reads of instances and timelines (`x`, `y`, `alpha`, `visible`, `rotation`, `scaleX/Y`, `currentFrame`, `totalFrames`, `currentLabel`, `mouseX/Y`, `name`), `removeEventListener`, `Event.ENTER_FRAME`, `KeyboardEvent.KEY_DOWN/KEY_UP` on the stage with `e.keyCode`, `e.target`/`e.currentTarget`, seeded `Math.random()`; keyboard in Test Movie and the HTML page, `control.test_movie` key events and `seed`; `player.js` mirrors the evaluator, checked step by step in Boa. Not yet: ActionScript `switch`, `for in`, arrays and objects, string methods, closures, event bubbling, mouse listeners on the stage, ActionScript 1.0/2.0, scripts on instances, filters and keyboard focus in the HTML page, sound actions, keyboard events, variables, persistent script state, masks in hit tests, a separate OS window. **Buttons, complete** (ADR 0057): a button open in place names its frames Up, Over, Down and Hit on the timeline and shows its Hit area translucent over the other states; Test Movie has **Show hit areas**; sounds on its frames play as its state changes. | | Headless | CLI: info, render, render-seq, **gif**, **apng**, **webp**, 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. **Live control** (ADR 0104, `docs/control-protocol.md`): `anicraft --control ` and `anicraft-cli mcp --bridge ` run the same tools on the open window, on this computer only, with a per-run token in `control.json`. | @@ -38,7 +38,7 @@ This integration depends on craft-libs #1962 and still requires hosted parity va | M | Theme | Exit criteria | |---|---|---| | **M0** | Foundations *(this version)* | Workspace + layering; document model; timeline evaluation with classic tweens and easing; CPU oracle renderer; command registry with undo; `.anicraft`; CLI render + JSON-lines; egui shell with stage, tools, timeline, properties, library; `--screenshot`. | -| **M1** | Authoring core ✅ *(v0.1.0)* | ~~Free transform tool with handles~~ ✅; ~~subselection and Bézier point editing~~ ✅; ~~Pen and Pencil~~ ✅; ~~Paint bucket / Ink bottle~~ ✅; ~~copy/paste~~ ✅, ~~duplicate, arrange~~ ✅, ~~align~~ ✅ (commands and menus; and the dock's Align panel ✅); ~~onion skin~~ ✅ (markers, tint, fade, outlines, keyframes only, Edit Multiple Frames: ADR 0047; its delete, copy/paste, Free Transform, align and re-merge, and both inside symbols: ADR 0051); ~~frame selection ranges in the timeline (multi-frame insert/remove/move keyframes by drag)~~ ✅ (including between layers); ~~PNG sequence + animated GIF export~~ ✅; ~~keyboard shortcut map editor~~ ✅; ~~groups, Combine Objects, Selection-tool modifiers~~ ✅ first slice (ADR 0073); ~~gradient editor, Gradient Transform tool and Lock Fill~~ ✅ (ADR 0074: the colour picker sets a fill's type, with a keyboard-operable stop bar, overflow, Linear RGB, focal point and bitmap fills; the Gradient Transform tool (F)); ~~rulers, grid and guides with one snap engine~~ ✅ first slice (ADR 0076); ~~Modify › Shape (Convert Lines to Fills, Expand Fill, Soften Fill Edges), the colour picker's eyedropper and transformation origins for several objects~~ ✅ first slice (ADR 0109). | +| **M1** | Authoring core ✅ *(v0.1.0)* | ~~Free transform tool with handles~~ ✅; ~~subselection and Bézier point editing~~ ✅; ~~Pen and Pencil~~ ✅; ~~Paint bucket / Ink bottle~~ ✅; ~~copy/paste~~ ✅, ~~duplicate, arrange~~ ✅, ~~align~~ ✅ (commands and menus; and the dock's Align panel ✅); ~~onion skin~~ ✅ (markers, tint, fade, outlines, keyframes only, Edit Multiple Frames: ADR 0047; its delete, copy/paste, Free Transform, align and re-merge, and both inside symbols: ADR 0051); ~~frame selection ranges in the timeline (multi-frame insert/remove/move keyframes by drag)~~ ✅ (including between layers); ~~PNG sequence + animated GIF export~~ ✅; ~~keyboard shortcut map editor~~ ✅; ~~groups, Combine Objects, Selection-tool modifiers~~ ✅ first slice (ADR 0073); ~~gradient editor, Gradient Transform tool and Lock Fill~~ ✅ (ADR 0074: the colour picker sets a fill's type, with a keyboard-operable stop bar, overflow, Linear RGB, focal point and bitmap fills; the Gradient Transform tool (F)); ~~rulers, grid and guides with one snap engine~~ ✅ first slice (ADR 0076); ~~Modify › Shape (Convert Lines to Fills, Expand Fill, Soften Fill Edges), the colour picker's eyedropper and transformation origins for several objects~~ ✅ first slice (ADR 0109); ~~a movable transformation point, a selection box that turns with the object, and layer opacity~~ ✅ first slice (ADR 0111). | | **M2** | Model at scale | ~~`Arc` structural sharing (O(changed) undo)~~ done early (ADR 0001); ~~scenes~~ ✅ (ADR 0011); ~~layer folders~~ ✅, ~~guide and motion-guide layers~~ ✅; ~~mask layers~~ ✅; ~~Movie Clip and Button behaviours~~ ✅ (playback; button states and scripting come with M6); ~~group alpha / offscreen compositing~~ ✅; ~~shape tween~~ ✅, ~~shape hints~~ ✅ (ADR 0023); ~~motion tween + Motion Editor curves~~ ✅ first slice (ADR 0016; the ease presets, saved and custom eases of ADR 0081 per segment); ~~Motion Editor and timeline retiming, Split/Join Motion~~ ✅ (ADR 0083); ~~motion paths on the stage with orient to path~~ ✅ first slice (ADR 0030), ~~path point add/delete/convert and moving the whole path~~ ✅ (ADR 0038), ~~anchors pinned to frames~~ ✅ (ADR 0049; 3D and XFL import later); ~~library management~~ ✅ first slice (ADR 0050: folders, rename, duplicate, Swap Symbol, use counts and unused items, sort, search, preview, Allow Smoothing), ~~Library and Properties polish~~ ✅ (ADR 0053: drag onto the stage, Swap Bitmap, Convert to Symbol folders, mixed on every Properties row), ~~9-slice scaling~~ ✅ first slice (ADR 0055); ~~colour effects, complete~~ ✅ (ADR 0056: Properties' Style menu with None, Brightness, Tint, Advanced and Alpha, one exact colour transform in the CPU oracle, the GPU stage, SVG `feColorMatrix`, HTML canvas and Lottie, XFL `Color` import with a corpus package, classic tweens across styles, motion tween tint colour, brightness and Advanced tracks; not yet: a colour picker for the Motion Editor's tint colour); ~~MCP server~~ ✅; perf budgets ✅ (machine-independent ones gate every PR; timing via `bench --check` on a known machine, CI once a benchmark runner exists); ~~layering check~~ ✅ (`src/architecture_tests.rs`, runs with `cargo test`). | | **M3** | GPU stage *(in progress; the default stage renderer since ADR 0032)* | ~~wgpu renderer behind a feature flag~~ ✅ first slice (ADR 0019: the oracle's fills, CPU tile binning with backdrops, compute coverage; gradient tables in a storage buffer); ~~per-pixel parity tests vs the CPU oracle~~ ✅ (max 1/255, mean < 0.0001/255); ~~4K at 60 fps for 1,000 shapes~~ ✅ (8.8–9.0 ms); ~~no-readback textures, masks/groups/blend modes on the GPU~~ ✅ second slice (ADR 0029: window's device, 4K 10k shapes in 10.2 ms as tiles); ~~GPU binning~~ ✅ fourth slice (ADR 0048: heavy frames without masks or groups binned on the GPU, 50k shapes at 4K 122 → 22.5 ms in one texture; outline mode's hairlines as fast as tinted onion skin); ~~bitmaps and filters on the GPU~~ ✅ third slice (ADR 0032: bitmaps byte-identical, filters max 1/255; 4K filtered sample 3.9 ms, 200 bitmaps 4.4 ms); ~~hardware breadth~~ ✅ Vulkan and DX12 (FXC), software adapters refused, oracle-checked self-test; ~~GPU as the default stage renderer~~ ✅ (`gpu-stage` on by default for the app, automatic CPU fallback); ~~surviving GPU failures mid-session~~ ✅ (ADR 0092: the stage drops to the CPU at once and retries the GPU after 3, 15, 60 and 300 s or on a resize; the window's device gets an error handler and a loss callback instead of wgpu's panic, a failing surface is reconfigured then recreated, and a lost window device autosaves, reopens the window a safer way and makes the next 3 starts try it late; not yet: recreating the window's device in place, which eframe doesn't offer); next: GPU binning inside masks and groups, shared filtered layers across tiles, an image atlas, GPU exports. | | **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); ~~larger self-authored corpus with golden render tests~~ ✅ (ADR 0035: twelve packages covering every mapped feature, exact report expectations, hostile variants, CPU-oracle goldens); ~~`.fla` variants of the corpus and a hardened zip reader~~ ✅ (ADR 0054: nine zip layouts imported identically to the folder, ZIP64, CP437 names, a 9,664-archive hostile fuzz; a 54.6 MB `.fla` imports in 0.31 s); ~~sound and video items, self-extracting and top-folder `.fla` archives~~ ✅ (ADR 0086: sound effects and custom envelopes, every sound and video that doesn't come across named with its format, Screen Video stills, zipped XFL folders and self-extracting stubs; not yet: sound in/out points, AIFF and compressed WAV, video playback); ~~SVG import (Import to Stage)~~ ✅, ~~SVG frame export~~ ✅; ~~Lottie export~~ ✅ (~~easing curves instead of per-frame keys~~ ✅, ADR 0089: keyframes with Bézier eases, moving artwork under group transforms, playback parity at every frame; not yet: motion along curved guides as spatial tangents, orient to path, nested tweens as nested transforms); ~~sprite sheet + JSON~~ ✅; ~~MP4/WebM via ffmpeg pipe~~ ✅; ~~animated PNG and WebP~~ ✅ (ADR 0063; lossless WebP; lossy WebP not yet). | diff --git a/src/a11y.rs b/src/a11y.rs index 74111b8e..91dfa468 100644 --- a/src/a11y.rs +++ b/src/a11y.rs @@ -443,7 +443,7 @@ mod tests { for tool in [Tool::Bone, Tool::Bind, Tool::Warp, Tool::Rect, Tool::Star, Tool::Text, Tool::Pencil, Tool::Brush, Tool::PaintBrush, 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", "motionedit", "motionpins", "motionpinsspan", "rawsub", "camera", "cameraview", "bones", "springbones", "shapebones", "shapeweights", "mixedbones", "warp", "sound", "envelope", "prefs", "shortcuts", "palette", "about", "files", "licenses", "confirm", "recovery", "frames", "actions", "script", "scriptproblems", "testscript", "onion", "onionmenu", "editmultiple", "library", "librarymenu", "edittransform", "onionsymbol", "layerprops", "frameview", "layercolour", "timelinepolish", "convert", "mixed", "bitmap", "nineslice", "nineslicedit", "find", "explorer", "publish", "publishreport", "publishanim", "start", "drop", "droplibrary", "testmovie", "testmovieinside", "templates", "savetemplate", "droptimeline", "textfields", "testtext", "richtext", "softmask", "pathtext", "gradient", "gradientbucket", "swatches", "swatchpanel", "brushlibrary", "brushcurve", "paintbrush"] { + for panel in ["select", "motion", "motionspan", "motionpath", "motionpoints", "motionedit", "motionpins", "motionpinsspan", "rawsub", "camera", "cameraview", "bones", "springbones", "shapebones", "shapeweights", "mixedbones", "warp", "sound", "envelope", "prefs", "shortcuts", "palette", "about", "files", "licenses", "confirm", "recovery", "frames", "actions", "script", "scriptproblems", "testscript", "onion", "onionmenu", "editmultiple", "library", "librarymenu", "edittransform", "onionsymbol", "layerprops", "layeropacity", "pivot", "frameview", "layercolour", "timelinepolish", "convert", "mixed", "bitmap", "nineslice", "nineslicedit", "find", "explorer", "publish", "publishreport", "publishanim", "start", "drop", "droplibrary", "testmovie", "testmovieinside", "templates", "savetemplate", "droptimeline", "textfields", "testtext", "richtext", "softmask", "pathtext", "gradient", "gradientbucket", "swatches", "swatchpanel", "brushlibrary", "brushcurve", "paintbrush"] { found.extend(check(panel, |a, _| a.open_panel(Some(panel)))); } // Every panel in front where it docks, and floating (ADR 0075); the other workspaces. diff --git a/src/app.rs b/src/app.rs index 9030a7c8..bd8fdafc 100644 --- a/src/app.rs +++ b/src/app.rs @@ -290,6 +290,8 @@ pub enum Drag { #[derive(Clone, Copy, Debug, PartialEq)] pub enum XfKind { Move, + /// Dragging the transformation point itself (ADR 0111): nothing is transformed. + Pivot, /// Handle position: -1/0/1 on each axis (corner, edge or centre). Scale { hx: i8, hy: i8 }, Rotate, @@ -482,6 +484,9 @@ pub struct App { /// The Properties panel's Scale lock (#304; view state, not undoable): while on, editing /// one Scale axis adjusts the other so the selection keeps its width:height proportion. pub scale_lock: bool, + /// Free Transform's own state (ADR 0111; view state): the transformation point held for a + /// selection that can't keep one, and the box a drag began with. + pub xf: crate::xform::State, /// The zoom edit-bar field's draft while it has the keyboard (view state, not undoable): /// `None` shows the current zoom, `Some` is what is being typed. pub zoom_text: Option, @@ -791,6 +796,7 @@ impl App { width_sel: None, open_fill_swatch: false, scale_lock: false, + xf: crate::xform::State::default(), zoom_text: None, bone_sel: None, bind: crate::bind_tool::BindOptions::default(), @@ -1911,6 +1917,31 @@ impl App { let (sin, cos) = (-60f32).to_radians().sin_cos(); self.run("modify.transform", json!({"a": cos, "b": sin, "c": -sin, "d": cos, "e": 0, "f": 0, "origin": "registration"})); } + Some("pivot") => { + // The transformation point and the turned box (ADR 0111; #302, #175): an arm, + // an instance whose transformation point was moved to its shoulder, turned 35° + // about it with Free Transform. Its box is turned with it, the white circle is + // on the shoulder, and Properties shows the point. + self.run("layer.new", json!({"name": "Arm"})); + self.run("draw.object_drawing", json!({"on": true})); + self.run("draw.rect", json!({"x": 420, "y": 520, "w": 300, "h": 44, "radius": 22, "fill": "#1b2a4a", "stroke": null})); + self.run("modify.convert_to_symbol", json!({"name": "Arm"})); // i18n-exempt: a sample symbol name + self.tool = Tool::Transform; + self.run("modify.transformation_point", json!({"x": 442, "y": 542})); + let (sin, cos) = (-35f32).to_radians().sin_cos(); + let turn = anicraft_engine::geom::Affine::translate(442.0, 542.0).mul(&anicraft_engine::geom::Affine { m: [cos, sin, -sin, cos, 0.0, 0.0] }).mul(&anicraft_engine::geom::Affine::translate(-442.0, -542.0)); + let [a, b, c, d, e, f] = turn.m; + self.run("modify.transform", json!({"a": a, "b": b, "c": c, "d": d, "e": e, "f": f})); + } + Some("layeropacity") => { + // Layer opacity (ADR 0111, #279): the top two layers faded, each as one, with + // the percentage beside their names; Layer Properties open on the active one. + let ids: Vec = self.s.timeline().layers.iter().filter(|l| !matches!(l.kind, anicraft_engine::doc::LayerKind::Folder | anicraft_engine::doc::LayerKind::Camera)).map(|l| l.id.0).collect(); + for (id, opacity) in ids.iter().zip([40, 65]) { + self.run("layer.set_opacity", json!({"layer": id, "opacity": opacity})); + } + crate::layer_props::open(self, ids.first().map(|id| anicraft_engine::doc::LayerId(*id))); + } Some("points") => { // A pencil stroke and a pen path being edited, with one smooth point selected. let wave: Vec<[f32; 2]> = (0..=240).map(|i| [140.0 + i as f32 * 1.5, 330.0 + (i as f32 * 0.06).sin() * 28.0]).collect(); diff --git a/src/layer_props.rs b/src/layer_props.rs index 36ca6ada..ba01b7ad 100644 --- a/src/layer_props.rs +++ b/src/layer_props.rs @@ -27,6 +27,8 @@ pub struct LayerPropsDialog { pub onion: bool, /// Rows: 1, 2 or 3 (100, 200, 300 %). pub height: u8, + /// Opacity in percent, 0 to 100 (ADR 0111). + pub opacity: f64, /// What the layer had when the dialog opened: OK sends only what changed. was: Value, focus: bool, @@ -55,6 +57,7 @@ pub fn open(app: &mut App, layer: Option) { outline: l.outline, onion: l.onion, height: l.height(), + opacity: p.get("opacity").and_then(Value::as_f64).unwrap_or(100.0), was: p, focus: true, }); @@ -162,6 +165,16 @@ pub fn window(app: &mut App, ctx: &egui::Context) { crate::theme::checkbox(ui, &mut d.onion, tr!("Onion skin this layer")).on_hover_text(tr!("Show this layer's frames around the playhead while onion skin is on")); }); } + // Opacity (ADR 0111, #279): in the movie and every export. The camera layer holds no + // artwork; mask and guide artwork ignore it. + if kind != LayerKind::Camera { + form_row(ui, FORM_LABEL_DIALOG, tr!("Opacity"), |ui| { + let tip = tr!("How strongly the layer shows, in the movie and every export. Its artwork fades together, so overlapping parts don't show through each other; a folder fades the layers in it"); + // A slider to drag and a field to type in, each with its own name. + ui.add(egui::Slider::new(&mut d.opacity, 0.0..=100.0).show_value(false)).on_hover_text(tip).set_name(tr!("Layer opacity")); + ui.add(egui::DragValue::new(&mut d.opacity).range(0.0..=100.0).suffix(" %").speed(1.0).max_decimals(0)).on_hover_text(tip).set_name(tr!("Layer opacity (percent)")); + }); + } form_row(ui, FORM_LABEL_DIALOG, tr!("Layer height"), |ui| { egui::ComboBox::from_id_salt("layer_props_height") .width(96.0) @@ -206,6 +219,7 @@ pub fn changes(d: &LayerPropsDialog) -> Value { "outline": d.outline, "onion": d.onion, "height": u32::from(d.height) * 100, + "opacity": (d.opacity.clamp(0.0, 100.0) * 100.0).round() / 100.0, }); let mut now = now; // The mask type is a mask layer's (and only sent when it changes). diff --git a/src/library.rs b/src/library.rs index a1a04ac1..63f0274c 100644 --- a/src/library.rs +++ b/src/library.rs @@ -931,7 +931,7 @@ fn symbol_frame(doc: &Document, id: anicraft_engine::doc::SymbolId) -> anicraft_ name: String::new(), transform: Default::default(), color: Default::default(), - kind: ElementKind::Symbol { symbol: id, loop_mode: LoopMode::SingleFrame, first_frame: 0, blend: Default::default(), filters: Vec::new(), events: Vec::new() }, + kind: ElementKind::Symbol { symbol: id, loop_mode: LoopMode::SingleFrame, first_frame: 0, blend: Default::default(), filters: Vec::new(), events: Vec::new(), pivot: None }, })]; } let mut scene = Scene::new(""); diff --git a/src/main.rs b/src/main.rs index b09b22f3..919c3116 100644 --- a/src/main.rs +++ b/src/main.rs @@ -100,6 +100,7 @@ mod timeline; mod web; mod widthtool; mod windows; +mod xform; mod workspaces_window; #[cfg(not(target_arch = "wasm32"))] @@ -283,7 +284,7 @@ fn parse_args(args: impl IntoIterator) -> Result { /// `--help` (the console's text, in English). #[cfg(not(target_arch = "wasm32"))] // i18n-exempt: the --help console text -const HELP: &str = "anicraft [file.anicraft|file.fla|file.xfl] [--version] [--screenshot out.png [--shot-width ]] [--renderer gl|wgpu|vulkan|dx12|metal] [--theme graphite|high-contrast] [--scale ] [--lang |auto|pseudo] [--control ] [--open palette|shortcuts|helpbone|lastscene|start|drop|droplibrary|select|selectzoom|about|files|confirm|transform|shapecommands|expandfill|softenfill|origins|points|merge|rawparts|rawedit|rawsub|rawpoints|rawsnap|rulers|editguides|editgrid|symboledit|groups|combine|nineslice|nineslicedit|brush|brushing|polystar|paintinside|drawingedit|shapeenvelope|brushlibrary|brushcurve|paintbrush|eraser|erasing|erasemerge|tiltbrush|eyedropper|pen|frames|span|bucket|tlzoom|tlwide|motion|motionspan|motionpath|motionpoints|motionedit|motionpins|motionpinsspan|hints|hintsend|camera|cameraview|bones|springbones|shapebones|shapeweights|mixedbones|layerdepth|layerdepthview|filters|strokes|prefs|licenses|zoom|recovery|plugins|actions|script|scriptproblems|testmovie|testmovieinside|testscript|textfields|testtext|richtext|softmask|pathtext|button|testhits|exporthtml|publish|publishreport|publishanim|sound|envelope|ease|easepreset|plugineases|pluginexport|pluginexportwindow|library|librarymenu|libraryfolders|colour|layerprops|frameview|layercolour|timelinepolish|dock|dockicons|floattabs|docknarrow|workspaces|animator|designer|gradient|gradientbucket|swatches|swatchpanel]\n\ +const HELP: &str = "anicraft [file.anicraft|file.fla|file.xfl] [--version] [--screenshot out.png [--shot-width ]] [--renderer gl|wgpu|vulkan|dx12|metal] [--theme graphite|high-contrast] [--scale ] [--lang |auto|pseudo] [--control ] [--open palette|shortcuts|helpbone|lastscene|start|drop|droplibrary|select|selectzoom|about|files|confirm|transform|shapecommands|expandfill|softenfill|origins|pivot|layeropacity|points|merge|rawparts|rawedit|rawsub|rawpoints|rawsnap|rulers|editguides|editgrid|symboledit|groups|combine|nineslice|nineslicedit|brush|brushing|polystar|paintinside|drawingedit|shapeenvelope|brushlibrary|brushcurve|paintbrush|eraser|erasing|erasemerge|tiltbrush|eyedropper|pen|frames|span|bucket|tlzoom|tlwide|motion|motionspan|motionpath|motionpoints|motionedit|motionpins|motionpinsspan|hints|hintsend|camera|cameraview|bones|springbones|shapebones|shapeweights|mixedbones|layerdepth|layerdepthview|filters|strokes|prefs|licenses|zoom|recovery|plugins|actions|script|scriptproblems|testmovie|testmovieinside|testscript|textfields|testtext|richtext|softmask|pathtext|button|testhits|exporthtml|publish|publishreport|publishanim|sound|envelope|ease|easepreset|plugineases|pluginexport|pluginexportwindow|library|librarymenu|libraryfolders|colour|layerprops|frameview|layercolour|timelinepolish|dock|dockicons|floattabs|docknarrow|workspaces|animator|designer|gradient|gradientbucket|swatches|swatchpanel]\n\ --renderer the window's graphics (also ANICRAFT_RENDERER); default automatic, falling back to OpenGL\n\ --open shows a panel at start (handy with --screenshot for visual checks)\n\ --shot-width scales the screenshot down to this width (the user guide's pictures)\n\ diff --git a/src/motion_editor.rs b/src/motion_editor.rs index 69b5d0c6..53d3c8a5 100644 --- a/src/motion_editor.rs +++ b/src/motion_editor.rs @@ -974,7 +974,7 @@ mod tests { use anicraft_engine::doc::{ColorEffect, ElementId, ElementKind, Filter, FilterEntry, SymbolId}; use anicraft_engine::geom::Affine; let filters = vec![FilterEntry::from(Filter::new("blur").unwrap()), FilterEntry { filter: Filter::new("adjust_color").unwrap(), enabled: false }]; - let clip = Element { id: ElementId(1), name: String::new(), transform: Affine::IDENTITY, color: ColorEffect::default(), kind: ElementKind::Symbol { symbol: SymbolId(1), loop_mode: Default::default(), first_frame: 0, blend: Default::default(), filters, events: Vec::new() } }; + let clip = Element { id: ElementId(1), name: String::new(), transform: Affine::IDENTITY, color: ColorEffect::default(), kind: ElementKind::Symbol { symbol: SymbolId(1), loop_mode: Default::default(), first_frame: 0, blend: Default::default(), filters, events: Vec::new(), pivot: None } }; let names = |rows: Vec| -> Vec { rows.iter() .skip_while(|r| matches!(r, Row::Prop(p) if !p.is_filter())) @@ -988,7 +988,7 @@ mod tests { assert_eq!(names(rows_for(&[], &[], &clip, &[])), ["[0 Blur true]", "filter.0.blur_x", "filter.0.blur_y", "filter.0.quality", "[1 Adjust Color false]", "filter.1.brightness", "filter.1.contrast", "filter.1.saturation", "filter.1.hue"]); // ADR 0099: a colour is one row; its channels are listed when it is open; quality and // the switches come last. - let glow = Element { kind: ElementKind::Symbol { symbol: SymbolId(1), loop_mode: Default::default(), first_frame: 0, blend: Default::default(), filters: vec![Filter::new("glow").unwrap().into()], events: Vec::new() }, ..clip.clone() }; + let glow = Element { kind: ElementKind::Symbol { symbol: SymbolId(1), loop_mode: Default::default(), first_frame: 0, blend: Default::default(), filters: vec![Filter::new("glow").unwrap().into()], events: Vec::new(), pivot: None }, ..clip.clone() }; assert_eq!(names(rows_for(&[], &[], &glow, &[])), ["[0 Glow true]", "filter.0.blur_x", "filter.0.blur_y", "filter.0.strength", "(0 color)", "filter.0.quality", "filter.0.inner", "filter.0.knockout"]); let open = names(rows_for(&[], &[], &glow, &[(0, FilterColor::Color)])); assert_eq!(open[4..9], ["(0 color)", "filter.0.color_red", "filter.0.color_green", "filter.0.color_blue", "filter.0.color_alpha"]); diff --git a/src/panels.rs b/src/panels.rs index 0330f0b4..f1bb3c6a 100644 --- a/src/panels.rs +++ b/src/panels.rs @@ -1177,6 +1177,27 @@ fn selection_props(app: &mut App, ui: &mut egui::Ui, e: &anicraft_engine::doc::E } mixed(ui, m.rotation); }); + // The transformation point (ADR 0111): one symbol instance keeps its own, and the + // fields above (and Free Transform, and tweens) then turn and scale it about it. + if !many + && matches!(e.kind, ElementKind::Symbol { .. }) + && let Some((at, moved)) = app.s.transformation_point() + { + let (mut px, mut py) = (at.x, at.y); + row(ui, tr!("Pivot"), |ui| { + let tip = tr!("The transformation point (the white circle Free Transform shows): what this instance turns, scales and skews about, on the stage, here and in tweens. Drag the circle with Free Transform, or set it here"); + let a = ui.add(egui::DragValue::new(&mut px).prefix("X ").speed(1.0).max_decimals(1)).named(tr!("Transformation point X")).on_hover_text(tip); + let b = ui.add(egui::DragValue::new(&mut py).prefix("Y ").speed(1.0).max_decimals(1)).named(tr!("Transformation point Y")).on_hover_text(tip); + if a.changed() || b.changed() { + live(app, tr_noop!("Move Transformation Point"), "modify.transformation_point", json!({"x": px, "y": py})); + } + // Back to the centre (double-clicking the circle does the same). + ui.spacing_mut().item_spacing.x = 4.0; + if ui.add_enabled(moved, egui::Button::new(text(Type::Label, tr!("Reset")))).on_hover_text(tr!("Put the transformation point back at the centre")).named(tr!("Reset transformation point")).clicked() { + app.run("modify.reset_transformation_point", json!({})); + } + }); + } if !matches!(e.kind, ElementKind::Camera) { colour_effect_rows(app, ui, &e.color, m.color, EffectOf::Selection); } diff --git a/src/rulers_tests.rs b/src/rulers_tests.rs index 4c17a30e..451a3658 100644 --- a/src/rulers_tests.rs +++ b/src/rulers_tests.rs @@ -107,10 +107,12 @@ fn drawing_and_free_transform_snap_to_guides() { } let g = canvas(&app); let screen_of = |x: f32, y: f32| pos2(g.origin.x + x * g.zoom, g.origin.y + y * g.zoom); - // Grabbed by the middle, so the box's centre is what snaps; let go 3 screen pixels short. + // Grabbed near the middle, so the box's centre is what snaps; let go 3 screen pixels short. + // (Not on the very centre: the transformation point is there, and a drag on it moves the + // point, not the box; ADR 0111.) let sel = app.s.selection_bounds(); let cx = (sel.min.x + sel.max.x) * 0.5; - let inside = screen_of(cx, (sel.min.y + sel.max.y) * 0.5); + let inside = screen_of(cx, (sel.min.y + sel.max.y) * 0.5) + vec2(0.0, 12.0); let dx = (500.0 - cx) * g.zoom - 3.0; drag(&ctx, &mut app, inside, inside + vec2(dx, 0.0)); let after = app.s.selection_bounds(); diff --git a/src/stage.rs b/src/stage.rs index 838f280b..d6921230 100644 --- a/src/stage.rs +++ b/src/stage.rs @@ -342,6 +342,10 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { // Edit Multiple Frames takes the Selection and Free Transform tools' input (ADR 0047); Free // Transform's box then holds the selection on every keyframe (ADR 0051). let multi = crate::onion::editing(app) && !preview; + // Free Transform's box round the selection: one element's own box, turned as it is, and + // the transformation point (ADR 0111). + crate::xform::sync(app); + let xf_frame = if app.tool == Tool::Transform && !multi && !preview { crate::xform::frame(app) } else { None }; let sel_bounds = if multi { crate::onion::selection_bounds(app) } else { bounds_arr(app.s.selection_bounds()) }; let sel_rect = sel_bounds.map(|b| Rect::from_min_max(to_screen(Vec2::new(b[0], b[1])), to_screen(Vec2::new(b[2], b[3])))); // Shape hint markers take the pointer first with the selection tools (ADR 0023). @@ -396,9 +400,14 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { Tool::Transform => { let zone = match app.drag { Drag::Transform { kind, .. } | Drag::MultiTransform { kind, .. } => Some(kind), - _ => sel_rect.zip(pointer).and_then(|(r, p)| xf_zone(r, p)), + _ if multi => sel_rect.zip(pointer).and_then(|(r, p)| xf_zone(r, p)), + _ => xf_frame.zip(pointer).and_then(|(f, p)| f.zone(to_screen, p)), }; + // The arrows follow a turned box (ADR 0111). + let turned = if multi { None } else { app.xf.drag.filter(|_| matches!(app.drag, Drag::Transform { .. })).or(xf_frame) }; match zone { + Some(kind) if turned.is_some_and(|f| f.m != Affine::IDENTITY || kind == XfKind::Pivot) => turned.map_or(CursorIcon::Default, |f| f.cursor(kind, to_screen, matches!(app.drag, Drag::Transform { .. }))), + Some(XfKind::Pivot) => CursorIcon::Grab, Some(XfKind::Scale { hx, hy }) if hx * hy > 0 => CursorIcon::ResizeNwSe, Some(XfKind::Scale { hx, hy }) if hx * hy < 0 => CursorIcon::ResizeNeSw, Some(XfKind::Scale { hx: 0, .. }) => CursorIcon::ResizeVertical, @@ -483,11 +492,18 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { Tool::Select if let Some(d) = crate::bone_tool::select_drag_start(app, xf, press) => d, Tool::Select => select_press(app, sp, shift, command, alt, zoom), Tool::Transform => { - let zone = sel_rect.and_then(|r| xf_zone(r, press)); - match (zone, sel_bounds) { - (Some(kind), Some(bounds)) => { - app.s.begin_gesture(tr_noop!("Free Transform")); - Drag::Transform { kind, start: sp, bounds, applied: Affine::IDENTITY } + let zone = xf_frame.and_then(|f| f.zone(to_screen, press)); + match (zone, xf_frame) { + (Some(kind), Some(frame)) => { + // Moving an instance's transformation point changes the document; + // a point held for the selection doesn't. + if kind != XfKind::Pivot { + app.s.begin_gesture(tr_noop!("Free Transform")); + } else if frame.keeps { + app.s.begin_gesture(tr_noop!("Move Transformation Point")); + } + app.xf.drag = Some(frame); + Drag::Transform { kind, start: sp, bounds: frame.b, applied: Affine::IDENTITY } } // Not on the box: grab whatever is under the pointer and move it. _ => match app.s.hit_test(to_v(sp), 3.0 / zoom) { @@ -496,6 +512,7 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { match bounds_arr(app.s.selection_bounds()) { Some(bounds) => { app.s.begin_gesture(tr_noop!("Free Transform")); + app.xf.drag = Some(crate::xform::Frame::upright(bounds)); Drag::Transform { kind: XfKind::Move, start: sp, bounds, applied: Affine::IDENTITY } } None => Drag::None, @@ -613,10 +630,20 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { } } } + (Drag::Transform { kind: XfKind::Pivot, .. }, Some(c)) => { + // The transformation point follows the pointer, snapping to the box's handles + // and centre (Alt: freely); it may leave the box (ADR 0111). + app.snap_ring = None; + crate::xform::drag_point(app, to_v(c), zoom, alt); + } (Drag::Transform { kind, start, bounds, applied }, Some(c)) => { + let (kind, start, bounds, applied) = (*kind, *start, *bounds, *applied); + // The box as it was when the drag began: its handles act along its own axes, + // and it turns about its transformation point (ADR 0111). + let frame = app.xf.drag.unwrap_or_else(|| crate::xform::Frame::upright(bounds)); // The handle being dragged (or the box, moving) snaps; Shift constrains instead. - let c = if shift { c } else { xf_snap(&mut app.s, &mut app.snap_ring, *kind, *bounds, *start, c, zoom) }; - let total = xf_total(*kind, *bounds, *start, c, shift, alt); + let c = if shift { c } else { xf_snap(&mut app.s, &mut app.snap_ring, kind, &frame, start, c, zoom) }; + let total = frame.total(kind, start, c, shift, alt); // Send only the change since the last frame; the gesture makes it one undo step. if let Some(inv) = applied.inverse() { let delta = total.mul(&inv); @@ -625,12 +652,15 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { let mut p = json!({"a": a, "b": b, "c": cc, "d": d, "e": e, "f": f}); // Turning, scaling and skewing follow the transformation origin (ADR // 0109): each object about its own point. A move is the same for all. - if *kind != XfKind::Move { + if kind != XfKind::Move { p["origin"] = json!(app.s.style.transform_origin.key()); } - let ok = app.s.execute("modify.transform", &p).is_ok(); - if ok { - *applied = total; + if app.s.execute("modify.transform", &p).is_ok() { + // A point held for the selection goes with the artwork. + crate::xform::carried(app, &delta); + if let Drag::Transform { applied, .. } = &mut app.drag { + *applied = total; + } } } } @@ -859,6 +889,15 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { } } } + // Double-clicking the transformation point puts it back at the centre (ADR 0111). + if app.tool == Tool::Transform + && !preview + && !multi + && resp.double_clicked() + && let Some(p) = resp.interact_pointer_pos() + { + crate::xform::double_click(app, to_screen, p); + } if app.tool == Tool::Subselect && !preview && resp.double_clicked() @@ -1266,7 +1305,10 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { } if transforming { // Free transform shows one box for the whole selection (below); members get a hint. - painter.rect_stroke(r, 0.0, Stroke::new(1.0, T.selection.gamma_multiply(0.45)), StrokeKind::Middle); + // (One element alone shows its own box, turned with it: no upright one beside it.) + if multi || app.s.selection.len() > 1 { + painter.rect_stroke(r, 0.0, Stroke::new(1.0, T.selection.gamma_multiply(0.45)), StrokeKind::Middle); + } continue; } // A plain box, as Animate's Selection tool shows: handles are Free Transform's (Q), @@ -1288,21 +1330,24 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { painter.circle(o, 3.5, Color32::WHITE, Stroke::new(1.0, Color32::BLACK)); } // Free transform box: recomputed every frame so it follows the artwork while you drag. - let xf_box = if multi { crate::onion::selection_bounds(app) } else { bounds_arr(app.s.selection_bounds()) }; - if transforming && !enveloped && let Some(b) = xf_box { - let r = Rect::from_min_max(to_screen(Vec2::new(b[0], b[1])), to_screen(Vec2::new(b[2], b[3]))).expand(1.0); - painter.rect_stroke(r, 0.0, Stroke::new(1.5, T.selection), StrokeKind::Middle); - for (h, _, _) in handles(r) { - let hr = Rect::from_center_size(h, vec2(HANDLE, HANDLE)); + // One element shows its own box, turned, scaled and skewed as it is (ADR 0111, #175); + // several, or Edit Multiple Frames' selection, the upright box round them all. + let xf_box = if multi { crate::onion::selection_bounds(app).map(crate::xform::Frame::upright) } else if preview { None } else { crate::xform::frame(app) }; + if transforming && !enveloped && let Some(frame) = xf_box { + let corners: Vec = frame.corners().into_iter().map(to_screen).collect(); + painter.add(egui::Shape::closed_line(corners, Stroke::new(1.5, T.selection))); + for (hx, hy) in crate::xform::HANDLES { + let hr = Rect::from_center_size(to_screen(frame.handle(hx, hy)), vec2(HANDLE, HANDLE)); painter.rect_filled(hr, 0.0, Color32::WHITE); painter.rect_stroke(hr, 0.0, Stroke::new(1.0, T.selection), StrokeKind::Middle); } - // The transformation point: the box's centre, or, when each object is transformed - // about its own point (ADR 0109), every object's (past a few hundred objects the box - // alone shows, so a huge selection stays quick). + // The transformation point (ADR 0111): the instance's own, the one held for the + // selection, or the box's centre; or, when each object is transformed about its own + // point (ADR 0109), every object's (past a few hundred objects the box alone shows, + // so a huge selection stays quick). let mode = app.s.style.transform_origin; let own = !multi && mode != anicraft_engine::TransformOrigin::Selection && app.s.selection.len() <= MAX_ORIGIN_MARKS; - let points: Vec = if own { anicraft_engine::transform_origins(&app.s, mode).into_iter().map(|(_, at)| to_screen(at)).collect() } else { vec![r.center()] }; + let points: Vec = if own { anicraft_engine::transform_origins(&app.s, mode).into_iter().map(|(_, at)| to_screen(at)).collect() } else { vec![to_screen(frame.point)] }; for c in points { painter.circle(c, 4.0, Color32::WHITE, Stroke::new(1.0, T.selection)); painter.line_segment([c - vec2(6.0, 0.0), c + vec2(6.0, 0.0)], Stroke::new(1.0, T.selection)); @@ -1471,20 +1516,20 @@ fn snap_move(app: &mut App, c: Pos2, zoom: f32, shift: bool) { /// handle, or while moving the box's corner or centre nearest where it was pressed) lands where /// the snap engine puts it: an object's point or line, a guide, the grid or a pixel. The /// selection itself is no target. Rotation doesn't snap. -fn xf_snap(s: &mut anicraft_engine::Session, ring: &mut Option, kind: XfKind, b: [f32; 4], start: Pos2, c: Pos2, zoom: f32) -> Pos2 { - let side = |h: i8, lo: f32, hi: f32| match h { - ..0 => lo, - 0 => (lo + hi) * 0.5, - _ => hi, +fn xf_snap(s: &mut anicraft_engine::Session, ring: &mut Option, kind: XfKind, frame: &crate::xform::Frame, start: Pos2, c: Pos2, zoom: f32) -> Pos2 { + // Where a handle of the box is on the stage (the box may be turned, ADR 0111). + let at = |hx: i8, hy: i8| { + let p = frame.handle(hx, hy); + pos2(p.x, p.y) }; let handle = match kind { - XfKind::Scale { hx, hy } => pos2(side(hx, b[0], b[2]), side(hy, b[1], b[3])), + XfKind::Scale { hx, hy } => at(hx, hy), XfKind::Move => { - let pts = [pos2(b[0], b[1]), pos2(b[2], b[1]), pos2(b[2], b[3]), pos2(b[0], b[3]), pos2((b[0] + b[2]) * 0.5, (b[1] + b[3]) * 0.5)]; + let pts = [at(-1, -1), at(1, -1), at(1, 1), at(-1, 1), at(0, 0)]; pts.into_iter().min_by(|p, q| p.distance(start).total_cmp(&q.distance(start))).unwrap_or(start) } - // Rotation and skew don't snap. - XfKind::Rotate | XfKind::Skew { .. } => { + // Rotation and skew don't snap (the transformation point snaps to its own box). + XfKind::Rotate | XfKind::Skew { .. } | XfKind::Pivot => { *ring = None; return c; } @@ -4262,10 +4307,10 @@ fn rotate_cursor(painter: &egui::Painter, at: Pos2, outward: egui::Vec2) { } /// Screen-space handle size and the rotation zone just outside each corner. -const HANDLE: f32 = 8.0; -const ROTATE_ZONE: f32 = 22.0; +pub(crate) const HANDLE: f32 = 8.0; +pub(crate) const ROTATE_ZONE: f32 = 22.0; /// How far from a box edge line (screen space) a press still grabs it to skew. -const SKEW_ZONE: f32 = 5.0; +pub(crate) const SKEW_ZONE: f32 = 5.0; fn bounds_arr(b: anicraft_engine::geom::Rect) -> Option<[f32; 4]> { (!b.is_empty()).then_some([b.min.x, b.min.y, b.max.x, b.max.y]) @@ -4305,10 +4350,18 @@ fn xf_zone(r: Rect, p: Pos2) -> Option { /// The whole transform of a free-transform drag from `start` to `cur` (stage space). pub(crate) fn xf_total(kind: XfKind, b: [f32; 4], start: Pos2, cur: Pos2, shift: bool, alt: bool) -> Affine { + xf_total_about(kind, b, None, start, cur, shift, alt) +} + +/// [`xf_total`] with the transformation point `about` (default: the box's centre): what a +/// rotation turns about, and what Alt scales and skews about (ADR 0111). +pub(crate) fn xf_total_about(kind: XfKind, b: [f32; 4], about: Option, start: Pos2, cur: Pos2, shift: bool, alt: bool) -> Affine { let [x0, y0, x1, y1] = b; - let (cx, cy) = ((x0 + x1) / 2.0, (y0 + y1) / 2.0); + let (cx, cy) = about.map_or(((x0 + x1) / 2.0, (y0 + y1) / 2.0), |p| (p.x, p.y)); let about = |px: f32, py: f32, m: Affine| Affine::translate(px, py).mul(&m).mul(&Affine::translate(-px, -py)); match kind { + // Moving the transformation point transforms nothing. + XfKind::Pivot => Affine::IDENTITY, XfKind::Move => { let mut d = cur - start; if shift { diff --git a/src/timeline.rs b/src/timeline.rs index 353a2c9e..eda0070c 100644 --- a/src/timeline.rs +++ b/src/timeline.rs @@ -813,6 +813,12 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { LayerKind::Normal => tr!("{name} · layer", name = name), }; let row_name = if has_selection { tr!("{row} · has selected artwork", row = row_name) } else { row_name }; + // A faded layer says so (ADR 0111): its opacity beside its name, and to screen readers. + let faded = ((layer.shown_opacity() * 100.0).round() as u32).min(100); + let row_name = if faded < 100 { tr!("{row} · {percent} % opacity", row = row_name, percent = faded) } else { row_name }; + if faded < 100 && !is_camera { + painter.text(pos2(name_rect.right() - 2.0, name_rect.center().y), egui::Align2::RIGHT_CENTER, format!("{faded}%"), crate::theme::font(Type::DataSmall), T.text_faint); + } a11y::control(ui, &nr, WidgetType::SelectableLabel, &row_name, Some(is_active)); // Ctrl+F6 lands on the active layer, or on the top row shown when it is scrolled away // (rows are drawn top down, so the active row, when drawn, has the last word). @@ -942,6 +948,15 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { if !is_folder && menus::check_item(ui, tr!("Onion Skin"), layer.onion, true) { app.run("layer.set_onion", json!({"layer": layer.id.0})); } + // Opacity (ADR 0111, #279): one click for the usual values; any other in Properties. + ui.menu_button(tr!("Opacity"), |ui| { + let now = (layer.shown_opacity() * 100.0).round() as u32; + for o in [100u32, 75, 50, 25, 0] { + if menus::check_item(ui, &format!("{o} %"), now == o, true) { + app.run("layer.set_opacity", json!({"layer": layer.id.0, "opacity": o})); + } + } + }); ui.menu_button(tr!("Layer Height"), |ui| { for h in 1..=anicraft_engine::doc::MAX_LAYER_HEIGHT { if menus::check_item(ui, &format!("{} %", u32::from(h) * 100), layer.height() == h, true) { diff --git a/src/xform.rs b/src/xform.rs new file mode 100644 index 00000000..dd2893f1 --- /dev/null +++ b/src/xform.rs @@ -0,0 +1,431 @@ +//! Free Transform's box and transformation point (ADR 0111). +//! +//! One selected element shows its own box, turned, scaled and skewed as it is, and its handles +//! act along the box's own axes (#175); several elements, or raw pieces, show the upright box +//! of the selection. The transformation point (the white circle) is what a rotation turns +//! about, and what Alt scales and skews about. Drag it to move it; double-click it to put it +//! back at the centre. A symbol instance keeps its point in the document +//! (`modify.transformation_point`); anything else has one for the selection while Free +//! Transform is held, kept here (#302, #280, #178, #183). +//! +//! Behaviour learned from Adobe's public help pages on transforming objects and from watching +//! the program; nothing was copied. + +use crate::app::{App, Tool, XfKind}; +use anicraft_engine::TransformOrigin; +use anicraft_engine::doc::ElementKind; +use anicraft_engine::geom::{Affine, Vec2}; +use egui::{CursorIcon, Pos2, pos2}; +use serde_json::json; +use std::hash::{Hash, Hasher}; + +/// How near the transformation point (screen pixels) a press grabs it. +pub const POINT_GRAB: f32 = 7.0; +/// How near one of the box's handles, corners or its centre (screen pixels) the dragged point +/// snaps to it. +pub const POINT_SNAP: f32 = 8.0; + +/// The selection's box as Free Transform draws it, and its transformation point. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Frame { + /// The box's own space to stage space. + pub m: Affine, + /// The box in its own space: `[x0, y0, x1, y1]`. + pub b: [f32; 4], + /// The transformation point, in stage space. + pub point: Vec2, + /// The selection is one symbol instance, which keeps its point in the document. + pub keeps: bool, + /// The point is one the artist moved (kept by the instance, or held for the selection). + pub moved: bool, + /// The point can be dragged: one point for the whole selection (ADR 0109's default mode). + pub movable: bool, +} + +/// The point held for a selection that can't keep one (raw shapes, groups, several elements), +/// while Free Transform is the tool. +#[derive(Clone, Copy, Debug, PartialEq)] +struct Held { + /// Which elements it is for. + selection: u64, + /// The selection's bounds when it was last placed: a selection that moves carries the + /// point; one that changes any other way drops it. + bounds: [f32; 4], + at: Vec2, +} + +/// Free Transform's own state: the held point, and the frame a drag began with. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub struct State { + held: Option, + /// The frame as it was when the drag in progress began (the drag's whole transform is + /// measured in it). + pub drag: Option, +} + +fn selection_key(app: &App) -> u64 { + let mut ids: Vec<(u64, u64)> = app.s.selection.iter().map(|(l, e)| (l.0, e.0)).collect(); + ids.sort_unstable(); + let mut h = std::collections::hash_map::DefaultHasher::new(); + ids.hash(&mut h); + h.finish() +} + +fn bounds(app: &App) -> Option<[f32; 4]> { + let b = app.s.selection_bounds(); + (!b.is_empty()).then_some([b.min.x, b.min.y, b.max.x, b.max.y]) +} + +/// Once a frame: the held point goes with its selection when that moves, and is dropped when +/// the tool or the selection changes, or the selection is reshaped by anything but a Free +/// Transform drag (which carries it itself, see [`carried`]). +pub fn sync(app: &mut App) { + let Some(h) = app.xf.held else { return }; + let now = (app.tool == Tool::Transform).then(|| bounds(app)).flatten().filter(|_| selection_key(app) == h.selection); + app.xf.held = now.and_then(|b| { + if b == h.bounds { + return Some(h); + } + let same = |a: f32, c: f32| (a - c).abs() <= 1e-2 * (1.0 + a.abs().max(c.abs())); + let moved = same(b[2] - b[0], h.bounds[2] - h.bounds[0]) && same(b[3] - b[1], h.bounds[3] - h.bounds[1]); + moved.then(|| Held { bounds: b, at: Vec2::new(h.at.x + b[0] - h.bounds[0], h.at.y + b[1] - h.bounds[1]), ..h }) + }); +} + +/// A Free Transform change `delta` (stage space) was applied to the selection: the held point +/// goes with the artwork. +pub fn carried(app: &mut App, delta: &Affine) { + if let (Some(h), Some(b)) = (app.xf.held, bounds(app)) { + let at = delta.apply(h.at); + app.xf.held = at.is_finite().then_some(Held { bounds: b, at, ..h }); + } +} + +/// The frame of the selection now. `None` with nothing selected. +pub fn frame(app: &App) -> Option { + let (m, r) = app.s.transform_frame()?; + let (mut point, mut moved) = app.s.transformation_point()?; + let selected = app.s.selected_elements(); + let keeps = matches!(selected.as_slice(), [(_, e)] if matches!(e.kind, ElementKind::Symbol { .. })); + if !keeps + && let Some(h) = app.xf.held.filter(|h| h.selection == selection_key(app)) + { + (point, moved) = (h.at, true); + } + let movable = app.s.style.transform_origin == TransformOrigin::Selection; + Some(Frame { m, b: [r.min.x, r.min.y, r.max.x, r.max.y], point, keeps, moved, movable }) +} + +/// The handle codes, clockwise from the top left (as the stage draws them). +pub const HANDLES: [(i8, i8); 8] = [(-1, -1), (0, -1), (1, -1), (1, 0), (1, 1), (0, 1), (-1, 1), (-1, 0)]; + +fn distance_to_segment(p: Pos2, a: Pos2, b: Pos2) -> f32 { + let (d, v) = (b - a, p - a); + let l = d.length_sq(); + let t = if l > 0.0 { (v.dot(d) / l).clamp(0.0, 1.0) } else { 0.0 }; + (a + d * t).distance(p) +} + +impl Frame { + /// An upright box (stage space) with its point at the centre. + pub fn upright(b: [f32; 4]) -> Frame { + Frame { m: Affine::IDENTITY, b, point: Vec2::new((b[0] + b[2]) * 0.5, (b[1] + b[3]) * 0.5), keeps: false, moved: false, movable: false } + } + + /// The stage position of handle `(hx, hy)` (-1, 0 or 1 on each axis; `(0, 0)` is the centre). + pub fn handle(&self, hx: i8, hy: i8) -> Vec2 { + let [x0, y0, x1, y1] = self.b; + let along = |h: i8, lo: f32, hi: f32| lo + (hi - lo) * (f32::from(h) + 1.0) * 0.5; + self.m.apply(Vec2::new(along(hx, x0, x1), along(hy, y0, y1))) + } + + /// The box's corners on the stage: top left, top right, bottom right, bottom left (of the + /// box's own space). + pub fn corners(&self) -> [Vec2; 4] { + [self.handle(-1, -1), self.handle(1, -1), self.handle(1, 1), self.handle(-1, 1)] + } + + /// What dragging from screen point `p` would do. `to_screen` maps the stage to the screen. + pub fn zone(&self, to_screen: impl Fn(Vec2) -> Pos2, p: Pos2) -> Option { + use crate::stage::{HANDLE, ROTATE_ZONE, SKEW_ZONE}; + if self.movable && to_screen(self.point).distance(p) <= POINT_GRAB { + return Some(XfKind::Pivot); + } + for (hx, hy) in HANDLES { + let h = to_screen(self.handle(hx, hy)); + if (p.x - h.x).abs() <= HANDLE && (p.y - h.y).abs() <= HANDLE { + return Some(XfKind::Scale { hx, hy }); + } + } + let [tl, tr, br, bl] = self.corners().map(&to_screen); + // The line between two handles skews (Animate parity, #174); the handles win at its ends. + for (a, b, hx, hy) in [(tl, tr, 0, -1), (bl, br, 0, 1), (tl, bl, -1, 0), (tr, br, 1, 0)] { + if distance_to_segment(p, a, b) <= SKEW_ZONE { + return Some(XfKind::Skew { hx, hy }); + } + } + // Inside the (convex) box: on the same side of all four edges. + let side = |a: Pos2, b: Pos2| (b.x - a.x) * (p.y - a.y) - (b.y - a.y) * (p.x - a.x); + let s = [side(tl, tr), side(tr, br), side(br, bl), side(bl, tl)]; + let inside = s.iter().all(|v| *v >= 0.0) || s.iter().all(|v| *v <= 0.0); + if inside { + return Some(XfKind::Move); + } + [tl, tr, br, bl].iter().any(|c| c.distance(p) <= ROTATE_ZONE).then_some(XfKind::Rotate) + } + + /// The whole transform (stage space) of a drag of `kind` from stage point `start` to + /// `cur`. Scaling and skewing act along the box's own axes; a rotation turns about the + /// transformation point, and Alt scales and skews about it. + pub fn total(&self, kind: XfKind, start: Pos2, cur: Pos2, shift: bool, alt: bool) -> Affine { + match kind { + XfKind::Pivot => Affine::IDENTITY, + XfKind::Move => crate::stage::xf_total(kind, self.b, start, cur, shift, alt), + // A turn is a turn on the stage, however the box is scaled or skewed. + XfKind::Rotate => { + let c = self.point; + let span = [c.x - 1.0, c.y - 1.0, c.x + 1.0, c.y + 1.0]; + crate::stage::xf_total(kind, span, start, cur, shift, alt) + } + XfKind::Scale { .. } | XfKind::Skew { .. } => { + let Some(inv) = self.m.inverse() else { return Affine::IDENTITY }; + let own = |p: Pos2| { + let q = inv.apply(Vec2::new(p.x, p.y)); + pos2(q.x, q.y) + }; + let about = inv.apply(self.point); + let local = crate::stage::xf_total_about(kind, self.b, Some(pos2(about.x, about.y)), own(start), own(cur), shift, alt); + let m = self.m.mul(&local).mul(&inv); + if m.is_finite() { m } else { Affine::IDENTITY } + } + } + } + + /// The pointer for `kind`: resize arrows follow the box as it is turned. + pub fn cursor(&self, kind: XfKind, to_screen: impl Fn(Vec2) -> Pos2, dragging: bool) -> CursorIcon { + // The screen direction a handle moves in, as one of the four arrow pairs. + let arrows = |from: Vec2, to: Vec2| { + let d = to_screen(to) - to_screen(from); + let turn = (d.y.atan2(d.x).to_degrees().rem_euclid(180.0) / 45.0).round() as i32 % 4; + match turn { + 0 => CursorIcon::ResizeHorizontal, + 1 => CursorIcon::ResizeNwSe, + 2 => CursorIcon::ResizeVertical, + _ => CursorIcon::ResizeNeSw, + } + }; + match kind { + XfKind::Pivot if dragging => CursorIcon::Grabbing, + XfKind::Pivot => CursorIcon::Grab, + XfKind::Move => CursorIcon::Move, + // No desktop has a rotate cursor: the stage draws its own (#194). + XfKind::Rotate => CursorIcon::None, + XfKind::Scale { hx, hy } => arrows(self.handle(0, 0), self.handle(hx, hy)), + // An edge slides along itself. + XfKind::Skew { hy: 0, .. } => arrows(self.handle(0, -1), self.handle(0, 1)), + XfKind::Skew { .. } => arrows(self.handle(-1, 0), self.handle(1, 0)), + } + } + + /// `c` (stage space), or the box's handle, corner or centre within [`POINT_SNAP`] screen + /// pixels of it: where the dragged transformation point lands (#178). + pub fn snap_point(&self, c: Vec2, zoom: f32) -> Vec2 { + let reach = POINT_SNAP / zoom.max(1e-3); + HANDLES.into_iter().chain([(0, 0)]).map(|(hx, hy)| self.handle(hx, hy)).filter(|h| h.distance(c) <= reach).min_by(|a, b| a.distance(c).total_cmp(&b.distance(c))).unwrap_or(c) + } +} + +/// Dragging the transformation point to stage point `c`: an instance keeps it (a document +/// change; the gesture makes the drag one undo step), anything else has it held here. Alt +/// leaves it unsnapped. +pub fn drag_point(app: &mut App, c: Vec2, zoom: f32, alt: bool) { + let Some(fr) = frame(app) else { return }; + let at = if alt { c } else { fr.snap_point(c, zoom) }; + if !at.is_finite() { + return; + } + if fr.keeps { + let _ = app.s.execute("modify.transformation_point", &json!({"x": at.x, "y": at.y})); + } else if let Some(b) = bounds(app) { + app.xf.held = Some(Held { selection: selection_key(app), bounds: b, at }); + } +} + +/// A double-click at screen point `p`: on the transformation point, it goes back to the +/// centre. Answers whether the click was on it. +pub fn double_click(app: &mut App, to_screen: impl Fn(Vec2) -> Pos2, p: Pos2) -> bool { + let Some(fr) = frame(app).filter(|f| f.movable && to_screen(f.point).distance(p) <= POINT_GRAB) else { return false }; + if !fr.keeps { + app.xf.held = None; + } else if fr.moved { + app.run("modify.reset_transformation_point", json!({})); + } + true +} + +#[cfg(test)] +mod tests { + use super::*; + use anicraft_engine::Session; + use anicraft_engine::doc::ElementId; + + fn near(a: Vec2, b: Vec2) -> bool { + a.distance(b) < 1e-2 + } + + fn screen(p: Vec2) -> Pos2 { + pos2(p.x, p.y) + } + + /// A 100 × 20 box turned 90° about (150, 110): it stands from (140, 60) to (160, 160). + fn turned() -> Frame { + let m = Affine::translate(150.0, 110.0).mul(&Affine::rotate(std::f32::consts::FRAC_PI_2)); + Frame { m, b: [-50.0, -10.0, 50.0, 10.0], point: Vec2::new(150.0, 110.0), keeps: true, moved: false, movable: true } + } + + #[test] + fn a_turned_box_has_its_handles_where_the_object_is() { + let f = turned(); + // The box's own right-middle handle is at the bottom of the standing box. + assert!(near(f.handle(1, 0), Vec2::new(150.0, 160.0))); + assert!(near(f.handle(-1, -1), Vec2::new(160.0, 60.0))); + assert_eq!(f.zone(screen, pos2(150.0, 160.0)), Some(XfKind::Scale { hx: 1, hy: 0 })); + assert_eq!(f.zone(screen, pos2(160.0, 60.0)), Some(XfKind::Scale { hx: -1, hy: -1 })); + // The point first, then inside, the edges between handles, just outside a corner, far away. + assert_eq!(f.zone(screen, pos2(152.0, 111.0)), Some(XfKind::Pivot)); + assert_eq!(f.zone(screen, pos2(150.0, 130.0)), Some(XfKind::Move)); + assert_eq!(f.zone(screen, pos2(160.0, 135.0)), Some(XfKind::Skew { hx: 0, hy: -1 })); + assert_eq!(f.zone(screen, pos2(172.0, 172.0)), Some(XfKind::Rotate)); + assert_eq!(f.zone(screen, pos2(300.0, 300.0)), None); + // Where the upright bounds would be but the turned box is not: nothing to grab (#175). + assert_eq!(f.zone(screen, pos2(190.0, 110.0)), None); + // A point that can't be dragged (each object about its own) is not grabbed. + let fixed = Frame { movable: false, point: Vec2::new(150.0, 135.0), ..f }; + assert_eq!(fixed.zone(screen, pos2(151.0, 135.0)), Some(XfKind::Move)); + assert_eq!(Frame { movable: true, ..fixed }.zone(screen, pos2(151.0, 135.0)), Some(XfKind::Pivot)); + } + + #[test] + fn a_turned_boxs_handles_scale_along_its_own_axes() { + let f = turned(); + // Dragging the box's right-middle handle (bottom of the standing box) 50 px down + // makes the box half as long again along its own x axis; the far end stays put. + let m = f.total(XfKind::Scale { hx: 1, hy: 0 }, pos2(150.0, 160.0), pos2(150.0, 210.0), false, false); + assert!(near(m.apply(f.handle(-1, 0)), f.handle(-1, 0)), "the opposite side stays"); + assert!(near(m.apply(f.handle(1, 0)), Vec2::new(150.0, 210.0)), "the handle follows the pointer"); + let d = m.mul(&f.m).decompose(); + assert!((d.sx - 1.5).abs() < 1e-4 && (d.sy - 1.0).abs() < 1e-4 && d.skew.abs() < 1e-4, "{d:?}"); + assert!((d.rotation.to_degrees() - 90.0).abs() < 1e-3, "still turned 90°, not skewed"); + // Dragged sideways (across the box's axis) the handle does nothing. + let m = f.total(XfKind::Scale { hx: 1, hy: 0 }, pos2(150.0, 160.0), pos2(190.0, 160.0), false, false); + assert!(m.m.iter().zip(Affine::IDENTITY.m).all(|(a, b)| (a - b).abs() < 1e-4), "{m:?}"); + // Alt scales about the transformation point: here the centre, so both ends move. + let m = f.total(XfKind::Scale { hx: 1, hy: 0 }, pos2(150.0, 160.0), pos2(150.0, 210.0), false, true); + assert!(near(m.apply(f.handle(-1, 0)), Vec2::new(150.0, 10.0)) && near(m.apply(f.point), f.point)); + // A corner scales both of the box's axes; Shift keeps its proportions. + let m = f.total(XfKind::Scale { hx: 1, hy: 1 }, pos2(140.0, 160.0), pos2(120.0, 260.0), true, false); + let d = m.mul(&f.m).decompose(); + assert!((d.sx - d.sy).abs() < 1e-4 && d.sx > 1.5, "{d:?}"); + // An edge slides along itself, in the box's own direction. + let m = f.total(XfKind::Skew { hx: 0, hy: 1 }, pos2(140.0, 110.0), pos2(140.0, 120.0), false, false); + assert!(near(m.apply(f.handle(0, 1)), Vec2::new(140.0, 120.0)) && near(m.apply(f.handle(0, -1)), f.handle(0, -1))); + } + + #[test] + fn a_rotation_turns_about_the_transformation_point() { + // The point at the box's own left end, (150, 60) on the stage. + let f = Frame { point: Vec2::new(150.0, 60.0), ..turned() }; + let m = f.total(XfKind::Rotate, pos2(150.0, 170.0), pos2(40.0, 60.0), false, false); + assert!(near(m.apply(f.point), f.point), "the point stays put"); + // A quarter turn clockwise on screen: the far end swings from below the point to its left. + assert!(near(m.apply(Vec2::new(150.0, 160.0)), Vec2::new(50.0, 60.0)), "{:?}", m.apply(Vec2::new(150.0, 160.0))); + // Shift turns in 15° steps. + let m = f.total(XfKind::Rotate, pos2(150.0, 170.0), pos2(140.0, 170.0), true, false); + let turn = m.decompose().rotation.to_degrees(); + assert!((turn / 15.0 - (turn / 15.0).round()).abs() < 1e-3, "{turn}"); + // An upright frame's point is its centre: Free Transform as before. + let u = Frame::upright([0.0, 0.0, 100.0, 50.0]); + assert_eq!(u.point, Vec2::new(50.0, 25.0)); + assert_eq!(u.total(XfKind::Rotate, pos2(110.0, 25.0), pos2(50.0, 100.0), true, false), crate::stage::xf_total(XfKind::Rotate, u.b, pos2(110.0, 25.0), pos2(50.0, 100.0), true, false)); + assert_eq!(u.total(XfKind::Scale { hx: 1, hy: 1 }, pos2(100.0, 50.0), pos2(200.0, 100.0), false, false), crate::stage::xf_total(XfKind::Scale { hx: 1, hy: 1 }, u.b, pos2(100.0, 50.0), pos2(200.0, 100.0), false, false)); + } + + #[test] + fn the_dragged_point_snaps_to_the_boxs_handles_and_centre() { + let f = turned(); + assert!(near(f.snap_point(Vec2::new(158.0, 62.0), 1.0), f.handle(-1, -1))); + assert!(near(f.snap_point(Vec2::new(151.0, 108.0), 1.0), Vec2::new(150.0, 110.0))); + assert_eq!(f.snap_point(Vec2::new(300.0, 300.0), 1.0), Vec2::new(300.0, 300.0), "outside the box it is free (#178)"); + // Zoomed in, the reach is the same on screen, so smaller on the stage. + assert_eq!(f.snap_point(Vec2::new(158.0, 62.0), 8.0), Vec2::new(158.0, 62.0)); + // The arrows follow the turn: the box's own x axis runs down the screen. + assert_eq!(f.cursor(XfKind::Scale { hx: 1, hy: 0 }, screen, false), CursorIcon::ResizeVertical); + assert_eq!(f.cursor(XfKind::Scale { hx: 0, hy: 1 }, screen, false), CursorIcon::ResizeHorizontal); + assert_eq!(Frame::upright([0.0, 0.0, 10.0, 10.0]).cursor(XfKind::Scale { hx: 1, hy: 1 }, screen, false), CursorIcon::ResizeNwSe); + } + + fn run(app: &mut App, id: &str, p: serde_json::Value) -> serde_json::Value { + app.s.execute(id, &p).unwrap_or_else(|e| panic!("{id}: {e}")) + } + + #[test] + fn an_instance_keeps_its_point_and_a_drawing_holds_one_while_the_tool_is() { + let mut app = App::with_context(&egui::Context::default(), Session::new(anicraft_engine::doc::Document::default()), Some(std::path::PathBuf::from("unused.png"))); + app.tool = Tool::Transform; + // A drawing object: its point is held here, not in the document. + run(&mut app, "draw.rect", json!({"x": 100, "y": 100, "w": 100, "h": 20, "stroke": null, "object": true})); + let f = frame(&app).unwrap(); + assert!(!f.keeps && !f.moved && f.movable && near(f.point, Vec2::new(150.0, 110.0))); + let undo = app.s.can_undo(); + drag_point(&mut app, Vec2::new(101.0, 111.0), 1.0, false); + let f = frame(&app).unwrap(); + assert!(f.moved && near(f.point, Vec2::new(100.0, 110.0)), "snapped to the left-middle handle: {:?}", f.point); + assert_eq!(app.s.can_undo(), undo, "no document change"); + // A Free Transform change carries it; so does a nudge (the selection only moved). + let turn = f.total(XfKind::Rotate, pos2(210.0, 110.0), pos2(100.0, 220.0), false, false); + let [a, b, c, d, e, g] = turn.m; + run(&mut app, "modify.transform", json!({"a": a, "b": b, "c": c, "d": d, "e": e, "f": g})); + carried(&mut app, &turn); + sync(&mut app); + assert!(near(frame(&app).unwrap().point, Vec2::new(100.0, 110.0)), "the hinge stays where it is"); + let b = app.s.selection_bounds(); + assert!((b.min.x - 90.0).abs() < 0.1 && (b.max.y - 210.0).abs() < 0.1, "the bar swung down from its left end: {b:?}"); + run(&mut app, "element.translate", json!({"dx": 20, "dy": 5})); + sync(&mut app); + assert!(near(frame(&app).unwrap().point, Vec2::new(120.0, 115.0))); + // Double-click puts it back; another tool, or another selection, drops it. + assert!(double_click(&mut app, screen, pos2(121.0, 116.0))); + assert!(!frame(&app).unwrap().moved); + drag_point(&mut app, Vec2::new(300.0, 300.0), 1.0, false); + app.tool = Tool::Select; + sync(&mut app); + app.tool = Tool::Transform; + assert!(!frame(&app).unwrap().moved); + + // An instance: the drag is a document change, kept and undone as one step. + let id = ElementId(run(&mut app, "modify.convert_to_symbol", json!({"name": "Arm"}))["instance"].as_u64().unwrap()); + let f = frame(&app).unwrap(); + assert!(f.keeps && !f.moved); + app.s.begin_gesture("Move Transformation Point"); + for i in 0..10 { + drag_point(&mut app, Vec2::new(400.0 + i as f32, 400.0), 1.0, false); + } + app.s.end_gesture(); + let f = frame(&app).unwrap(); + assert!(f.moved && near(f.point, Vec2::new(409.0, 400.0))); + let e = app.s.selected_elements().into_iter().map(|(_, e)| e).find(|e| e.id == id).unwrap(); + assert!(e.pivot().is_some()); + // The turn about it leaves it where it is. + let turn = f.total(XfKind::Rotate, pos2(500.0, 400.0), pos2(409.0, 500.0), false, false); + assert!(near(turn.apply(f.point), f.point)); + assert!(double_click(&mut app, screen, pos2(409.0, 400.0))); + assert!(!frame(&app).unwrap().moved); + run(&mut app, "edit.undo", json!({})); + assert!(frame(&app).unwrap().moved, "the reset is one step"); + run(&mut app, "edit.undo", json!({})); + assert!(!frame(&app).unwrap().moved, "and so is the whole drag"); + // With each object about its own point (ADR 0109) the point is not dragged. + run(&mut app, "modify.transform_origin", json!({"mode": "center"})); + assert!(!frame(&app).unwrap().movable); + } +}