Skip to main content

alpha2_model/
shapes.rs

1//! The content tree of a shapes generator: geometry, paints and modifiers in the order an
2//! After Effects or Lottie shape layer lists them.
3//!
4//! Positions and sizes are normalized to the generator's picture, `(0, 0)` top-left to
5//! `(1, 1)` bottom-right; lengths (radii, stroke widths, dashes) are fractions of the
6//! picture's shorter side. Rotation and scale act in pixel space, so a rotated square stays
7//! square on a wide canvas.
8
9use crate::animation::{opaque, unit_scale, valid_keyframes, visit_keyed, visit_keyed_point};
10use crate::checks::{
11    ValueIssue, ValueProblem, any, non_negative, point, scalar, unit, validate_paint, vec2,
12};
13use crate::{Animated, AnimatedPoint, Paint, Vec2};
14use serde::{Deserialize, Serialize};
15use std::fmt;
16
17/// Most items one shapes generator holds, including nested groups and their items.
18pub const MAX_SHAPE_ITEMS: usize = 1_024;
19/// Deepest group nesting in one shapes generator.
20pub const MAX_SHAPE_DEPTH: usize = 32;
21/// Most vertices one path holds, over all its subpaths.
22pub const MAX_PATH_VERTICES: usize = 4_096;
23/// Most subpaths one path holds.
24pub const MAX_PATH_SUBPATHS: usize = 256;
25/// Most entries in a stroke's dash pattern.
26pub const MAX_DASH_ENTRIES: usize = 16;
27/// Most points a polystar has. A fractional count is valid; the fraction is dropped when
28/// drawn.
29pub const MAX_POLYSTAR_POINTS: f32 = 100.0;
30/// Fewest points a polystar has.
31pub const MIN_POLYSTAR_POINTS: f32 = 3.0;
32
33/// One entry of a shapes generator's content tree.
34///
35/// A group is read front to back. Geometry accumulates in its group; a fill or stroke paints
36/// the geometry listed before it in the same group (nested groups included), and a trim cuts
37/// and replaces that geometry. Earlier paints draw on top of later ones, as in After Effects
38/// and Lottie.
39#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
40#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
41#[serde(tag = "type", rename_all = "snake_case", deny_unknown_fields)]
42pub enum ShapeItem {
43    /// Items drawn together through one transform and opacity. Their geometry also counts as the
44    /// enclosing group's for paints and trims after the group.
45    Group {
46        /// The group's items, front first.
47        #[serde(deserialize_with = "crate::bounded::seq::<_, _, { crate::MAX_SHAPE_ITEMS }>")]
48        #[cfg_attr(feature = "schema", schemars(length(max = crate::MAX_SHAPE_ITEMS)))]
49        items: Vec<ShapeItem>,
50        /// Where the group lies, and how opaque it is.
51        #[serde(default)]
52        transform: ShapeTransform,
53    },
54    /// A rectangle, optionally with rounded corners.
55    Rectangle(RectangleGeometry),
56    /// An ellipse.
57    Ellipse(EllipseGeometry),
58    /// A regular polygon or star.
59    Polystar(PolystarGeometry),
60    /// A Bezier path.
61    Path(PathGeometry),
62    /// Paints the inside of the geometry listed before it in its group, as one compound path
63    /// under `rule`. Open paths are closed for it.
64    Fill {
65        /// What covers it.
66        paint: Animated<Paint>,
67        /// Opacity in `0..=1`.
68        #[serde(default = "opaque")]
69        opacity: Animated<f32>,
70        /// Which regions of the compound path are inside.
71        #[serde(default)]
72        rule: FillRule,
73    },
74    /// Strokes the geometry listed before it in its group.
75    Stroke(StrokeItem),
76    /// Keeps part of the geometry listed before it in its group, by length.
77    Trim(TrimItem),
78}
79
80fn zero() -> Animated<f32> {
81    Animated::Constant { value: 0.0 }
82}
83
84/// A geometry alone, as a mask's outline is.
85#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
86#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
87#[serde(tag = "type", rename_all = "snake_case", deny_unknown_fields)]
88pub enum ShapeGeometry {
89    /// A rectangle, optionally with rounded corners.
90    Rectangle(RectangleGeometry),
91    /// An ellipse.
92    Ellipse(EllipseGeometry),
93    /// A regular polygon or star.
94    Polystar(PolystarGeometry),
95    /// A Bezier path.
96    Path(PathGeometry),
97}
98
99/// A rectangle about its centre, turned clockwise about it. Its outline starts at the
100/// top-right corner and runs clockwise.
101#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
102#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
103#[serde(deny_unknown_fields)]
104pub struct RectangleGeometry {
105    /// Centre.
106    pub center: AnimatedPoint,
107    /// Full width and height before rotation: x a fraction of the picture's width, y of its
108    /// height. Non-negative.
109    pub size: Animated<Vec2>,
110    /// Corner radius, as a fraction of the shorter side. Non-negative; capped at half the
111    /// rectangle.
112    #[serde(default = "zero")]
113    pub corner_radius: Animated<f32>,
114    /// Clockwise rotation about the centre, in degrees.
115    #[serde(default = "zero")]
116    pub rotation_degrees: Animated<f32>,
117}
118
119/// The ellipse inscribed in a size, turned clockwise about its centre. Its outline starts at
120/// the top and runs clockwise.
121#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
122#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
123#[serde(deny_unknown_fields)]
124pub struct EllipseGeometry {
125    /// Centre.
126    pub center: AnimatedPoint,
127    /// Full width and height before rotation: x a fraction of the picture's width, y of its
128    /// height. Non-negative.
129    pub size: Animated<Vec2>,
130    /// Clockwise rotation about the centre, in degrees.
131    #[serde(default = "zero")]
132    pub rotation_degrees: Animated<f32>,
133}
134
135/// A regular polygon or star, its first point straight up from the centre before rotation,
136/// the rest clockwise.
137#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
138#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
139#[serde(deny_unknown_fields)]
140pub struct PolystarGeometry {
141    /// A polygon or a star.
142    pub kind: PolystarKind,
143    /// Centre.
144    pub center: AnimatedPoint,
145    /// Number of points (polygon corners or star tips), from [`MIN_POLYSTAR_POINTS`] to
146    /// [`MAX_POLYSTAR_POINTS`]. A fraction is dropped when drawn, as Lottie does, so an animated
147    /// count changes one whole point at a time.
148    pub points: Animated<f32>,
149    /// Distance of the points from the centre, as a fraction of the shorter side. Non-negative.
150    pub outer_radius: Animated<f32>,
151    /// A star's distance of its inner corners from the centre. Non-negative.
152    #[serde(default = "zero")]
153    pub inner_radius: Animated<f32>,
154    /// How round the outer corners are, in `0..=1`: 0 sharp, 1 a smooth curve through them.
155    #[serde(default = "zero")]
156    pub outer_roundness: Animated<f32>,
157    /// How round a star's inner corners are, in `0..=1`.
158    #[serde(default = "zero")]
159    pub inner_roundness: Animated<f32>,
160    /// Clockwise rotation about the centre, in degrees.
161    #[serde(default = "zero")]
162    pub rotation_degrees: Animated<f32>,
163}
164
165/// What kind of figure a polystar is.
166#[derive(Copy, Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
167#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
168#[serde(rename_all = "snake_case")]
169pub enum PolystarKind {
170    /// Points joined by inner corners.
171    #[default]
172    Star,
173    /// Points joined by straight sides.
174    Polygon,
175}
176
177/// A path, animated as one value.
178///
179/// Keyframes must agree in structure: the same subpath count, each closed or open alike with
180/// the same vertex count. Between keyframes every point and tangent moves linearly.
181#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
182#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
183#[serde(deny_unknown_fields)]
184pub struct PathGeometry {
185    /// The path.
186    pub path: Animated<Path>,
187}
188
189/// One or more subpaths.
190#[derive(Clone, Debug, Default, Deserialize, PartialEq, Serialize)]
191#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
192#[serde(deny_unknown_fields)]
193pub struct Path {
194    /// The subpaths, at most [`MAX_PATH_SUBPATHS`], with at most [`MAX_PATH_VERTICES`] vertices
195    /// in total.
196    #[serde(deserialize_with = "crate::bounded::seq::<_, _, { crate::MAX_PATH_SUBPATHS }>")]
197    #[cfg_attr(feature = "schema", schemars(length(max = crate::MAX_PATH_SUBPATHS)))]
198    pub subpaths: Vec<Subpath>,
199}
200
201/// A run of vertices joined by cubic Bezier segments.
202#[derive(Clone, Debug, Default, Deserialize, PartialEq, Serialize)]
203#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
204#[serde(deny_unknown_fields)]
205pub struct Subpath {
206    /// Whether a segment joins the last vertex back to the first.
207    #[serde(default)]
208    pub closed: bool,
209    /// The vertices, in order.
210    #[serde(deserialize_with = "crate::bounded::seq::<_, _, { crate::MAX_PATH_VERTICES }>")]
211    #[cfg_attr(feature = "schema", schemars(length(max = crate::MAX_PATH_VERTICES)))]
212    pub vertices: Vec<PathVertex>,
213}
214
215/// A path vertex and its tangents. The segment from `a` to `b` is the cubic Bezier through
216/// `a.point`, `a.point + a.out_tangent`, `b.point + b.in_tangent` and `b.point`; zero tangents
217/// make it straight.
218#[derive(Copy, Clone, Debug, Default, Deserialize, PartialEq, Serialize)]
219#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
220#[serde(deny_unknown_fields)]
221pub struct PathVertex {
222    /// Where the vertex lies.
223    pub point: Vec2,
224    /// The control point of the segment ending here, relative to `point`.
225    #[serde(default)]
226    pub in_tangent: Vec2,
227    /// The control point of the segment starting here, relative to `point`.
228    #[serde(default)]
229    pub out_tangent: Vec2,
230}
231
232/// A group's placement. In pixel space: translate by `position`, rotate, scale, then
233/// translate by minus `anchor`, so `anchor` lands on `position`. The default is identity.
234#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
235#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
236#[serde(deny_unknown_fields)]
237pub struct ShapeTransform {
238    /// The point of the items that is placed at `position`.
239    #[serde(default = "origin")]
240    pub anchor: Animated<Vec2>,
241    /// Where `anchor` is placed.
242    #[serde(default)]
243    pub position: AnimatedPoint,
244    /// Per-axis scale; 1 leaves the items unscaled. Stroke widths scale with it.
245    #[serde(default = "unit_scale")]
246    pub scale: Animated<Vec2>,
247    /// Clockwise rotation, in degrees.
248    #[serde(default = "zero")]
249    pub rotation_degrees: Animated<f32>,
250    /// Opacity of the group as a whole, in `0..=1`; overlapping items are composited first and
251    /// faded together.
252    #[serde(default = "opaque")]
253    pub opacity: Animated<f32>,
254}
255
256fn origin() -> Animated<Vec2> {
257    Animated::Constant {
258        value: Vec2::new(0.0, 0.0),
259    }
260}
261
262impl Default for ShapeTransform {
263    fn default() -> Self {
264        Self {
265            anchor: origin(),
266            position: AnimatedPoint::default(),
267            scale: unit_scale(),
268            rotation_degrees: zero(),
269            opacity: opaque(),
270        }
271    }
272}
273
274/// A stroke along geometry, centred on its outline.
275#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
276#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
277#[serde(deny_unknown_fields)]
278pub struct StrokeItem {
279    /// What covers the stroke.
280    pub paint: Animated<Paint>,
281    /// Full width, as a fraction of the shorter side. Non-negative; zero draws nothing.
282    pub width: Animated<f32>,
283    /// Opacity in `0..=1`.
284    #[serde(default = "opaque")]
285    pub opacity: Animated<f32>,
286    /// How segments meet.
287    #[serde(default)]
288    pub join: LineJoin,
289    /// Longest a miter join reaches, as a multiple of half the width, before it is beveled. At
290    /// least 1.
291    #[serde(default = "four")]
292    pub miter_limit: f32,
293    /// How open ends look.
294    #[serde(default)]
295    pub cap: LineCap,
296    /// Dashes, or a solid stroke when absent.
297    #[serde(default)]
298    pub dash: Option<Dash>,
299}
300
301const fn four() -> f32 {
302    4.0
303}
304
305/// How stroke segments meet at a vertex.
306#[derive(Copy, Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
307#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
308#[serde(rename_all = "snake_case")]
309pub enum LineJoin {
310    /// Extended edges meeting at a point, up to the miter limit.
311    #[default]
312    Miter,
313    /// A circular arc.
314    Round,
315    /// A straight cut across the corner.
316    Bevel,
317}
318
319/// How an open stroke ends.
320#[derive(Copy, Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
321#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
322#[serde(rename_all = "snake_case")]
323pub enum LineCap {
324    /// Flat at the end point.
325    #[default]
326    Butt,
327    /// A half circle past the end point.
328    Round,
329    /// A half square past the end point.
330    Square,
331}
332
333/// A dash pattern.
334#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
335#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
336#[serde(deny_unknown_fields)]
337pub struct Dash {
338    /// Alternating dash and gap lengths, as fractions of the shorter side: one to
339    /// [`MAX_DASH_ENTRIES`] non-negative entries, not all zero. An odd count repeats once more to
340    /// pair up.
341    #[serde(deserialize_with = "crate::bounded::seq::<_, _, { crate::MAX_DASH_ENTRIES }>")]
342    #[cfg_attr(feature = "schema", schemars(length(max = crate::MAX_DASH_ENTRIES)))]
343    pub pattern: Vec<Animated<f32>>,
344    /// How far into the pattern the stroke starts.
345    #[serde(default = "zero")]
346    pub offset: Animated<f32>,
347}
348
349/// Keeps a span of geometry's length.
350#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
351#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
352#[serde(deny_unknown_fields)]
353pub struct TrimItem {
354    /// Where the kept span starts, as a fraction of the length, in `0..=1`.
355    pub start: Animated<f32>,
356    /// Where it ends, in `0..=1`. Nothing is kept unless it is after `start`.
357    pub end: Animated<f32>,
358    /// Turns the span is shifted by; it wraps around a closed path.
359    #[serde(default = "zero")]
360    pub offset: Animated<f32>,
361    /// Whether the span is of all the geometry together or of each part.
362    #[serde(default)]
363    pub mode: TrimMode,
364}
365
366/// What a trim measures.
367#[derive(Copy, Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
368#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
369#[serde(rename_all = "snake_case")]
370pub enum TrimMode {
371    /// One span over the length of every subpath end to end, in order.
372    #[default]
373    Together,
374    /// A span of each subpath alone.
375    Individually,
376}
377
378/// Which regions of a path are inside it.
379#[derive(Copy, Clone, Debug, Default, Deserialize, Eq, Hash, PartialEq, Serialize)]
380#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
381#[serde(rename_all = "snake_case")]
382pub enum FillRule {
383    /// Where the outline winds around a point at all.
384    #[default]
385    Nonzero,
386    /// Where it winds around a point an odd number of times.
387    Evenodd,
388}
389
390/// Why a content tree or a mask outline is invalid.
391#[derive(Copy, Clone, Debug, Eq, PartialEq)]
392#[non_exhaustive]
393pub enum ShapeProblem {
394    /// More than [`MAX_SHAPE_ITEMS`] items.
395    TooManyItems,
396    /// Groups nested deeper than [`MAX_SHAPE_DEPTH`].
397    TooDeep,
398    /// A path with more than [`MAX_PATH_SUBPATHS`] subpaths or [`MAX_PATH_VERTICES`] vertices.
399    PathTooLarge,
400    /// A dash pattern with no entries, more than [`MAX_DASH_ENTRIES`], or only zeros.
401    InvalidDash,
402    /// Keyframes that are empty, out of order, or have an unusable curve.
403    InvalidKeyframes,
404    /// A value that is not finite or outside its range.
405    OutOfRange,
406    /// Path keyframes that differ in subpath count, closing, or vertex count.
407    PathKeyframesDiffer,
408    /// Paint keyframes that differ in kind, stop count, or spread.
409    PaintKeyframesDiffer,
410}
411
412impl fmt::Display for ShapeProblem {
413    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
414        formatter.write_str(match self {
415            Self::TooManyItems => "has more items than a shapes generator may hold",
416            Self::TooDeep => "nests groups too deeply",
417            Self::PathTooLarge => "has more subpaths or vertices than a path may hold",
418            Self::InvalidDash => "has an invalid dash pattern",
419            Self::InvalidKeyframes => "has invalid keyframes",
420            Self::OutOfRange => "has a value out of range",
421            Self::PathKeyframesDiffer => "has path keyframes that differ in structure",
422            Self::PaintKeyframesDiffer => "has paint keyframes that differ in kind or stops",
423        })
424    }
425}
426
427/// Where in a content tree a problem lies, and what it is.
428#[derive(Clone, Debug, Eq, PartialEq)]
429pub struct ShapeIssue {
430    /// The item's path from the tree's root, like `items[2].items[0].path`, or a mask's field,
431    /// like `shape.size`.
432    pub at: String,
433    /// What is wrong there.
434    pub problem: ShapeProblem,
435}
436
437impl From<ValueIssue> for ShapeIssue {
438    fn from(issue: ValueIssue) -> Self {
439        Self::new(
440            issue.at,
441            match issue.problem {
442                ValueProblem::InvalidKeyframes => ShapeProblem::InvalidKeyframes,
443                ValueProblem::OutOfRange => ShapeProblem::OutOfRange,
444                ValueProblem::PaintKeyframesDiffer => ShapeProblem::PaintKeyframesDiffer,
445            },
446        )
447    }
448}
449
450impl ShapeIssue {
451    fn new(at: impl Into<String>, problem: ShapeProblem) -> Self {
452        Self {
453            at: at.into(),
454            problem,
455        }
456    }
457}
458
459type Checked = Result<(), ShapeIssue>;
460
461/// Checks a content tree: its limits, every value's range, and that animated paths and paints
462/// agree in structure between keyframes.
463///
464/// # Errors
465/// Returns the first problem in document order.
466pub fn validate_shape_items(items: &[ShapeItem]) -> Result<(), ShapeIssue> {
467    let mut count = 0;
468    validate_items(items, "items", 1, &mut count)
469}
470
471pub(crate) fn validate_items(
472    items: &[ShapeItem],
473    at: &str,
474    depth: usize,
475    count: &mut usize,
476) -> Checked {
477    if depth > MAX_SHAPE_DEPTH {
478        return Err(ShapeIssue::new(at, ShapeProblem::TooDeep));
479    }
480    for (index, item) in items.iter().enumerate() {
481        let at = format!("{at}[{index}]");
482        *count += 1;
483        if *count > MAX_SHAPE_ITEMS {
484            return Err(ShapeIssue::new(at, ShapeProblem::TooManyItems));
485        }
486        match item {
487            ShapeItem::Group { items, transform } => {
488                validate_transform(transform, &format!("{at}.transform"))?;
489                validate_items(items, &format!("{at}.items"), depth + 1, count)?;
490            }
491            ShapeItem::Rectangle(geometry) => validate_rectangle(geometry, &at)?,
492            ShapeItem::Ellipse(geometry) => validate_ellipse(geometry, &at)?,
493            ShapeItem::Polystar(geometry) => validate_polystar(geometry, &at)?,
494            ShapeItem::Path(geometry) => validate_path(&geometry.path, &format!("{at}.path"))?,
495            ShapeItem::Fill { paint, opacity, .. } => {
496                validate_paint(paint, &format!("{at}.paint"))?;
497                scalar(opacity, &format!("{at}.opacity"), unit)?;
498            }
499            ShapeItem::Stroke(stroke) => validate_stroke(stroke, &at)?,
500            ShapeItem::Trim(trim) => {
501                scalar(&trim.start, &format!("{at}.start"), unit)?;
502                scalar(&trim.end, &format!("{at}.end"), unit)?;
503                scalar(&trim.offset, &format!("{at}.offset"), any)?;
504            }
505        }
506    }
507    Ok(())
508}
509
510impl ShapeGeometry {
511    /// Checks the outline as a content tree's geometry is checked; `at` names it in the issue.
512    ///
513    /// # Errors
514    /// Returns the first problem in document order.
515    pub fn validate(&self, at: &str) -> Result<(), ShapeIssue> {
516        match self {
517            Self::Rectangle(geometry) => validate_rectangle(geometry, at),
518            Self::Ellipse(geometry) => validate_ellipse(geometry, at),
519            Self::Polystar(geometry) => validate_polystar(geometry, at),
520            Self::Path(geometry) => validate_path(&geometry.path, &format!("{at}.path")),
521        }
522    }
523}
524
525fn sizes(value: Vec2) -> bool {
526    value.x >= 0.0 && value.y >= 0.0
527}
528
529fn validate_rectangle(geometry: &RectangleGeometry, at: &str) -> Checked {
530    point(&geometry.center, &format!("{at}.center"))?;
531    vec2(&geometry.size, &format!("{at}.size"), sizes)?;
532    scalar(
533        &geometry.corner_radius,
534        &format!("{at}.corner_radius"),
535        non_negative,
536    )?;
537    scalar(
538        &geometry.rotation_degrees,
539        &format!("{at}.rotation_degrees"),
540        any,
541    )?;
542    Ok(())
543}
544
545fn validate_ellipse(geometry: &EllipseGeometry, at: &str) -> Checked {
546    point(&geometry.center, &format!("{at}.center"))?;
547    vec2(&geometry.size, &format!("{at}.size"), sizes)?;
548    scalar(
549        &geometry.rotation_degrees,
550        &format!("{at}.rotation_degrees"),
551        any,
552    )?;
553    Ok(())
554}
555
556fn validate_polystar(geometry: &PolystarGeometry, at: &str) -> Checked {
557    point(&geometry.center, &format!("{at}.center"))?;
558    scalar(&geometry.points, &format!("{at}.points"), |points| {
559        crate::Domain::POLYSTAR_POINTS.contains(points)
560    })?;
561    scalar(
562        &geometry.outer_radius,
563        &format!("{at}.outer_radius"),
564        non_negative,
565    )?;
566    scalar(
567        &geometry.inner_radius,
568        &format!("{at}.inner_radius"),
569        non_negative,
570    )?;
571    scalar(
572        &geometry.outer_roundness,
573        &format!("{at}.outer_roundness"),
574        unit,
575    )?;
576    scalar(
577        &geometry.inner_roundness,
578        &format!("{at}.inner_roundness"),
579        unit,
580    )?;
581    scalar(
582        &geometry.rotation_degrees,
583        &format!("{at}.rotation_degrees"),
584        any,
585    )?;
586    Ok(())
587}
588
589fn validate_transform(transform: &ShapeTransform, at: &str) -> Checked {
590    vec2(&transform.anchor, &format!("{at}.anchor"), |_| true)?;
591    point(&transform.position, &format!("{at}.position"))?;
592    vec2(&transform.scale, &format!("{at}.scale"), |_| true)?;
593    scalar(
594        &transform.rotation_degrees,
595        &format!("{at}.rotation_degrees"),
596        any,
597    )?;
598    scalar(&transform.opacity, &format!("{at}.opacity"), unit)?;
599    Ok(())
600}
601
602fn validate_stroke(stroke: &StrokeItem, at: &str) -> Checked {
603    validate_paint(&stroke.paint, &format!("{at}.paint"))?;
604    scalar(&stroke.width, &format!("{at}.width"), non_negative)?;
605    scalar(&stroke.opacity, &format!("{at}.opacity"), unit)?;
606    if !stroke.miter_limit.is_finite() || stroke.miter_limit < 1.0 {
607        return Err(ShapeIssue::new(
608            format!("{at}.miter_limit"),
609            ShapeProblem::OutOfRange,
610        ));
611    }
612    if let Some(dash) = &stroke.dash {
613        let at = format!("{at}.dash");
614        if dash.pattern.is_empty() || dash.pattern.len() > MAX_DASH_ENTRIES {
615            return Err(ShapeIssue::new(
616                format!("{at}.pattern"),
617                ShapeProblem::InvalidDash,
618            ));
619        }
620        for (index, entry) in dash.pattern.iter().enumerate() {
621            scalar(entry, &format!("{at}.pattern[{index}]"), non_negative)?;
622        }
623        // A pattern of only zeros has no length to repeat over. Animated entries need some positive
624        // keyframe.
625        let positive = dash.pattern.iter().any(|entry| match entry {
626            Animated::Constant { value } => *value > 0.0,
627            Animated::Keyframes { keyframes, .. } => keyframes.iter().any(|key| key.value > 0.0),
628            Animated::Split { .. } => false,
629            Animated::Data(_) => true,
630        });
631        if !positive {
632            return Err(ShapeIssue::new(
633                format!("{at}.pattern"),
634                ShapeProblem::InvalidDash,
635            ));
636        }
637        scalar(&dash.offset, &format!("{at}.offset"), any)?;
638    }
639    Ok(())
640}
641
642fn validate_path(path: &Animated<Path>, at: &str) -> Checked {
643    let check_one = |path: &Path| -> Checked {
644        let vertices: usize = path
645            .subpaths
646            .iter()
647            .map(|subpath| subpath.vertices.len())
648            .sum();
649        if path.subpaths.len() > MAX_PATH_SUBPATHS || vertices > MAX_PATH_VERTICES {
650            return Err(ShapeIssue::new(at, ShapeProblem::PathTooLarge));
651        }
652        let finite = |value: Vec2| value.x.is_finite() && value.y.is_finite();
653        let all_finite = path.subpaths.iter().all(|subpath| {
654            subpath.vertices.iter().all(|vertex| {
655                finite(vertex.point) && finite(vertex.in_tangent) && finite(vertex.out_tangent)
656            })
657        });
658        all_finite
659            .then_some(())
660            .ok_or_else(|| ShapeIssue::new(at, ShapeProblem::OutOfRange))
661    };
662    match path {
663        Animated::Data(_) | Animated::Split { .. } => {
664            Err(ShapeIssue::new(at, ShapeProblem::OutOfRange))
665        }
666        Animated::Constant { value } => check_one(value),
667        Animated::Keyframes {
668            keyframes,
669            before,
670            after,
671        } => {
672            if !valid_keyframes(keyframes, *before, *after) {
673                return Err(ShapeIssue::new(at, ShapeProblem::InvalidKeyframes));
674            }
675            for keyframe in keyframes {
676                check_one(&keyframe.value)?;
677            }
678            let structure = |path: &Path| {
679                path.subpaths
680                    .iter()
681                    .map(|subpath| (subpath.closed, subpath.vertices.len()))
682                    .collect::<Vec<_>>()
683            };
684            let first = structure(&keyframes[0].value);
685            if keyframes[1..]
686                .iter()
687                .any(|keyframe| structure(&keyframe.value) != first)
688            {
689                return Err(ShapeIssue::new(at, ShapeProblem::PathKeyframesDiffer));
690            }
691            Ok(())
692        }
693    }
694}
695
696impl Path {
697    /// Number of vertices over all subpaths.
698    #[must_use]
699    pub fn vertex_count(&self) -> usize {
700        self.subpaths
701            .iter()
702            .map(|subpath| subpath.vertices.len())
703            .sum()
704    }
705}
706
707impl ShapeItem {
708    /// Whether the item or anything in it changes over time.
709    #[must_use]
710    pub fn is_animated(&self) -> bool {
711        match self {
712            Self::Group { items, transform } => {
713                transform.is_animated() || items.iter().any(Self::is_animated)
714            }
715            Self::Rectangle(geometry) => geometry.is_animated(),
716            Self::Ellipse(geometry) => geometry.is_animated(),
717            Self::Polystar(geometry) => geometry.is_animated(),
718            Self::Path(geometry) => keyed(&geometry.path),
719            Self::Fill { paint, opacity, .. } => keyed(paint) || keyed(opacity),
720            Self::Stroke(stroke) => {
721                keyed(&stroke.paint)
722                    || keyed(&stroke.width)
723                    || keyed(&stroke.opacity)
724                    || stroke
725                        .dash
726                        .as_ref()
727                        .is_some_and(|dash| dash.pattern.iter().any(keyed) || keyed(&dash.offset))
728            }
729            Self::Trim(trim) => keyed(&trim.start) || keyed(&trim.end) || keyed(&trim.offset),
730        }
731    }
732}
733
734/// Calls `visit` with each keyframed value of `items`, by its path below `at`
735/// (`items[0].transform.opacity` for `at` "items"), and its keyframe times, in document order.
736pub(crate) fn for_each_keyed_item(
737    items: &[ShapeItem],
738    at: &str,
739    visit: &mut impl FnMut(&str, crate::animation::Keyed<'_>),
740) {
741    for (index, item) in items.iter().enumerate() {
742        item.for_each_keyed(&format!("{at}[{index}]"), visit);
743    }
744}
745
746impl ShapeItem {
747    /// Calls `visit` with each of its keyframed values, by path below `at`, and their times.
748    pub(crate) fn for_each_keyed(
749        &self,
750        at: &str,
751        visit: &mut impl FnMut(&str, crate::animation::Keyed<'_>),
752    ) {
753        match self {
754            Self::Group { items, transform } => {
755                let transform_at = format!("{at}.transform");
756                visit_keyed(&format!("{transform_at}.anchor"), &transform.anchor, visit);
757                visit_keyed_point(
758                    &format!("{transform_at}.position"),
759                    &transform.position,
760                    visit,
761                );
762                visit_keyed(&format!("{transform_at}.scale"), &transform.scale, visit);
763                visit_keyed(
764                    &format!("{transform_at}.rotation_degrees"),
765                    &transform.rotation_degrees,
766                    visit,
767                );
768                visit_keyed(
769                    &format!("{transform_at}.opacity"),
770                    &transform.opacity,
771                    visit,
772                );
773                for_each_keyed_item(items, &format!("{at}.items"), visit);
774            }
775            Self::Rectangle(geometry) => geometry.for_each_keyed(at, visit),
776            Self::Ellipse(geometry) => geometry.for_each_keyed(at, visit),
777            Self::Polystar(geometry) => geometry.for_each_keyed(at, visit),
778            Self::Path(geometry) => visit_keyed(&format!("{at}.path"), &geometry.path, visit),
779            Self::Fill { paint, opacity, .. } => {
780                visit_keyed(&format!("{at}.paint"), paint, visit);
781                visit_keyed(&format!("{at}.opacity"), opacity, visit);
782            }
783            Self::Stroke(stroke) => {
784                visit_keyed(&format!("{at}.paint"), &stroke.paint, visit);
785                visit_keyed(&format!("{at}.width"), &stroke.width, visit);
786                visit_keyed(&format!("{at}.opacity"), &stroke.opacity, visit);
787                if let Some(dash) = &stroke.dash {
788                    for (index, entry) in dash.pattern.iter().enumerate() {
789                        visit_keyed(&format!("{at}.dash.pattern[{index}]"), entry, visit);
790                    }
791                    visit_keyed(&format!("{at}.dash.offset"), &dash.offset, visit);
792                }
793            }
794            Self::Trim(trim) => {
795                visit_keyed(&format!("{at}.start"), &trim.start, visit);
796                visit_keyed(&format!("{at}.end"), &trim.end, visit);
797                visit_keyed(&format!("{at}.offset"), &trim.offset, visit);
798            }
799        }
800    }
801}
802
803impl ShapeGeometry {
804    /// Calls `visit` with each of its keyframed values, by path below `at`, and their times.
805    pub(crate) fn for_each_keyed(
806        &self,
807        at: &str,
808        visit: &mut impl FnMut(&str, crate::animation::Keyed<'_>),
809    ) {
810        match self {
811            Self::Rectangle(geometry) => geometry.for_each_keyed(at, visit),
812            Self::Ellipse(geometry) => geometry.for_each_keyed(at, visit),
813            Self::Polystar(geometry) => geometry.for_each_keyed(at, visit),
814            Self::Path(geometry) => visit_keyed(&format!("{at}.path"), &geometry.path, visit),
815        }
816    }
817
818    /// Whether the outline changes over time.
819    #[must_use]
820    pub fn is_animated(&self) -> bool {
821        match self {
822            Self::Rectangle(geometry) => geometry.is_animated(),
823            Self::Ellipse(geometry) => geometry.is_animated(),
824            Self::Polystar(geometry) => geometry.is_animated(),
825            Self::Path(geometry) => keyed(&geometry.path),
826        }
827    }
828}
829
830impl RectangleGeometry {
831    fn is_animated(&self) -> bool {
832        self.center.is_animated()
833            || keyed(&self.size)
834            || keyed(&self.corner_radius)
835            || keyed(&self.rotation_degrees)
836    }
837}
838
839impl EllipseGeometry {
840    fn is_animated(&self) -> bool {
841        self.center.is_animated() || keyed(&self.size) || keyed(&self.rotation_degrees)
842    }
843}
844
845impl RectangleGeometry {
846    fn for_each_keyed(&self, at: &str, visit: &mut impl FnMut(&str, crate::animation::Keyed<'_>)) {
847        visit_keyed_point(&format!("{at}.center"), &self.center, visit);
848        visit_keyed(&format!("{at}.size"), &self.size, visit);
849        visit_keyed(&format!("{at}.corner_radius"), &self.corner_radius, visit);
850        visit_keyed(
851            &format!("{at}.rotation_degrees"),
852            &self.rotation_degrees,
853            visit,
854        );
855    }
856}
857
858impl EllipseGeometry {
859    fn for_each_keyed(&self, at: &str, visit: &mut impl FnMut(&str, crate::animation::Keyed<'_>)) {
860        visit_keyed_point(&format!("{at}.center"), &self.center, visit);
861        visit_keyed(&format!("{at}.size"), &self.size, visit);
862        visit_keyed(
863            &format!("{at}.rotation_degrees"),
864            &self.rotation_degrees,
865            visit,
866        );
867    }
868}
869
870impl PolystarGeometry {
871    fn for_each_keyed(&self, at: &str, visit: &mut impl FnMut(&str, crate::animation::Keyed<'_>)) {
872        visit_keyed_point(&format!("{at}.center"), &self.center, visit);
873        visit_keyed(&format!("{at}.points"), &self.points, visit);
874        visit_keyed(&format!("{at}.outer_radius"), &self.outer_radius, visit);
875        visit_keyed(&format!("{at}.inner_radius"), &self.inner_radius, visit);
876        visit_keyed(
877            &format!("{at}.outer_roundness"),
878            &self.outer_roundness,
879            visit,
880        );
881        visit_keyed(
882            &format!("{at}.inner_roundness"),
883            &self.inner_roundness,
884            visit,
885        );
886        visit_keyed(
887            &format!("{at}.rotation_degrees"),
888            &self.rotation_degrees,
889            visit,
890        );
891    }
892
893    fn is_animated(&self) -> bool {
894        self.center.is_animated()
895            || keyed(&self.points)
896            || keyed(&self.outer_radius)
897            || keyed(&self.inner_radius)
898            || keyed(&self.outer_roundness)
899            || keyed(&self.inner_roundness)
900            || keyed(&self.rotation_degrees)
901    }
902}
903
904impl ShapeTransform {
905    fn is_animated(&self) -> bool {
906        keyed(&self.anchor)
907            || self.position.is_animated()
908            || keyed(&self.scale)
909            || keyed(&self.rotation_degrees)
910            || keyed(&self.opacity)
911    }
912}
913
914const fn keyed<T>(animation: &Animated<T>) -> bool {
915    matches!(
916        animation,
917        Animated::Keyframes { .. } | Animated::Split { .. }
918    )
919}