mirror of
https://github.com/storytold/AniCraft.git
synced 2026-11-30 18:14:14 +01:00
1376 lines
67 KiB
Rust
1376 lines
67 KiB
Rust
//! Timeline evaluation: `(document, frame) -> DisplayList`. Pure, deterministic, no caching.
|
|
|
|
use crate::camera::Camera;
|
|
use crate::nine_slice::Slicing;
|
|
use crate::player::PlayerState;
|
|
use crate::{ColorTransform, Document, Element, ElementId, ElementKind, Layer, LayerId, LayerKind, MaskMode, Paint, Rgba, Shape, Stroke, SymbolId, SymbolKind, Timeline, TweenKind};
|
|
use anicraft_geom::walk::PathWalk;
|
|
use anicraft_geom::{Affine, FillRule, Path, Vec2};
|
|
use std::borrow::Cow;
|
|
use std::cell::Cell;
|
|
use std::sync::Arc;
|
|
|
|
/// Symbols nested deeper than this are not drawn (guards cyclic libraries).
|
|
pub const MAX_SYMBOL_DEPTH: usize = 32;
|
|
|
|
/// The work one evaluation (or one bounds query) may do, nested symbols and groups included
|
|
/// (ADR 0128). The depth cap alone leaves a symbol holding two instances of the next, 32 deep,
|
|
/// to expand 2^32 times, which no file may make AniCraft do: past the allowance the rest is
|
|
/// left out, so a hostile or damaged document draws in part instead of hanging or running
|
|
/// out of memory, and the result says so ([`DisplayList::left_out`]). Real scenes stay far
|
|
/// below it (the heaviest benchmark has 50,000 shapes).
|
|
///
|
|
/// A unit is one element or one layer visited. A shape costs one more for every
|
|
/// [`PATH_COMMANDS_PER_UNIT`] commands of its outline, and finding a symbol one more for every
|
|
/// [`LIBRARY_ENTRIES_PER_UNIT`] library entries passed, so neither a huge outline nor a huge
|
|
/// library, repeated by nesting, multiplies the work past what the allowance stands for.
|
|
pub const MAX_EVAL_ELEMENTS: u32 = 1_000_000;
|
|
|
|
/// A shape's outline costs one unit of work for each this many path commands.
|
|
pub const PATH_COMMANDS_PER_UNIT: usize = 256;
|
|
|
|
/// Finding a symbol costs one unit of work for each this many library entries looked at.
|
|
pub const LIBRARY_ENTRIES_PER_UNIT: usize = 1024;
|
|
|
|
/// An allowance of work (see [`MAX_EVAL_ELEMENTS`]) shared by everything one query visits, that
|
|
/// remembers whether it ran out.
|
|
pub(crate) struct Work {
|
|
left: Cell<u32>,
|
|
ran_out: Cell<bool>,
|
|
}
|
|
|
|
impl Work {
|
|
pub(crate) fn new(units: u32) -> Work {
|
|
Work { left: Cell::new(units), ran_out: Cell::new(false) }
|
|
}
|
|
|
|
/// Takes `units`; `false` once the allowance is spent (and from then on).
|
|
pub(crate) fn spend(&self, units: u32) -> bool {
|
|
match self.left.get().checked_sub(units) {
|
|
Some(left) if !self.ran_out.get() => {
|
|
self.left.set(left);
|
|
true
|
|
}
|
|
_ => {
|
|
self.left.set(0);
|
|
self.ran_out.set(true);
|
|
false
|
|
}
|
|
}
|
|
}
|
|
|
|
/// Something was left out because the allowance was spent.
|
|
pub(crate) fn ran_out(&self) -> bool {
|
|
self.ran_out.get()
|
|
}
|
|
|
|
/// Takes what visiting `el` costs.
|
|
pub(crate) fn visit(&self, el: &Element) -> bool {
|
|
let outline = match &el.kind {
|
|
ElementKind::Shape(s) => s.path.cmds.len() / PATH_COMMANDS_PER_UNIT,
|
|
_ => 0,
|
|
};
|
|
self.spend(u32::try_from(outline).unwrap_or(u32::MAX).saturating_add(1))
|
|
}
|
|
|
|
/// The library symbol `id`, paid for by how far into the library it is.
|
|
pub(crate) fn symbol<'d>(&self, doc: &'d Document, id: SymbolId) -> Option<&'d crate::Symbol> {
|
|
let at = doc.library.iter().position(|s| s.id == id);
|
|
let passed = at.unwrap_or(doc.library.len()) / LIBRARY_ENTRIES_PER_UNIT;
|
|
if passed > 0 && !self.spend(u32::try_from(passed).unwrap_or(u32::MAX)) {
|
|
return None;
|
|
}
|
|
at.and_then(|i| doc.library.get(i)).map(|s| &**s)
|
|
}
|
|
}
|
|
|
|
/// One shape to draw, fully resolved to stage space.
|
|
#[derive(Clone, Debug)]
|
|
pub struct DisplayItem {
|
|
pub path: Arc<Path>,
|
|
/// Local → stage transform.
|
|
pub transform: Affine,
|
|
pub fill: Option<Paint>,
|
|
pub stroke: Option<Stroke>,
|
|
pub fill_rule: FillRule,
|
|
/// The colour transform of every instance around it, composed (ADR 0056).
|
|
pub color: ColorTransform,
|
|
/// The top-level layer and element this item came from (for picking).
|
|
pub layer: LayerId,
|
|
pub element: ElementId,
|
|
/// Outline-only display (layer outline mode).
|
|
pub outline: Option<Rgba>,
|
|
/// Drawn only inside this clip (an index into [`DisplayList::clip_parents`]).
|
|
pub clip: Option<u32>,
|
|
/// Mask artwork: not drawn; it forms this clip: its fill area (strokes and opacity
|
|
/// ignored), or for a soft clip ([`DisplayList::clip_mode`]) its opacity or brightness as
|
|
/// drawn.
|
|
pub masks: Option<u32>,
|
|
/// Guide artwork: shown while editing, never in output.
|
|
pub guide: bool,
|
|
/// The innermost group this item fades with (see [`DisplayList::groups`]); `color`
|
|
/// leaves out the groups' opacity.
|
|
pub group: Option<u32>,
|
|
/// The decoded pixels a [`Paint::Bitmap`] fill shows (shared, never copied).
|
|
pub image: Option<Arc<crate::Pixels>>,
|
|
/// Whether `image` is filtered between its pixels (the bitmap's Allow Smoothing, ADR 0050);
|
|
/// off, each pixel is a hard-edged square.
|
|
pub smooth: bool,
|
|
/// A warped bitmap fill (ADR 0079): the mesh, in the item's local space, that carries the
|
|
/// image as drawn (`rest`) to where it shows (`shown`); renderers draw the image through
|
|
/// its triangles. `None` for everything else (a warped shape's path is already bent).
|
|
pub warp: Option<Arc<crate::warp::WarpMesh>>,
|
|
}
|
|
|
|
/// Back-to-front list of shapes.
|
|
#[derive(Clone, Debug, Default)]
|
|
pub struct DisplayList {
|
|
pub items: Vec<DisplayItem>,
|
|
/// One entry per clip: the enclosing clip it is intersected with. A parent always has a
|
|
/// lower index than its children. A clip with no mask artwork hides everything in it.
|
|
pub clip_parents: Vec<Option<u32>>,
|
|
/// How each clip's artwork reveals (ADR 0070), by clip index. Sparse: a clip past its end
|
|
/// is [`MaskMode::Coverage`], so lists that don't care leave it empty.
|
|
pub clip_modes: Vec<MaskMode>,
|
|
/// Groups that fade as one: a symbol instance with an opacity below 1 composites its
|
|
/// items together, then blends the result at `alpha`, so overlapping parts don't show
|
|
/// through each other. A group's items are one unbroken run of `items`, nested runs for
|
|
/// nested groups; a parent always has a lower index.
|
|
pub groups: Vec<Group>,
|
|
/// Links on text (ADR 0085): `(item, url)` for each item drawing characters that link
|
|
/// somewhere, in item order. Sparse: most lists have none.
|
|
pub links: Vec<(u32, Arc<str>)>,
|
|
/// The frame's allowance of work ([`MAX_EVAL_ELEMENTS`]) ran out, so artwork is missing
|
|
/// from this list: whoever shows or exports it says so instead of passing it off as the
|
|
/// whole frame (ADR 0128).
|
|
pub left_out: bool,
|
|
}
|
|
|
|
/// A group that fades as one (see [`DisplayList::groups`]).
|
|
#[derive(Clone, Debug, PartialEq)]
|
|
pub struct Group {
|
|
pub parent: Option<u32>,
|
|
pub alpha: f32,
|
|
/// How the group's composited pixels combine with what is below.
|
|
pub blend: crate::BlendMode,
|
|
/// Filters applied to the group's composited pixels, in order (empty for most groups).
|
|
pub filters: Arc<[crate::Filter]>,
|
|
/// The clip in force where the instance is: a filtered group is clipped after filtering.
|
|
pub clip: Option<u32>,
|
|
}
|
|
|
|
impl DisplayList {
|
|
/// How clip `c`'s artwork reveals (coverage when unset).
|
|
pub fn clip_mode(&self, c: u32) -> MaskMode {
|
|
self.clip_modes.get(c as usize).copied().unwrap_or_default()
|
|
}
|
|
|
|
/// Sets clip `c`'s mode (only a soft mode is stored; coverage stays implicit).
|
|
pub fn set_clip_mode(&mut self, c: u32, mode: MaskMode) {
|
|
let i = c as usize;
|
|
if mode.is_soft() && i < self.clip_parents.len() {
|
|
if self.clip_modes.len() <= i {
|
|
self.clip_modes.resize(i + 1, MaskMode::Coverage);
|
|
}
|
|
if let Some(m) = self.clip_modes.get_mut(i) {
|
|
*m = mode;
|
|
}
|
|
}
|
|
}
|
|
|
|
/// The opacity an item ends up with: its own times every group's it is in (what an item
|
|
/// looks like when nothing overlaps it; also what picking and outlines use).
|
|
pub fn effective_alpha(&self, item: &DisplayItem) -> f32 {
|
|
let mut a = item.color.opacity();
|
|
let mut g = item.group;
|
|
for _ in 0..self.groups.len() {
|
|
let Some(id) = g else { break };
|
|
let Some(grp) = self.groups.get(id as usize) else { break };
|
|
a *= grp.alpha;
|
|
g = grp.parent.filter(|&p| p < id);
|
|
}
|
|
a
|
|
}
|
|
|
|
/// Whether stage point `p` lies inside clip `clip` (and every clip enclosing it): the test
|
|
/// that keeps masked-away parts of a shape from being picked.
|
|
pub fn clip_contains(&self, clip: u32, p: anicraft_geom::Vec2) -> bool {
|
|
let mut c = Some(clip);
|
|
for _ in 0..self.clip_parents.len() {
|
|
let Some(id) = c else { return true };
|
|
if !self.items.iter().any(|i| i.masks == Some(id) && i.fill.is_some() && i.path.contains(p, &i.transform, i.fill_rule)) {
|
|
return false;
|
|
}
|
|
c = self.clip_parents.get(id as usize).copied().flatten().filter(|&q| q < id);
|
|
}
|
|
c.is_none()
|
|
}
|
|
|
|
/// Appends `other`'s items (drawn on top), renumbering its clips and groups.
|
|
pub fn append(&mut self, other: DisplayList) {
|
|
let base = self.clip_parents.len() as u32;
|
|
let shift = |c: Option<u32>| c.map(|c| c + base);
|
|
let gbase = self.groups.len() as u32;
|
|
let gshift = |g: Option<u32>| g.map(|g| g + gbase);
|
|
self.clip_parents.extend(other.clip_parents.into_iter().map(shift));
|
|
for (i, m) in other.clip_modes.into_iter().enumerate() {
|
|
self.set_clip_mode(base + i as u32, m);
|
|
}
|
|
self.groups.extend(other.groups.into_iter().map(|g| Group { parent: gshift(g.parent), alpha: g.alpha, blend: g.blend, filters: g.filters, clip: shift(g.clip) }));
|
|
self.left_out |= other.left_out;
|
|
let ibase = self.items.len() as u32;
|
|
self.links.extend(other.links.into_iter().map(|(i, u)| (i + ibase, u)));
|
|
self.items.extend(other.items.into_iter().map(|mut i| {
|
|
i.clip = shift(i.clip);
|
|
i.masks = shift(i.masks);
|
|
i.group = gshift(i.group);
|
|
i
|
|
}));
|
|
}
|
|
}
|
|
|
|
/// Evaluates movie frame `frame` (0-based): the scenes play one after the other, each seen
|
|
/// through its camera (ADR 0027). This is what every export draws.
|
|
pub fn evaluate(doc: &Document, frame: u32) -> DisplayList {
|
|
let (scene, local) = doc.locate(frame);
|
|
evaluate_scene_camera(doc, scene, local)
|
|
}
|
|
|
|
/// Evaluates scene `scene`'s timeline at its own `frame` in stage space, the camera not
|
|
/// applied: what the stage shows while editing (and what picking and bounds use).
|
|
pub fn evaluate_scene(doc: &Document, scene: usize, frame: u32) -> DisplayList {
|
|
let mut out = DisplayList::default();
|
|
let work = Work::new(MAX_EVAL_ELEMENTS);
|
|
eval_timeline(doc, doc.timeline(scene), frame, &Ctx::top(Affine::IDENTITY, &work), &mut out, None);
|
|
out.left_out = work.ran_out();
|
|
out
|
|
}
|
|
|
|
/// A symbol's timeline at its own `frame`, in the symbol's space, as the stage edits it while the
|
|
/// symbol is open for editing (ADR 0045): what picking and bounds use then. Its layers are the
|
|
/// top-level ones, as a scene's are in [`evaluate_scene`].
|
|
pub fn evaluate_timeline(doc: &Document, tl: &Timeline, frame: u32) -> DisplayList {
|
|
let mut out = DisplayList::default();
|
|
let work = Work::new(MAX_EVAL_ELEMENTS);
|
|
eval_timeline(doc, tl, frame, &Ctx::top(Affine::IDENTITY, &work), &mut out, None);
|
|
out.left_out = work.ran_out();
|
|
out
|
|
}
|
|
|
|
/// [`evaluate_timeline`] placed by `xf` (symbol space to stage space): what an instance of the
|
|
/// timeline at `xf` shows, but with the timeline's own layers as the top-level ones, so each item
|
|
/// still says which of them it is on. The stage draws a symbol open in place this way when onion
|
|
/// skin or Edit Multiple Frames composes its frames (ADR 0051).
|
|
pub fn evaluate_timeline_at(doc: &Document, tl: &Timeline, frame: u32, xf: Affine) -> DisplayList {
|
|
let mut out = DisplayList::default();
|
|
let work = Work::new(MAX_EVAL_ELEMENTS);
|
|
eval_timeline(doc, tl, frame, &Ctx::top(xf, &work), &mut out, None);
|
|
out.left_out = work.ran_out();
|
|
out
|
|
}
|
|
|
|
/// Scene `scene` at its own `frame` as the movie shows it: through the scene's camera, each
|
|
/// layer shifted by its depth, the camera's tint over everything (ADR 0027). Without a camera
|
|
/// this is [`evaluate_scene`].
|
|
pub fn evaluate_scene_camera(doc: &Document, scene: usize, frame: u32) -> DisplayList {
|
|
let tl = doc.timeline(scene);
|
|
let mut out = DisplayList::default();
|
|
let work = Work::new(MAX_EVAL_ELEMENTS);
|
|
eval_timeline(doc, tl, frame, &Ctx::through(tl.camera_at(frame, &doc.stage), &work), &mut out, None);
|
|
out.left_out = work.ran_out();
|
|
out
|
|
}
|
|
|
|
/// What the player shows (ADR 0024): the scene and frame its main timeline is on, each movie
|
|
/// clip at its own playhead, buttons in their pointer state, and properties scripts set, seen
|
|
/// through the scene's camera.
|
|
pub fn evaluate_player(doc: &Document, state: &PlayerState) -> DisplayList {
|
|
let mut out = DisplayList::default();
|
|
let work = Work::new(MAX_EVAL_ELEMENTS);
|
|
let play = Play { state, path: Vec::new() };
|
|
let tl = doc.timeline(state.scene);
|
|
eval_timeline(doc, tl, state.root.frame, &Ctx::through(tl.camera_at(state.root.frame, &doc.stage), &work), &mut out, Some(&play));
|
|
out.left_out = work.ran_out();
|
|
out
|
|
}
|
|
|
|
/// A symbol's timeline at `frame`, drawn at `xf` (stage space): a button's hit area, or a movie
|
|
/// clip's artwork, as the player sees it when `play` is given.
|
|
///
|
|
/// `work` is the caller's allowance, so a player step that looks at many instances pays for
|
|
/// all of them from one.
|
|
pub(crate) fn evaluate_symbol(doc: &Document, tl: &Timeline, frame: u32, xf: Affine, play: Option<&Play<'_>>, work: &Work) -> DisplayList {
|
|
let mut out = DisplayList::default();
|
|
let mut cx = Ctx::top(xf, work);
|
|
cx.depth = 1;
|
|
cx.stage = false;
|
|
eval_timeline(doc, tl, frame, &cx, &mut out, play);
|
|
out.left_out = work.ran_out();
|
|
out
|
|
}
|
|
|
|
/// The player state an evaluation follows, and the instance path of the timeline being
|
|
/// evaluated (empty for the main timeline).
|
|
pub(crate) struct Play<'a> {
|
|
pub state: &'a PlayerState,
|
|
pub path: Vec<ElementId>,
|
|
}
|
|
|
|
impl<'a> Play<'a> {
|
|
pub fn child(&self, id: ElementId) -> Play<'a> {
|
|
let mut path = Vec::with_capacity(self.path.len() + 1);
|
|
path.extend_from_slice(&self.path);
|
|
path.push(id);
|
|
Play { state: self.state, path }
|
|
}
|
|
}
|
|
|
|
/// Elements of `layer` as they appear at `frame`, with tweens applied, plus the start frame of
|
|
/// the covering keyframe. `None` when the frame is empty on this layer.
|
|
pub fn evaluate_layer_elements(layer: &Layer, frame: u32) -> Option<(u32, Cow<'_, [Arc<Element>]>)> {
|
|
evaluate_guided(layer, frame, None)
|
|
}
|
|
|
|
/// [`evaluate_layer_elements`] with a motion guide: tweened elements travel along `guide` (in
|
|
/// the layer's own space) from the point nearest their start to the point nearest their end,
|
|
/// turning with it when the tween orients to the path.
|
|
///
|
|
/// On an armature layer (ADR 0043) the instances are then placed by the pose at the frame
|
|
/// (tweened between pose keyframes): forward kinematics from the root's own transform.
|
|
pub fn evaluate_guided<'a>(layer: &'a Layer, frame: u32, guide: Option<&PathWalk>) -> Option<(u32, Cow<'a, [Arc<Element>]>)> {
|
|
let (start, els) = evaluate_tweened(layer, frame, guide)?;
|
|
let Some(arm) = layer.armature.as_deref().filter(|a| layer.kind == crate::LayerKind::Armature && !a.is_empty()) else { return Some((start, els)) };
|
|
let pose = crate::armature::pose_at(layer, frame).unwrap_or_default();
|
|
let mut els = els.into_owned();
|
|
crate::armature::apply(arm, &mut els, &pose);
|
|
Some((start, Cow::Owned(els)))
|
|
}
|
|
|
|
/// [`evaluate_guided`] as the movie shows the layer at `fps` frames a second: an armature's
|
|
/// springs (ADR 0084) swing its bones by the motion up to the frame. This is what every
|
|
/// renderer, export, the player and the stage draw; commands edit the keyed pose
|
|
/// ([`evaluate_guided`]). The same as [`evaluate_guided`] without springs.
|
|
pub fn evaluate_shown<'a>(layer: &'a Layer, frame: u32, guide: Option<&PathWalk>, fps: f32) -> Option<(u32, Cow<'a, [Arc<Element>]>)> {
|
|
let Some(arm) = layer.armature.as_deref().filter(|a| layer.kind == crate::LayerKind::Armature && a.has_springs()) else { return evaluate_guided(layer, frame, guide) };
|
|
let (start, els) = evaluate_tweened(layer, frame, guide)?;
|
|
let pose = crate::spring::sprung_pose(layer, frame, fps).unwrap_or_default();
|
|
let mut els = els.into_owned();
|
|
crate::armature::apply(arm, &mut els, &pose);
|
|
Some((start, Cow::Owned(els)))
|
|
}
|
|
|
|
pub(crate) fn evaluate_tweened<'a>(layer: &'a Layer, frame: u32, guide: Option<&PathWalk>) -> Option<(u32, Cow<'a, [Arc<Element>]>)> {
|
|
let idx = layer.keyframe_index_at(frame)?;
|
|
let kf = layer.keyframes.get(idx)?;
|
|
// A motion tween: its target follows the property curves (and its motion path, ADR 0030);
|
|
// anything else on the key holds.
|
|
if let Some(m) = &kf.motion {
|
|
let Some(i) = m.target_index(&kf.elements).filter(|_| !m.tracks.is_empty() || m.path.is_some()) else { return Some((kf.start, Cow::Borrowed(&kf.elements))) };
|
|
let mut els = kf.elements.clone();
|
|
if let Some(slot) = els.get_mut(i) {
|
|
*slot = Arc::new(m.apply(slot, (frame - kf.start) as f32));
|
|
}
|
|
return Some((kf.start, Cow::Owned(els)));
|
|
}
|
|
let Some(tween) = &kf.tween else { return Some((kf.start, Cow::Borrowed(&kf.elements))) };
|
|
let Some(next) = layer.keyframes.get(idx + 1) else { return Some((kf.start, Cow::Borrowed(&kf.elements))) };
|
|
if next.start != kf.end() || frame == kf.start {
|
|
return Some((kf.start, Cow::Borrowed(&kf.elements)));
|
|
}
|
|
let t = Progress::of(tween, (frame - kf.start) as f32 / kf.duration.max(1) as f32);
|
|
let morph = tween.kind == TweenKind::Shape;
|
|
let path = guide.map(|g| (g, tween.orient));
|
|
let runs = |els: &[Arc<Element>]| els.iter().filter(|e| raw_stroke(e).is_some()).count();
|
|
// Along a motion guide the runs are joined even when both keys have as many: a guide places
|
|
// each element by its own origin, so runs left to pair one by one would each take their own
|
|
// way along it and leave the fill they edge.
|
|
if morph && (runs(&kf.elements) != runs(&next.elements) || (path.is_some() && runs(&kf.elements) > 0)) {
|
|
return Some((kf.start, Cow::Owned(morph_raw_strokes(kf, next, t, path))));
|
|
}
|
|
let pairs = if morph && !kf.hints.is_empty() { crate::hints::hint_pairs(kf, next) } else { Vec::new() };
|
|
let els = kf
|
|
.elements
|
|
.iter()
|
|
.enumerate()
|
|
.map(|(i, a)| {
|
|
let hints: Vec<_> = pairs.iter().filter(|h| h.0 == i).map(|h| (h.1, h.2)).collect();
|
|
next.elements.get(i).and_then(|b| interpolate(a, b, t, morph, &hints, path)).map_or_else(|| a.clone(), Arc::new)
|
|
})
|
|
.collect();
|
|
Some((kf.start, Cow::Owned(els)))
|
|
}
|
|
|
|
/// How far a classic tween has gone, eased, for each property group (ADR 0081): `main` for
|
|
/// what has no group (outlines, fills, strokes, a group's members), the rest each by its
|
|
/// group's ease (the tween's own when the group has none).
|
|
#[derive(Clone, Copy, Debug, PartialEq)]
|
|
pub struct Progress {
|
|
pub main: f32,
|
|
pub position: f32,
|
|
pub rotation: f32,
|
|
pub scale: f32,
|
|
pub color: f32,
|
|
pub filters: f32,
|
|
/// The scale axes move geometrically (the tween's Keep area, ADR 0115).
|
|
pub keep_area: bool,
|
|
}
|
|
|
|
impl Progress {
|
|
/// Everything at `t`.
|
|
pub fn uniform(t: f32) -> Progress {
|
|
Progress { main: t, position: t, rotation: t, scale: t, color: t, filters: t, keep_area: false }
|
|
}
|
|
|
|
/// `tween` at linear progress `t`.
|
|
pub fn of(tween: &crate::Tween, t: f32) -> Progress {
|
|
let main = tween.easing.apply(t);
|
|
if tween.groups.is_empty() {
|
|
return Progress { keep_area: tween.keep_area, ..Progress::uniform(main) };
|
|
}
|
|
let g = |g: crate::EaseGroup| if tween.has_own(g) { tween.ease(g).apply(t) } else { main };
|
|
Progress { main, position: g(crate::EaseGroup::Position), rotation: g(crate::EaseGroup::Rotation), scale: g(crate::EaseGroup::Scale), color: g(crate::EaseGroup::Color), filters: g(crate::EaseGroup::Filters), keep_area: tween.keep_area }
|
|
}
|
|
}
|
|
|
|
/// A raw stroke run (merge drawing, ADR 0031): a raw shape's outline is stored as one element
|
|
/// per run of its stroke, apart from its fill.
|
|
fn raw_stroke(e: &Element) -> Option<&Stroke> {
|
|
match &e.kind {
|
|
ElementKind::Shape(s) if s.merge && s.fill.is_none() => s.stroke.as_ref(),
|
|
_ => None,
|
|
}
|
|
}
|
|
|
|
/// The raw fill of `els` that `path` (in `xf` space) edges: the one whose edge is within two
|
|
/// snaps of the middle of `path`, or that contains it, or the one whose origin is nearest `xf`'s.
|
|
/// The middle, not an end: a run ends at a corner, where the runs of the fill next door end
|
|
/// too, so an end says nothing about whose edge the run is. An edge two fills share (their
|
|
/// outlines joined there) goes with the lower of the two, the first in the stack.
|
|
fn fill_of(els: &[Arc<Element>], path: &Path, xf: &Affine) -> Option<usize> {
|
|
let middle = |pl: anicraft_geom::Polyline| {
|
|
let k = pl.points.len() / 2;
|
|
match (pl.points.get(k.wrapping_sub(1)), pl.points.get(k)) {
|
|
(Some(a), Some(b)) => Some(a.lerp(*b, 0.5)),
|
|
(None, b) => b.copied(),
|
|
(a, None) => a.copied(),
|
|
}
|
|
};
|
|
if let Some(p) = path.flatten(xf, 0.25).into_iter().next().and_then(middle)
|
|
&& let Some((k, _)) = els.iter().enumerate().find(|(_, e)| {
|
|
matches!(&e.kind, ElementKind::Shape(s) if s.merge && s.fill.is_some() && (s.path.contains(p, &e.transform, s.fill_rule) || s.path.distance_to_edge(p, &e.transform) <= 2.0 * anicraft_geom::planar::SNAP))
|
|
})
|
|
{
|
|
return Some(k);
|
|
}
|
|
let own = xf.translation();
|
|
els.iter()
|
|
.enumerate()
|
|
.filter(|(_, e)| matches!(&e.kind, ElementKind::Shape(s) if s.merge && s.fill.is_some()))
|
|
.min_by(|(_, a), (_, b)| own.distance(a.transform.translation()).total_cmp(&own.distance(b.transform.translation())))
|
|
.map(|(k, _)| k)
|
|
}
|
|
|
|
/// Raw stroke runs joined into one outline: the indices of the runs (the first one's space is
|
|
/// the outline's), the fill they edge, and the joined element.
|
|
struct Joined {
|
|
members: Vec<usize>,
|
|
fill: Option<usize>,
|
|
el: Element,
|
|
}
|
|
|
|
/// Whether an outline's runs are chained into whole outlines by [`joined_runs`]: a stroke with
|
|
/// no dash pattern and no width profile. A dash pattern restarts, and a profile is measured, on
|
|
/// each run, so those runs stay apart.
|
|
fn chained(el: &Element) -> bool {
|
|
raw_stroke(el).is_some_and(|st| st.style.dash.is_none() && st.profile.is_none())
|
|
}
|
|
|
|
/// The raw stroke runs of `els` joined into one element per stroke style (and scale, rotation
|
|
/// and skew, which the stroke's width follows, and colour effect), each in the space of its first run;
|
|
/// when `by_fill`, runs that edge different fills stay in separate outlines so each outline can
|
|
/// follow its own fill along a motion guide.
|
|
fn joined_runs(els: &[Arc<Element>], by_fill: bool) -> Vec<Joined> {
|
|
let mut out: Vec<Joined> = Vec::new();
|
|
for (i, e) in els.iter().enumerate() {
|
|
let (Some(st), ElementKind::Shape(s)) = (raw_stroke(e), &e.kind) else { continue };
|
|
let fill = by_fill.then(|| fill_of(els, &s.path, &e.transform)).flatten();
|
|
let slot = out.iter_mut().find_map(|j| {
|
|
let ElementKind::Shape(js) = &mut j.el.kind else { return None };
|
|
let into = j.el.transform.inverse()?.mul(&e.transform);
|
|
(j.fill == fill && j.el.transform.m[..4] == e.transform.m[..4] && js.stroke.as_ref() == Some(st) && j.el.color == e.color).then_some((&mut j.members, js, into))
|
|
});
|
|
match slot {
|
|
Some((members, js, into)) => {
|
|
members.push(i);
|
|
Arc::make_mut(&mut js.path).cmds.extend(s.path.transformed(&into).cmds);
|
|
}
|
|
None => out.push(Joined { members: vec![i], fill, el: (**e).clone() }),
|
|
}
|
|
}
|
|
for j in &mut out {
|
|
// A dash pattern restarts, and a width profile is measured, on each run; chained, the
|
|
// pattern and widths would jump on the first frame after the key. Such runs stay apart.
|
|
if chained(&j.el) && let ElementKind::Shape(s) = &mut j.el.kind {
|
|
s.path = Arc::new(anicraft_geom::morph::chain(&s.path, anicraft_geom::planar::SNAP));
|
|
}
|
|
}
|
|
out
|
|
}
|
|
|
|
/// `e` with its origin moved to `origin` (in its parent's space) and its path moved back, so
|
|
/// it looks the same.
|
|
fn rebase(e: &mut Element, origin: anicraft_geom::Vec2) {
|
|
let mut moved = e.transform;
|
|
moved.m[4] = origin.x;
|
|
moved.m[5] = origin.y;
|
|
let (Some(inv), ElementKind::Shape(s)) = (moved.inverse(), &mut e.kind) else { return };
|
|
let d = inv.apply(e.transform.translation());
|
|
if !d.is_finite() {
|
|
return;
|
|
}
|
|
s.path = Arc::new(s.path.transformed(&Affine::translate(d.x, d.y)));
|
|
e.transform = moved;
|
|
}
|
|
|
|
/// What stands, in an in-between frame, for a run `x` joined into the outline `el`: nothing
|
|
/// drawn (no fill, no stroke) but the run's identity over the outline, so a run selected on a
|
|
/// key stays selected through the tween, with the outline's bounds.
|
|
fn joined_member(x: &Element, el: &Element) -> Element {
|
|
let mut e = el.clone();
|
|
e.id = x.id;
|
|
e.name.clone_from(&x.name);
|
|
if let ElementKind::Shape(s) = &mut e.kind {
|
|
let pad = s.stroke.as_ref().map_or(0.0, Stroke::reach);
|
|
let b = s.path.bounds();
|
|
if (b.width() == 0.0 || b.height() == 0.0) && pad > 0.0 {
|
|
let r = b.inflate(pad);
|
|
s.path = Arc::new(Path::rect(r.min.x, r.min.y, r.width(), r.height()));
|
|
}
|
|
s.stroke = None;
|
|
s.fill = None;
|
|
}
|
|
e
|
|
}
|
|
|
|
/// The partner on `b` of each joined outline of `a`: one with the same stroke and colour first, then the
|
|
/// rest in order.
|
|
fn pair_joined(a: &[Joined], b: &[Joined]) -> Vec<Option<usize>> {
|
|
let mut taken = vec![false; b.len()];
|
|
let mut out: Vec<Option<usize>> = a
|
|
.iter()
|
|
.map(|x| {
|
|
let m = b.iter().zip(&taken).position(|(y, &used)| !used && raw_stroke(&y.el) == raw_stroke(&x.el) && y.el.color == x.el.color)?;
|
|
if let Some(u) = taken.get_mut(m) {
|
|
*u = true;
|
|
}
|
|
Some(m)
|
|
})
|
|
.collect();
|
|
for slot in out.iter_mut().filter(|s| s.is_none()) {
|
|
*slot = taken.iter().position(|&used| !used);
|
|
if let Some(u) = slot.and_then(|m| taken.get_mut(m)) {
|
|
*u = true;
|
|
}
|
|
}
|
|
out
|
|
}
|
|
|
|
/// `el` with its runs chained into whole outlines, for a morph against an outline that is
|
|
/// chained: both ends then correspond along the whole outline, the way the fill's do. Only the
|
|
/// in-between frames see this; the keys keep their own runs.
|
|
fn chained_for_morph(el: &Element) -> Element {
|
|
let mut e = el.clone();
|
|
if let ElementKind::Shape(s) = &mut e.kind {
|
|
s.path = Arc::new(anicraft_geom::morph::chain(&s.path, anicraft_geom::planar::SNAP));
|
|
}
|
|
e
|
|
}
|
|
|
|
/// `e` shrunk to the centre of its path: where an outline without a partner grows from or
|
|
/// shrinks to.
|
|
fn collapsed(e: &Element) -> Element {
|
|
let mut e = e.clone();
|
|
if let ElementKind::Shape(s) = &mut e.kind {
|
|
let c = s.path.bounds().center();
|
|
s.path = Arc::new(s.path.transformed(&Affine { m: [0.0, 0.0, 0.0, 0.0, c.x, c.y] }));
|
|
}
|
|
e
|
|
}
|
|
|
|
/// A shape tween between keyframes whose raw shapes have different numbers of stroke runs: the
|
|
/// runs of each keyframe are joined into whole outlines that morph like the fills, in place of
|
|
/// pairing the runs one by one. An outline with no partner shrinks away or grows in. Hints
|
|
/// steer the outlines (and the other elements) they are placed on at both ends. Everything else
|
|
/// pairs in order, as in a plain shape tween.
|
|
fn morph_raw_strokes(kf: &crate::Keyframe, next: &crate::Keyframe, t: Progress, guide: Option<(&PathWalk, bool)>) -> Vec<Arc<Element>> {
|
|
let (a, b) = (&kf.elements, &next.elements);
|
|
let (mut runs_a, mut runs_b) = (joined_runs(a, guide.is_some()), joined_runs(b, guide.is_some()));
|
|
if guide.is_some() {
|
|
// A guide places each element by its own origin, so an outline with an origin of its own
|
|
// would take another path than the fill it edges. Each outline takes the origin of the
|
|
// fill it edges, so it travels with that fill; with no fill, of the first outline.
|
|
for (els, runs) in [(a, &mut runs_a), (b, &mut runs_b)] {
|
|
let first = runs.first().map(|r| r.el.transform.translation());
|
|
for r in runs.iter_mut() {
|
|
let origin = r.fill.and_then(|k| els.get(k)).map(|e| e.transform.translation()).or(first);
|
|
if let Some(origin) = origin {
|
|
rebase(&mut r.el, origin);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
let partner = pair_joined(&runs_a, &runs_b);
|
|
let placed = if kf.hints.is_empty() { Vec::new() } else { crate::hints::placed_hints(kf, next) };
|
|
// The hints placed on what `on_a` and `on_b` pick, in the spaces of `x` and `y`.
|
|
let hints =
|
|
|on_a: &dyn Fn(usize) -> bool, on_b: &dyn Fn(usize) -> bool, x: &Element, y: &Element| -> Vec<(anicraft_geom::Vec2, anicraft_geom::Vec2)> {
|
|
let (Some(ia), Some(ib)) = (x.transform.inverse(), y.transform.inverse()) else { return Vec::new() };
|
|
placed.iter().filter(|h| on_a(h.0) && on_b(h.1)).map(|h| (ia.apply(h.2), ib.apply(h.3))).collect()
|
|
};
|
|
let mut rest_b = b.iter().enumerate().filter(|(_, e)| raw_stroke(e).is_none());
|
|
let mut out = Vec::with_capacity(a.len());
|
|
// Which outline of the start key draws each of its runs, worked out once: searching the
|
|
// outlines for every run would cost n(n+1)/2 comparisons for an outline of n runs.
|
|
let mut outline_of: Vec<Option<usize>> = vec![None; a.len()];
|
|
for (k, r) in runs_a.iter().enumerate() {
|
|
for &m in &r.members {
|
|
if let Some(slot) = outline_of.get_mut(m) {
|
|
*slot = Some(k);
|
|
}
|
|
}
|
|
}
|
|
// Each joined outline of the start key, tweened; it stands in for its first run.
|
|
let mut tweened: Vec<Option<Arc<Element>>> = vec![None; runs_a.len()];
|
|
for (i, x) in a.iter().enumerate() {
|
|
if raw_stroke(x).is_none() {
|
|
let y = rest_b.next();
|
|
out.push(
|
|
y.and_then(|(j, y)| interpolate(x, y, t, true, &hints(&|h| h == i, &|h| h == j, x, y), guide)).map_or_else(|| x.clone(), Arc::new),
|
|
);
|
|
continue;
|
|
}
|
|
let Some((k, ra)) = outline_of.get(i).copied().flatten().and_then(|k| runs_a.get(k).map(|r| (k, r))) else { continue };
|
|
if let Some(el) = tweened.get(k).and_then(Option::as_ref) {
|
|
// A later run of the outline keeps its identity, drawn by the first.
|
|
out.push(Arc::new(joined_member(x, el)));
|
|
continue;
|
|
}
|
|
let el = match partner.get(k).copied().flatten().and_then(|m| runs_b.get(m)) {
|
|
Some(rb) => {
|
|
// A solid outline against a dashed or profiled one: only one of the two is
|
|
// chained, so a whole outline would morph against the other key's loose runs and
|
|
// the stroke would follow a different correspondence than the fill. Both are
|
|
// chained for the morph.
|
|
let (x, y) = if chained(&ra.el) == chained(&rb.el) {
|
|
(Cow::Borrowed(&ra.el), Cow::Borrowed(&rb.el))
|
|
} else {
|
|
(Cow::Owned(chained_for_morph(&ra.el)), Cow::Owned(chained_for_morph(&rb.el)))
|
|
};
|
|
interpolate(&x, &y, t, true, &hints(&|h| ra.members.contains(&h), &|h| rb.members.contains(&h), &x, &y), guide)
|
|
}
|
|
// No partner on the end keyframe: it shrinks away.
|
|
None => interpolate(&ra.el, &collapsed(&ra.el), t, false, &[], guide),
|
|
};
|
|
let el = Arc::new(el.unwrap_or_else(|| ra.el.clone()));
|
|
if let Some(slot) = tweened.get_mut(k) {
|
|
*slot = Some(el.clone());
|
|
}
|
|
out.push(el);
|
|
}
|
|
// Outlines only on the end keyframe grow in.
|
|
for (_, rb) in runs_b.iter().enumerate().filter(|(m, _)| !partner.contains(&Some(*m))) {
|
|
if let Some(el) = interpolate(&collapsed(&rb.el), &rb.el, t, false, &[], guide) {
|
|
out.push(Arc::new(el));
|
|
}
|
|
}
|
|
out
|
|
}
|
|
|
|
/// Interpolates two elements; `None` when they cannot tween. With `morph` (a shape tween),
|
|
/// shapes of different structure blend through [`anicraft_geom::morph`], steered by `hints`
|
|
/// (shape hints in each element's own space, ADR 0023); otherwise a shape changes only when
|
|
/// both keyframes share its structure.
|
|
fn interpolate(a: &Element, b: &Element, pr: Progress, morph: bool, hints: &[(anicraft_geom::Vec2, anicraft_geom::Vec2)], guide: Option<(&PathWalk, bool)>) -> Option<Element> {
|
|
let t = pr.main;
|
|
let kind = match (&a.kind, &b.kind) {
|
|
(ElementKind::Shape(sa), ElementKind::Shape(sb)) => {
|
|
// Warped on both keyframes (ADR 0079): the pins tween and bend the outline as drawn.
|
|
let warp = match (sa.live_warp(), sb.live_warp()) {
|
|
(Some(wa), Some(wb)) if !morph || hints.is_empty() => wa.lerp(wb, t),
|
|
_ => None,
|
|
};
|
|
let path = if let Some(w) = &warp {
|
|
w.outline()
|
|
} else if Arc::ptr_eq(&sa.path, &sb.path) && hints.is_empty() {
|
|
sa.path.clone()
|
|
} else if morph {
|
|
anicraft_geom::morph::morph_hinted(&sa.path, &sb.path, hints, t).map(Arc::new).unwrap_or_else(|| sa.path.clone())
|
|
} else {
|
|
sa.path.lerp(&sb.path, t).map(Arc::new).unwrap_or_else(|| sa.path.clone())
|
|
};
|
|
let fill = match (&sa.fill, &sb.fill) {
|
|
(Some(x), Some(y)) => Some(x.lerp(y, t)),
|
|
(x, _) => x.clone(),
|
|
};
|
|
let stroke = match (&sa.stroke, &sb.stroke) {
|
|
(Some(x), Some(y)) => Some(x.lerp(y, t)),
|
|
(x, _) => x.clone(),
|
|
};
|
|
let warp = match warp {
|
|
Some(mut w) => {
|
|
w.shown = crate::warp::fingerprint(&path);
|
|
Some(Arc::new(w))
|
|
}
|
|
// Not tweening the pins: the shape keeps its warp only while it shows it.
|
|
None => sa.warp.clone().filter(|w| w.shows(&path)),
|
|
};
|
|
ElementKind::Shape(Shape { path, fill, stroke, fill_rule: sa.fill_rule, merge: sa.merge, warp })
|
|
}
|
|
// An instance tweens its filters: pairwise when both keyframes have the same kinds in
|
|
// the same order, else as Animate pairs them, a filter without a partner fading in or
|
|
// out (ADR 0099).
|
|
(ElementKind::Symbol { symbol: s1, filters: fa, .. }, ElementKind::Symbol { symbol: s2, filters: fb, .. }) if s1 == s2 => {
|
|
let mut k = a.kind.clone();
|
|
if let (ElementKind::Symbol { filters, .. }, Some(lerped)) = (&mut k, crate::filter::lerp_filters(fa, fb, pr.filters)) {
|
|
*filters = lerped;
|
|
}
|
|
k
|
|
}
|
|
// Text tweens its placement, colour effect and filters (ADR 0099); the words stay the
|
|
// first keyframe's.
|
|
(ElementKind::Text(ta), ElementKind::Text(tb)) => match crate::filter::lerp_filters(&ta.filters, &tb.filters, pr.filters) {
|
|
Some(filters) => ElementKind::Text(Arc::new(crate::TextBlock { filters, ..(**ta).clone() })),
|
|
None => a.kind.clone(),
|
|
},
|
|
(ElementKind::Camera, ElementKind::Camera) => ElementKind::Camera,
|
|
// A group tweens its placement and colour effect, and its members pair by order, layer by
|
|
// layer, tweening as they would on their own (ADR 0073); a member without a partner holds.
|
|
(ElementKind::Group { members: ma }, ElementKind::Group { members: mb }) => {
|
|
let mut members = ma.clone();
|
|
for (la, lb) in members.layers.iter_mut().zip(&mb.layers) {
|
|
let (Some(ka), Some(kb)) = (la.keyframe_at(0), lb.keyframe_at(0)) else { continue };
|
|
let els: Vec<Arc<Element>> = ka.elements.iter().enumerate().map(|(i, x)| kb.elements.get(i).and_then(|y| interpolate(x, y, Progress::uniform(t), morph, &[], None)).map_or_else(|| x.clone(), Arc::new)).collect();
|
|
if let Some(k) = Arc::make_mut(la).keyframe_mut(0) {
|
|
k.elements = els;
|
|
}
|
|
}
|
|
ElementKind::Group { members }
|
|
}
|
|
_ => return None,
|
|
};
|
|
let (da, db) = (a.transform.decompose(), b.transform.decompose());
|
|
let mut d = da.lerp(&db, pr.position);
|
|
if pr.rotation != pr.position || pr.scale != pr.position {
|
|
let (r, s) = (da.lerp(&db, pr.rotation), da.lerp(&db, pr.scale));
|
|
(d.rotation, d.skew, d.sx, d.sy) = (r.rotation, r.skew, s.sx, s.sy);
|
|
}
|
|
// Keep area (ADR 0115): each scale axis goes geometrically from its key to the next, so
|
|
// the area (sx · sy; skew and rotation don't change it) of two keys that share it stays on
|
|
// every frame, and eases smoothly from one to the other when they don't.
|
|
if pr.keep_area {
|
|
d.sx = anicraft_geom::lerp_geometric(da.sx, db.sx, pr.scale);
|
|
d.sy = anicraft_geom::lerp_geometric(da.sy, db.sy, pr.scale);
|
|
}
|
|
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);
|
|
}
|
|
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.
|
|
#[derive(Clone, Copy)]
|
|
struct Ctx<'a> {
|
|
/// The evaluation's allowance of work ([`MAX_EVAL_ELEMENTS`]), shared by everything nested
|
|
/// in it.
|
|
work: &'a Work,
|
|
/// Local → stage transform and colour effect of the enclosing instance.
|
|
xf: Affine,
|
|
color: ColorTransform,
|
|
depth: usize,
|
|
/// The top-level layer and element everything inside belongs to (for picking).
|
|
root: Option<(LayerId, ElementId)>,
|
|
outline: Option<Rgba>,
|
|
/// The stage as edited (ADR 0061): layers in outline mode are drawn as outlines. Off for
|
|
/// the movie (every export, the player): View as Outlines is an editing aid.
|
|
stage: bool,
|
|
/// The clip everything inside is drawn within.
|
|
clip: Option<u32>,
|
|
/// Set while evaluating mask artwork: everything inside forms this clip.
|
|
masks: Option<u32>,
|
|
/// Set while evaluating guide artwork.
|
|
guide: bool,
|
|
/// The group everything inside fades with.
|
|
group: Option<u32>,
|
|
/// The camera the scene's layers are seen through (main timeline only; each layer's
|
|
/// transform comes from it and the layer's depth, and `xf` is ignored).
|
|
camera: Option<Camera>,
|
|
/// The 9-slice scaling of the instance whose timeline this is (ADR 0055): its own shapes go
|
|
/// through it, in place of the scale in `xf`. Not passed on to nested symbols.
|
|
slice: Option<Slicing>,
|
|
}
|
|
|
|
impl<'a> Ctx<'a> {
|
|
fn top(xf: Affine, work: &'a Work) -> Ctx<'a> {
|
|
Ctx { work, xf, color: ColorTransform::IDENTITY, depth: 0, root: None, outline: None, stage: true, clip: None, masks: None, guide: false, group: None, camera: None, slice: None }
|
|
}
|
|
|
|
/// A main timeline seen through `camera`: its tint colours everything.
|
|
fn through(camera: Option<Camera>, work: &'a Work) -> Ctx<'a> {
|
|
let mut cx = Ctx::top(Affine::IDENTITY, work);
|
|
cx.stage = false;
|
|
if let Some(c) = camera {
|
|
cx.color = c.color();
|
|
cx.camera = Some(c);
|
|
}
|
|
cx
|
|
}
|
|
}
|
|
|
|
/// The first frame of the unbroken run of keyframes on `layer`, up to `frame`, that hold
|
|
/// element `id` as an instance of `symbol`: where a movie clip instance started playing.
|
|
pub fn instance_start(layer: &Layer, frame: u32, id: ElementId, symbol: SymbolId) -> u32 {
|
|
let Some(mut i) = layer.keyframe_index_at(frame) else { return frame };
|
|
let holds = |k: &crate::Keyframe| k.elements.iter().any(|e| e.id == id && matches!(e.kind, ElementKind::Symbol { symbol: s, .. } if s == symbol));
|
|
let mut start = layer.keyframes.get(i).map_or(frame, |k| k.start);
|
|
while let Some(prev) = i.checked_sub(1).and_then(|p| layer.keyframes.get(p)) {
|
|
if prev.end() != start || !holds(prev) {
|
|
break;
|
|
}
|
|
start = prev.start;
|
|
i -= 1;
|
|
}
|
|
start
|
|
}
|
|
|
|
/// Most lines of a guide layer that are looked at when joining them into one path.
|
|
const MAX_GUIDE_LINES: usize = 512;
|
|
|
|
/// How near two line ends are to be one corner of the guide, in the layer's pixels. Lines drawn
|
|
/// with snapping, and the pieces merge drawing cuts a line into, meet much closer than this.
|
|
const GUIDE_JOIN: f32 = 0.75;
|
|
|
|
/// The path a guide layer traces at `frame`, in the layer's own space: its first shape's line,
|
|
/// continued through every other line on the layer that meets it end to end. A guide drawn as
|
|
/// several strokes (a zigzag made with the Line tool is one raw stroke per straight run, #490)
|
|
/// is one path, sharp corners and all; a closed outline is followed once round.
|
|
pub fn guide_walk(guide: &Layer, frame: u32) -> Option<PathWalk> {
|
|
let (_, els) = evaluate_layer_elements(guide, frame)?;
|
|
let mut lines = els
|
|
.iter()
|
|
.filter_map(|e| match &e.kind {
|
|
ElementKind::Shape(s) => Some(s.path.flatten(&e.transform, 0.25)),
|
|
ElementKind::Symbol { .. } | ElementKind::Text(_) | ElementKind::Camera | ElementKind::Group { .. } => None,
|
|
})
|
|
.flatten()
|
|
.filter(|l| l.points.len() >= 2 && l.points.iter().all(|p| p.is_finite()))
|
|
.take(MAX_GUIDE_LINES);
|
|
let first = lines.next()?;
|
|
let mut pts = first.points;
|
|
if first.closed {
|
|
// Round and back to its start: nothing joins a closed outline.
|
|
if let Some(&start) = pts.first() {
|
|
pts.push(start);
|
|
}
|
|
return PathWalk::new(&pts);
|
|
}
|
|
let mut rest: Vec<Vec<Vec2>> = lines.filter(|l| !l.closed).map(|l| l.points).collect();
|
|
// Grow the path at its end, then at its start, one line at a time (each line is used once,
|
|
// so this ends after at most `MAX_GUIDE_LINES` joins).
|
|
let near = |a: Vec2, b: Vec2| a.distance(b) <= GUIDE_JOIN;
|
|
while let (Some(&head), Some(&tail)) = (pts.first(), pts.last()) {
|
|
let join = rest.iter().enumerate().find_map(|(i, l)| {
|
|
let (a, b) = (*l.first()?, *l.last()?);
|
|
// (which line, joins at the path's end, the line runs backwards)
|
|
if near(tail, a) {
|
|
Some((i, true, false))
|
|
} else if near(tail, b) {
|
|
Some((i, true, true))
|
|
} else if near(head, b) {
|
|
Some((i, false, false))
|
|
} else if near(head, a) {
|
|
Some((i, false, true))
|
|
} else {
|
|
None
|
|
}
|
|
});
|
|
let Some((i, at_end, backwards)) = join else { break };
|
|
let mut line = rest.swap_remove(i);
|
|
if backwards {
|
|
line.reverse();
|
|
}
|
|
if at_end {
|
|
pts.extend(line.into_iter().skip(1));
|
|
} else {
|
|
line.pop();
|
|
line.extend(pts);
|
|
pts = line;
|
|
}
|
|
}
|
|
PathWalk::new(&pts)
|
|
}
|
|
|
|
/// The tweened transform `tw` moved onto the guide: its origin travels from the point on the
|
|
/// guide nearest the start keyframe's origin to the point nearest the end's; with `orient`, it
|
|
/// also turns as the path turns.
|
|
fn follow(g: &PathWalk, orient: bool, from: &Affine, to: &Affine, t: f32, tw: Affine) -> Affine {
|
|
let (s0, s1) = (g.project(from.translation()), g.project(to.translation()));
|
|
let s = s0 + (s1 - s0) * t;
|
|
let p = g.at(s);
|
|
let [a, b, c, d, _, _] = tw.m;
|
|
let mut lin = Affine { m: [a, b, c, d, 0.0, 0.0] };
|
|
if orient {
|
|
let (d0, d1) = (g.tangent(s0), g.tangent(s));
|
|
lin = Affine::rotate(d1.y.atan2(d1.x) - d0.y.atan2(d0.x)).mul(&lin);
|
|
}
|
|
let [a, b, c, d, _, _] = lin.m;
|
|
let out = Affine { m: [a, b, c, d, p.x, p.y] };
|
|
if out.is_finite() { out } else { tw }
|
|
}
|
|
|
|
fn eval_timeline(doc: &Document, tl: &Timeline, frame: u32, cx: &Ctx<'_>, out: &mut DisplayList, play: Option<&Play<'_>>) {
|
|
if cx.depth > MAX_SYMBOL_DEPTH {
|
|
return;
|
|
}
|
|
// One clip per visible mask layer, nested in the enclosing clip. Inside mask artwork every
|
|
// layer is artwork, so masks there do not mask again. A hidden mask layer masks nothing.
|
|
let mut clips: Vec<(LayerId, u32)> = Vec::new();
|
|
if cx.masks.is_none() {
|
|
for layer in tl.layers.iter().filter(|l| l.kind == LayerKind::Mask && l.visible) {
|
|
let c = out.clip_parents.len() as u32;
|
|
clips.push((layer.id, c));
|
|
out.clip_parents.push(cx.clip);
|
|
out.set_clip_mode(c, layer.mask_mode);
|
|
}
|
|
}
|
|
let clip_of = |id: LayerId| clips.iter().find(|(l, _)| *l == id).map(|(_, c)| *c);
|
|
// Folders draw nothing, and a hidden folder hides everything in it.
|
|
let has_folders = tl.layers.iter().any(|l| l.kind == LayerKind::Folder);
|
|
// Deepest first, ties in timeline order (ADR 0082); depth belongs to a scene's own layers.
|
|
// (Only sorted when some layer has a depth: nested timelines allocate nothing.)
|
|
let sorted = (cx.depth == 0 && tl.layers.iter().any(|l| l.has_depth())).then(|| tl.draw_order(frame));
|
|
// Each layer's space (ADR 0113): a layer with a parent layer is placed by that layer's
|
|
// lead object at this frame. (Only worked out when some layer has a parent.)
|
|
let rig = tl.has_rig().then(|| tl.rig_spaces(frame, doc.stage.fps));
|
|
let n = tl.layers.len();
|
|
for k in 0..n {
|
|
let index = sorted.as_ref().map_or(n - 1 - k, |o| o.get(k).copied().unwrap_or(n));
|
|
let Some(layer) = tl.layers.get(index) else { continue };
|
|
// A layer looked at counts as an element does, so a timeline of empty layers, repeated
|
|
// by nesting, is bounded too.
|
|
if !cx.work.spend(1) {
|
|
return;
|
|
}
|
|
// Guide artwork is listed (marked, for editing) but never drawn; inside mask artwork
|
|
// it plays no part at all.
|
|
let is_guide = layer.kind == LayerKind::Guide;
|
|
// The camera layer holds the camera, not artwork (ADR 0027).
|
|
if !layer.visible || matches!(layer.kind, LayerKind::Folder | LayerKind::Camera) || (is_guide && cx.masks.is_some()) || (has_folders && tl.hidden_by_folder(index)) {
|
|
continue;
|
|
}
|
|
let (clip, masks) = match (cx.masks, layer.kind) {
|
|
(Some(_), _) => (cx.clip, cx.masks),
|
|
(None, LayerKind::Mask) => (cx.clip, clip_of(layer.id)),
|
|
(None, LayerKind::Guide) => (cx.clip, None),
|
|
(None, _) => (layer.parent.and_then(clip_of).or(cx.clip), None),
|
|
};
|
|
let guide = cx.guide || is_guide;
|
|
// A layer guided by a guide layer: its tweens follow the guide's first path.
|
|
let walk = layer.parent.and_then(|p| tl.layer(p)).filter(|g| g.kind == LayerKind::Guide).and_then(|g| guide_walk(g, frame));
|
|
let shown = evaluate_shown(layer, frame, walk.as_ref(), doc.stage.fps);
|
|
let layer_outline = cx.outline.or(if layer.outline && cx.stage { Some(layer.color) } else { None });
|
|
// Through a camera, each layer is placed by the camera and its own depth (an attached
|
|
// layer stays put); a layer the camera has passed isn't drawn.
|
|
let layer_xf = match cx.camera {
|
|
Some(c) => match c.layer_view(&doc.stage, layer, frame) {
|
|
Some(v) => v,
|
|
None => continue,
|
|
},
|
|
None => cx.xf,
|
|
};
|
|
let layer_xf = match rig.as_ref().and_then(|r| r.get(index)) {
|
|
Some(space) => layer_xf.mul(space),
|
|
None => layer_xf,
|
|
};
|
|
// A reference video (ADR 0116) goes under the layer's artwork: a placeholder with no
|
|
// paint, marked as guide artwork, so it is in no movie and no export. The stage alone
|
|
// fills it with the video's frame. Only on the timeline being looked at, never through
|
|
// a symbol or in mask artwork.
|
|
if let Some(v) = layer.video.as_deref().filter(|v| cx.depth == 0 && masks.is_none() && v.time_at(frame, doc.stage.fps).is_some()) {
|
|
out.items.push(DisplayItem {
|
|
path: Arc::new(Path::rect(0.0, 0.0, v.width as f32, v.height as f32)),
|
|
transform: layer_xf.mul(&v.transform),
|
|
fill: None,
|
|
stroke: None,
|
|
fill_rule: FillRule::NonZero,
|
|
color: ColorTransform::alpha(tl.layer_opacity(index)),
|
|
layer: layer.id,
|
|
element: v.id,
|
|
outline: None,
|
|
clip: None,
|
|
masks: None,
|
|
guide: true,
|
|
group: None,
|
|
image: None,
|
|
smooth: true,
|
|
warp: None,
|
|
});
|
|
}
|
|
let Some((kf_start, elements)) = shown else { continue };
|
|
// Data bindings (ADR 0118): a table's column in place of a bound instance's property.
|
|
let elements = doc.bound_elements(elements, frame);
|
|
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);
|
|
}
|
|
}
|
|
}
|
|
|
|
/// The layer an element is drawn on, as [`eval_element`] needs it.
|
|
#[derive(Clone, Copy)]
|
|
struct LayerCtx<'a> {
|
|
layer: &'a Layer,
|
|
frame: u32,
|
|
/// The first frame of the keyframe the element is on.
|
|
kf_start: u32,
|
|
clip: Option<u32>,
|
|
masks: Option<u32>,
|
|
guide: bool,
|
|
outline: Option<Rgba>,
|
|
/// The layer's space (and, inside a group, the group's) to stage space.
|
|
xf: Affine,
|
|
}
|
|
|
|
fn eval_element(doc: &Document, cx: &Ctx<'_>, lc: &LayerCtx<'_>, el: &Element, out: &mut DisplayList, play: Option<&Play<'_>>) {
|
|
// Every element drawn counts, however deep, and a shape by the size of its outline: see
|
|
// MAX_EVAL_ELEMENTS.
|
|
if !cx.work.visit(el) {
|
|
return;
|
|
}
|
|
let LayerCtx { layer, frame, kf_start, clip, masks, guide, outline: layer_outline, xf: layer_xf } = *lc;
|
|
// In the player, a symbol instance has its own path, and maybe properties a script set.
|
|
let child = match (&el.kind, play) {
|
|
(ElementKind::Symbol { .. }, Some(p)) => Some(p.child(el.id)),
|
|
// So is a dynamic or input text field (ADR 0066).
|
|
(ElementKind::Text(t), Some(p)) if t.field.is_some() => Some(p.child(el.id)),
|
|
_ => None,
|
|
};
|
|
let set;
|
|
let el: &Element = match child.as_ref().and_then(|c| c.state.props.get(&c.path)) {
|
|
Some(ov) if !ov.shown() => return,
|
|
Some(ov) => {
|
|
set = ov.apply(el);
|
|
&set
|
|
}
|
|
None => el,
|
|
};
|
|
let (root_layer, root_el) = cx.root.unwrap_or((layer.id, el.id));
|
|
let xf = layer_xf.mul(&el.transform);
|
|
let fx = el.color.transform();
|
|
let color = cx.color.concat(&fx);
|
|
match &el.kind {
|
|
ElementKind::Shape(s) => {
|
|
// Inside a 9-slice instance, the shape's outline is cut and mapped (bitmap
|
|
// fills scale normally, as in Animate).
|
|
let sliced = cx.slice.filter(|_| !matches!(s.fill, Some(Paint::Bitmap { .. }))).map(|sl| sliced_shape(s, &el.transform, &sl));
|
|
let is_sliced = sliced.is_some();
|
|
let (path, transform, fill, stroke) = match sliced {
|
|
Some(x) => x,
|
|
None => (s.path.clone(), xf, s.fill.clone(), s.stroke.clone()),
|
|
};
|
|
out.items.push(DisplayItem {
|
|
path,
|
|
transform,
|
|
fill,
|
|
stroke,
|
|
fill_rule: s.fill_rule,
|
|
color,
|
|
layer: root_layer,
|
|
element: root_el,
|
|
outline: layer_outline,
|
|
clip,
|
|
masks,
|
|
guide,
|
|
group: cx.group,
|
|
image: match &s.fill {
|
|
Some(Paint::Bitmap { bitmap, .. }) => doc.bitmap(*bitmap).and_then(crate::Bitmap::pixels),
|
|
_ => None,
|
|
},
|
|
smooth: match &s.fill {
|
|
Some(Paint::Bitmap { bitmap, .. }) => doc.bitmap(*bitmap).is_none_or(|b| b.smoothing),
|
|
_ => true,
|
|
},
|
|
// A bitmap bent by its warp is drawn through the mesh (ADR 0079).
|
|
warp: match &s.fill {
|
|
Some(Paint::Bitmap { .. }) if !is_sliced => s.live_warp().filter(|w| !w.at_rest()).and_then(crate::warp::Warp::mesh).map(Arc::new),
|
|
_ => None,
|
|
},
|
|
});
|
|
}
|
|
ElementKind::Text(t) => {
|
|
// Text with filters draws on its own, as a movie clip does (ADR 0099): its items
|
|
// composite in a group the filters run on, and the group fades at the text's alpha.
|
|
// (Mask artwork takes neither.)
|
|
let (color, group) = if masks.is_none() && crate::filter::any_active(&t.filters) {
|
|
let gid = out.groups.len() as u32;
|
|
out.groups.push(Group { parent: cx.group, alpha: fx.alpha_factor().unwrap_or(1.0), blend: crate::BlendMode::Normal, filters: crate::filter::active(&t.filters).into(), clip });
|
|
let inner = if fx.alpha_factor().is_some() { fx.without_alpha() } else { fx };
|
|
(cx.color.concat(&inner), Some(gid))
|
|
} else {
|
|
(color, cx.group)
|
|
};
|
|
let item = |path: Arc<Path>, transform: Affine, fill: Option<Paint>, stroke: Option<Stroke>, clip: Option<u32>, masks: Option<u32>| DisplayItem {
|
|
path,
|
|
transform,
|
|
fill,
|
|
stroke,
|
|
fill_rule: FillRule::NonZero,
|
|
color,
|
|
layer: root_layer,
|
|
element: root_el,
|
|
outline: layer_outline,
|
|
clip,
|
|
masks,
|
|
guide,
|
|
group,
|
|
image: None,
|
|
smooth: true,
|
|
warp: None,
|
|
};
|
|
match &t.field {
|
|
// Mask artwork: a field's text masks; its box and border don't.
|
|
Some(f) if masks.is_none() => {
|
|
let live = child.as_ref().map(|c| (c.state.fields.get(&c.path), c.state.focus.as_deref() == Some(c.path.as_slice())));
|
|
field_items(t, f, live, xf, clip, out, item);
|
|
}
|
|
_ => match child.as_ref().and_then(|c| c.state.fields.get(&c.path)).and_then(|s| s.look.as_ref()) {
|
|
Some(l) => out.items.push(item(l.outline.clone(), xf, Some(Paint::Solid(t.color)), None, clip, masks)),
|
|
// One item per colour (ADR 0085), with its link.
|
|
None => text_fills(t, out, |path, color| item(path, xf, Some(Paint::Solid(color)), None, clip, masks)),
|
|
},
|
|
}
|
|
}
|
|
ElementKind::Camera => {}
|
|
// A group (ADR 0073): its members, placed and coloured by it, as if they stood on its layer
|
|
// (graphics and movie clips inside keep time with it), picked as it. Below full opacity it
|
|
// fades as one, as an instance does.
|
|
ElementKind::Group { members } => {
|
|
if cx.depth > MAX_SYMBOL_DEPTH + crate::MAX_GROUP_DEPTH {
|
|
return;
|
|
}
|
|
let fade = fx.alpha_factor().unwrap_or(1.0);
|
|
let (color, group) = if masks.is_none() && 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 });
|
|
(cx.color.concat(&fx.without_alpha()), Some(gid))
|
|
} else {
|
|
(color, cx.group)
|
|
};
|
|
let inner = Ctx { color, depth: cx.depth + 1, root: Some((root_layer, root_el)), group, slice: None, camera: None, ..*cx };
|
|
let lc = LayerCtx { xf, ..*lc };
|
|
for m in members.layers.iter().rev().filter(|l| l.visible && l.kind != LayerKind::Guide).filter_map(|l| l.keyframe_at(0)).flat_map(|k| k.elements.iter()) {
|
|
eval_element(doc, &inner, &lc, m, out, play);
|
|
}
|
|
}
|
|
ElementKind::Symbol { symbol, loop_mode, first_frame, blend, filters, .. } => {
|
|
let Some(sym) = cx.work.symbol(doc, *symbol) else { return };
|
|
let len = sym.timeline.frame_count();
|
|
let local = match (sym.kind, &child) {
|
|
// A graphic keeps step with this timeline: loop mode and first frame apply.
|
|
(SymbolKind::Graphic, _) => loop_mode.local_frame(frame.saturating_sub(kf_start), *first_frame, len),
|
|
// In the player, movie clips and buttons are where it has them.
|
|
(SymbolKind::MovieClip, Some(c)) => c.state.clip_frame(&c.path, len),
|
|
(SymbolKind::Button, Some(c)) => c.state.button_frame(&c.path, len),
|
|
// A movie clip plays its own timeline on a loop from when the instance
|
|
// appeared, carrying on across keyframes that hold the same instance.
|
|
(SymbolKind::MovieClip, None) => frame.saturating_sub(instance_start(layer, frame, el.id, *symbol)) % len.max(1),
|
|
// While editing, a button shows its Up frame.
|
|
(SymbolKind::Button, None) => 0,
|
|
};
|
|
// An instance below full opacity fades as one: its contents composite in a
|
|
// group at full opacity, and the group blends at the instance's alpha. (Mask
|
|
// artwork ignores opacity, so it never needs one.)
|
|
// A blend mode composites the instance on its own too, then blends it.
|
|
// An alpha offset (Advanced) changes each item's alpha on its own: it stays
|
|
// in the items' transform, and the group (for a blend or filters) is opaque.
|
|
let fade = fx.alpha_factor().unwrap_or(1.0);
|
|
let (color, group) = if masks.is_none() && (fade < 1.0 - 1e-4 || !blend.is_normal() || crate::filter::any_active(filters)) {
|
|
let gid = out.groups.len() as u32;
|
|
out.groups.push(Group { parent: cx.group, alpha: fade, blend: *blend, filters: crate::filter::active(filters).into(), clip });
|
|
let inner = if fx.alpha_factor().is_some() { fx.without_alpha() } else { fx };
|
|
(cx.color.concat(&inner), Some(gid))
|
|
} else {
|
|
(color, cx.group)
|
|
};
|
|
// A symbol with 9-slice guides, scaled: its shapes are sliced (ADR 0055).
|
|
let slice = crate::nine_slice::slicing(doc, sym, &el.transform).map(|s| Slicing { post: layer_xf.mul(&s.post), ..s });
|
|
let inner = Ctx { work: cx.work, xf, color, depth: cx.depth + 1, root: Some((root_layer, root_el)), outline: layer_outline, stage: cx.stage, clip, masks, guide, group, camera: None, slice };
|
|
eval_timeline(doc, &sym.timeline, local, &inner, out, child.as_ref());
|
|
}
|
|
}
|
|
}
|
|
|
|
/// A text block's authored outline as items, one per colour piece (ADR 0085), recording the
|
|
/// links of pieces that have one.
|
|
fn text_fills(t: &crate::TextBlock, out: &mut DisplayList, item: impl Fn(Arc<Path>, Rgba) -> DisplayItem) {
|
|
for (color, url, path) in t.fill_paths() {
|
|
if !url.is_empty() {
|
|
out.links.push((out.items.len() as u32, Arc::from(url)));
|
|
}
|
|
out.items.push(item(path, color));
|
|
}
|
|
}
|
|
|
|
/// The highlight behind selected text in a focused field.
|
|
pub const SELECTION: Rgba = Rgba::new(0.62, 0.78, 1.0, 1.0);
|
|
|
|
/// A dynamic or input field's items (ADR 0066): its background, its text cut to its box, the
|
|
/// selection and caret when it has the keyboard, and its border. `live` is its state in the
|
|
/// player (and whether it is focused); without one, it shows its authored outline.
|
|
fn field_items(t: &crate::TextBlock, f: &crate::TextField, live: Option<(Option<&crate::field::FieldState>, bool)>, xf: Affine, clip: Option<u32>, out: &mut DisplayList, item: impl Fn(Arc<Path>, Affine, Option<Paint>, Option<Stroke>, Option<u32>, Option<u32>) -> DisplayItem) {
|
|
let (w, h) = (t.box_width.max(0.0), t.box_height.max(0.0));
|
|
let rect = Arc::new(Path::rect(0.0, 0.0, w, h));
|
|
if f.background {
|
|
out.items.push(item(rect.clone(), xf, Some(Paint::Solid(f.background_color)), None, clip, None));
|
|
}
|
|
// The box clips what is inside it.
|
|
let inner = out.clip_parents.len() as u32;
|
|
out.clip_parents.push(clip);
|
|
out.items.push(item(rect.clone(), xf, Some(Paint::Solid(Rgba::BLACK)), None, clip, Some(inner)));
|
|
let (state, focused) = live.unwrap_or((None, false));
|
|
let scroll = state.map_or(anicraft_geom::Vec2::ZERO, |s| s.scroll);
|
|
let text_xf = xf.mul(&Affine::translate(-scroll.x, -scroll.y));
|
|
let look = state.and_then(|s| s.look.as_deref());
|
|
// The selection, under the text.
|
|
if let (true, Some(st), Some(look)) = (focused, state, look) {
|
|
let (a, b) = st.selection();
|
|
if a != b {
|
|
for (row, l) in look.lines.iter().enumerate() {
|
|
let (from, to) = (a.max(l.start), b.min(l.end));
|
|
if from > to || (from == to && !(a <= l.end && b > l.end)) {
|
|
continue;
|
|
}
|
|
// One stretch per direction the selection runs through (ADR 0130).
|
|
let mut spans = l.spans(from, to);
|
|
if b > l.end {
|
|
// The line break is selected too: a little past where the line ends.
|
|
let (x, tail) = (l.x_at(l.end), t.size * 0.25);
|
|
match spans.last_mut() {
|
|
Some(last) if !l.rtl && (last.1 - x).abs() < 1e-3 => last.1 = x + tail,
|
|
_ if l.rtl => spans.push((x - tail, x)),
|
|
_ => spans.push((x, x + tail)),
|
|
}
|
|
}
|
|
let y = row as f32 * look.line_height;
|
|
for (x0, x1) in spans {
|
|
let r = Path::rect(crate::FIELD_GUTTER + x0, crate::FIELD_GUTTER + y, (x1 - x0).max(0.0), look.line_height);
|
|
out.items.push(item(Arc::new(r), text_xf, Some(Paint::Solid(SELECTION)), None, Some(inner), None));
|
|
}
|
|
}
|
|
}
|
|
}
|
|
// The text: laid out by the player when it changed, else the authored outline (a field whose
|
|
// text changed but couldn't be laid out shows none).
|
|
match (state.and_then(|s| s.text.as_ref()), look) {
|
|
(_, Some(l)) if !l.pieces.is_empty() => {
|
|
for (color, piece) in l.pieces.iter() {
|
|
out.items.push(item(piece.clone(), text_xf, Some(Paint::Solid(*color)), None, Some(inner), None));
|
|
}
|
|
}
|
|
(_, Some(l)) => out.items.push(item(l.outline.clone(), text_xf, Some(Paint::Solid(t.color)), None, Some(inner), None)),
|
|
(None, None) => text_fills(t, out, |path, color| item(path, text_xf, Some(Paint::Solid(color)), None, Some(inner), None)),
|
|
(Some(_), None) => {}
|
|
}
|
|
// The caret, in an input field with the keyboard and nothing selected.
|
|
if let (true, Some(st), crate::TextKind::Input) = (focused, state, f.kind)
|
|
&& st.caret == st.anchor
|
|
{
|
|
let (at, lh) = look.map_or((anicraft_geom::Vec2::ZERO, t.size * 1.2), |l| (l.caret_at(st.caret), l.line_height));
|
|
let r = Path::rect(crate::FIELD_GUTTER + at.x - 0.5, crate::FIELD_GUTTER + at.y, 1.0, lh);
|
|
out.items.push(item(Arc::new(r), text_xf, Some(Paint::Solid(t.color)), None, Some(inner), None));
|
|
}
|
|
if f.border {
|
|
let mut s = Stroke::new(f.border_color, 1.0);
|
|
s.style.join = crate::Join::Miter;
|
|
out.items.push(item(rect, xf, None, Some(s), clip, None));
|
|
}
|
|
}
|
|
|
|
/// A shape inside a 9-slice instance (ADR 0055): its outline placed by its own transform, then
|
|
/// cut at the guides and mapped piecewise; drawn by the instance's transform without its scale.
|
|
/// The stroke keeps its width (times the shape's own scale inside the symbol); gradients follow
|
|
/// the map, their size the shape's own scale times the instance's.
|
|
fn sliced_shape(s: &Shape, own: &Affine, sl: &Slicing) -> (Arc<Path>, Affine, Option<Paint>, Option<Stroke>) {
|
|
let path = Arc::new(anicraft_geom::slice::slice_path(&s.path, own, &sl.map));
|
|
let k = own.mean_scale();
|
|
let stroke = s.stroke.as_ref().map(|st| if (k - 1.0).abs() > 1e-6 { st.scaled(k) } else { st.clone() });
|
|
let at = |p: anicraft_geom::Vec2| sl.map.map(own.apply(p));
|
|
let size = k * sl.scale.mean_scale();
|
|
let fill = s.fill.as_ref().map(|f| {
|
|
let mut f = f.clone();
|
|
match &mut f {
|
|
Paint::Linear { start, end, .. } => {
|
|
*start = at(*start);
|
|
*end = at(*end);
|
|
}
|
|
Paint::Radial { center, radius, matrix, .. } => {
|
|
// The ring's shape (its matrix's linear part) stays, round the mapped centre.
|
|
let c = at(matrix.apply(*center));
|
|
let l = Affine { m: [matrix.m[0], matrix.m[1], matrix.m[2], matrix.m[3], 0.0, 0.0] };
|
|
if *matrix != Affine::IDENTITY {
|
|
*matrix = Affine::translate(c.x, c.y).mul(&l).mul(&Affine::translate(-c.x, -c.y));
|
|
}
|
|
*center = c;
|
|
*radius *= size;
|
|
}
|
|
Paint::Solid(_) | Paint::Bitmap { .. } => {}
|
|
}
|
|
f
|
|
});
|
|
(path, sl.post, fill, stroke)
|
|
}
|
|
|
|
#[cfg(test)]
|
|
#[path = "eval_tests.rs"]
|
|
pub(crate) mod tests;
|
|
|
|
#[cfg(test)]
|
|
#[path = "pivot_tests.rs"]
|
|
mod pivot_tests;
|