use crate::{CubicBezier, DataBinding, Easing, EasingPoint, Steps, ValueBezier};
use serde::{Deserialize, Serialize};
#[derive(Copy, Clone, Debug, Default, Deserialize, PartialEq, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct Vec2 {
pub x: f32,
pub y: f32,
}
impl Vec2 {
#[must_use]
pub const fn new(x: f32, y: f32) -> Self {
Self { x, y }
}
fn is_finite(self) -> bool {
self.x.is_finite() && self.y.is_finite()
}
#[must_use]
pub fn is_zero(&self) -> bool {
self.x == 0.0 && self.y == 0.0
}
}
pub const MAX_KEYFRAMES: usize = 100_000;
#[derive(Copy, Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "snake_case")]
pub enum Extrapolation {
#[default]
Hold,
Linear,
Repeat,
RepeatOffset,
PingPong,
}
impl Extrapolation {
#[must_use]
pub const fn is_hold(&self) -> bool {
matches!(self, Self::Hold)
}
const fn word(self) -> &'static str {
match self {
Self::Hold => "hold",
Self::Linear => "linear",
Self::Repeat => "repeat",
Self::RepeatOffset => "repeat_offset",
Self::PingPong => "ping_pong",
}
}
}
#[derive(Clone, Debug, PartialEq, Serialize)]
#[serde(tag = "mode", rename_all = "snake_case")]
pub enum Animated<T> {
Constant {
value: T,
},
Keyframes {
keyframes: Vec<Keyframe<T>>,
#[serde(default, skip_serializing_if = "Extrapolation::is_hold")]
before: Extrapolation,
#[serde(default, skip_serializing_if = "Extrapolation::is_hold")]
after: Extrapolation,
},
Split {
channels: Vec<Animated<f32>>,
},
Data(Box<DataBinding>),
}
const MAX_SPLIT_CHANNELS: usize = 4;
mod sealed {
pub trait Sealed {}
}
pub trait AnimatedValue: sealed::Sealed {
const ACCEPTS_DATA: bool;
const VALUE_CURVES: bool = false;
const INTERPOLATES: bool;
const OFFSETS: bool;
const SPLIT: Option<(usize, usize)> = None;
fn takes_value_curve(&self) -> bool {
Self::VALUE_CURVES
}
fn extrapolates(&self, extrapolation: Extrapolation) -> bool {
match extrapolation {
Extrapolation::Hold | Extrapolation::Repeat | Extrapolation::PingPong => true,
Extrapolation::Linear => Self::INTERPOLATES,
Extrapolation::RepeatOffset => Self::OFFSETS,
}
}
}
macro_rules! animated_value {
(data: $data:literal, interpolates: $interpolates:literal, offsets: $offsets:literal;
$($type:ty),+) => {
$(
impl sealed::Sealed for $type {}
impl AnimatedValue for $type {
const ACCEPTS_DATA: bool = $data;
const INTERPOLATES: bool = $interpolates;
const OFFSETS: bool = $offsets;
}
)+
};
}
impl sealed::Sealed for f32 {}
impl AnimatedValue for f32 {
const ACCEPTS_DATA: bool = true;
const VALUE_CURVES: bool = true;
const INTERPOLATES: bool = true;
const OFFSETS: bool = true;
}
impl sealed::Sealed for crate::EffectValue {}
impl AnimatedValue for crate::EffectValue {
const ACCEPTS_DATA: bool = true;
const VALUE_CURVES: bool = true;
const INTERPOLATES: bool = true;
const OFFSETS: bool = true;
const SPLIT: Option<(usize, usize)> = Some((2, MAX_SPLIT_CHANNELS));
fn takes_value_curve(&self) -> bool {
matches!(self, Self::Float(_))
}
fn extrapolates(&self, extrapolation: Extrapolation) -> bool {
match extrapolation {
Extrapolation::Hold | Extrapolation::Repeat | Extrapolation::PingPong => true,
Extrapolation::Linear => self.interpolates(),
Extrapolation::RepeatOffset => {
matches!(self, Self::Float(_) | Self::Vec2(_) | Self::Vec4(_))
}
}
}
}
impl sealed::Sealed for Vec2 {}
impl AnimatedValue for Vec2 {
const ACCEPTS_DATA: bool = true;
const INTERPOLATES: bool = true;
const OFFSETS: bool = true;
const SPLIT: Option<(usize, usize)> = Some((2, 2));
}
animated_value!(data: false, interpolates: false, offsets: false; String, crate::TextContent);
animated_value!(
data: false, interpolates: true, offsets: false;
crate::Paint,
crate::Rgba,
crate::Path,
crate::LayoutLength,
crate::LayoutSize,
crate::LayoutOffset,
crate::Insets
);
#[derive(Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(tag = "mode", rename_all = "snake_case", deny_unknown_fields)]
#[cfg_attr(feature = "schema", schemars(rename = "Animated_{T}"))]
#[cfg_attr(
feature = "schema",
schemars(bound = "T: schemars::JsonSchema + AnimatedValue")
)]
enum AnimatedWire<T> {
Constant {
value: T,
},
Keyframes {
#[serde(deserialize_with = "crate::bounded::seq::<_, _, { crate::MAX_KEYFRAMES }>")]
#[cfg_attr(feature = "schema", schemars(length(max = crate::MAX_KEYFRAMES)))]
keyframes: Vec<Keyframe<T>>,
#[serde(default, skip_serializing_if = "Extrapolation::is_hold")]
#[cfg_attr(
feature = "schema",
schemars(schema_with = "extrapolation_schema::<T>")
)]
before: Extrapolation,
#[serde(default, skip_serializing_if = "Extrapolation::is_hold")]
#[cfg_attr(
feature = "schema",
schemars(schema_with = "extrapolation_schema::<T>")
)]
after: Extrapolation,
},
Split {
#[serde(deserialize_with = "crate::bounded::seq::<_, _, MAX_SPLIT_CHANNELS>")]
channels: Vec<Animated<f32>>,
},
Data(DataBinding),
}
#[cfg(feature = "schema")]
fn extrapolation_schema<T: AnimatedValue>(
generator: &mut schemars::SchemaGenerator,
) -> schemars::Schema {
match (T::INTERPOLATES, T::OFFSETS) {
(true, true) => generator.subschema_for::<Extrapolation>(),
(true, false) => generator.subschema_for::<ExtrapolationWithoutOffset>(),
(false, _) => generator.subschema_for::<HoldExtrapolation>(),
}
}
#[cfg(feature = "schema")]
struct ExtrapolationWithoutOffset;
#[cfg(feature = "schema")]
impl schemars::JsonSchema for ExtrapolationWithoutOffset {
fn schema_name() -> std::borrow::Cow<'static, str> {
"ExtrapolationWithoutOffset".into()
}
fn schema_id() -> std::borrow::Cow<'static, str> {
"alpha2_model::ExtrapolationWithoutOffset".into()
}
fn json_schema(generator: &mut schemars::SchemaGenerator) -> schemars::Schema {
let mut schema = Extrapolation::json_schema(generator);
crate::schema::drop_word(&mut schema, Extrapolation::RepeatOffset.word());
schema.insert(
"description".to_owned(),
"What a keyframed value that has no difference to add does before its first \
keyframe or after its\nlast: every choice but `repeat_offset`."
.into(),
);
schema
}
}
#[cfg(feature = "schema")]
struct HoldExtrapolation;
#[cfg(feature = "schema")]
impl schemars::JsonSchema for HoldExtrapolation {
fn schema_name() -> std::borrow::Cow<'static, str> {
"HoldExtrapolation".into()
}
fn schema_id() -> std::borrow::Cow<'static, str> {
"alpha2_model::HoldExtrapolation".into()
}
fn json_schema(generator: &mut schemars::SchemaGenerator) -> schemars::Schema {
let mut schema = Extrapolation::json_schema(generator);
for extrapolation in [Extrapolation::Linear, Extrapolation::RepeatOffset] {
crate::schema::drop_word(&mut schema, extrapolation.word());
}
schema.insert(
"description".to_owned(),
"What a keyframed value that only holds does before its first keyframe or after \
its last: `hold`,\n`repeat` or `ping_pong`."
.into(),
);
schema
}
}
impl<'de, T: Deserialize<'de> + AnimatedValue> Deserialize<'de> for Animated<T> {
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
Ok(match AnimatedWire::<T>::deserialize(deserializer)? {
AnimatedWire::Constant { value } => Self::Constant { value },
AnimatedWire::Keyframes {
keyframes,
before,
after,
} => {
if keyframes.iter().any(|keyframe| {
matches!(keyframe.interpolation, Interpolation::ValueBezier(_))
&& !keyframe.value.takes_value_curve()
}) {
return Err(serde::de::Error::custom(if T::SPLIT.is_some() {
"this value takes no `value_bezier`; split it or use a timing curve"
} else {
"this value takes no `value_bezier`; use a timing curve"
}));
}
if let Some(refused) = [before, after].into_iter().find(|extrapolation| {
!keyframes
.iter()
.all(|keyframe| keyframe.value.extrapolates(*extrapolation))
}) {
return Err(serde::de::Error::custom(format_args!(
"this value takes no `{}` extrapolation",
refused.word()
)));
}
Self::Keyframes {
keyframes,
before,
after,
}
}
AnimatedWire::Split { channels } => match T::SPLIT {
Some((least, most)) if (least..=most).contains(&channels.len()) => {
Self::Split { channels }
}
Some((least, most)) => {
return Err(serde::de::Error::custom(format_args!(
"a `split` of this value has {least} to {most} channels, not {}",
channels.len()
)));
}
None => {
return Err(serde::de::Error::custom("this value takes no `split` mode"));
}
},
AnimatedWire::Data(binding) if T::ACCEPTS_DATA => Self::Data(Box::new(binding)),
AnimatedWire::Data(_) => {
return Err(serde::de::Error::custom(
"this value takes no `data` mode; use `constant` or `keyframes`",
));
}
})
}
}
#[cfg(feature = "schema")]
impl<T: schemars::JsonSchema + AnimatedValue> schemars::JsonSchema for Animated<T> {
fn schema_name() -> std::borrow::Cow<'static, str> {
if T::ACCEPTS_DATA {
AnimatedWire::<T>::schema_name()
} else {
format!("Keyframed_{}", T::schema_name()).into()
}
}
fn schema_id() -> std::borrow::Cow<'static, str> {
if T::ACCEPTS_DATA {
AnimatedWire::<T>::schema_id()
} else {
format!("alpha2_model::Keyframed<{}>", T::schema_id()).into()
}
}
fn json_schema(generator: &mut schemars::SchemaGenerator) -> schemars::Schema {
let mut schema = AnimatedWire::<T>::json_schema(generator);
match T::SPLIT {
Some((least, most)) => crate::schema::bound_split_channels(&mut schema, least, most),
None => crate::schema::drop_variant(&mut schema, "mode", "split"),
}
if !T::ACCEPTS_DATA {
crate::schema::drop_data_mode(&mut schema);
schema.insert(
"description".to_owned(),
"A value that is constant or controlled by sorted keyframes.".into(),
);
}
schema
}
}
impl<T> Animated<T> {
#[must_use]
pub const fn keyed(keyframes: Vec<Keyframe<T>>) -> Self {
Self::Keyframes {
keyframes,
before: Extrapolation::Hold,
after: Extrapolation::Hold,
}
}
#[must_use]
pub fn map<U>(&self, map: impl Fn(&T) -> U) -> Animated<U> {
match self {
Self::Constant { value } => Animated::Constant { value: map(value) },
Self::Keyframes {
keyframes,
before,
after,
} => Animated::Keyframes {
keyframes: keyframes
.iter()
.map(|keyframe| Keyframe {
time: keyframe.time,
value: map(&keyframe.value),
interpolation: keyframe.interpolation.clone(),
})
.collect(),
before: *before,
after: *after,
},
Self::Split { channels } => Animated::Split {
channels: channels.clone(),
},
Self::Data(binding) => Animated::Data(binding.clone()),
}
}
#[must_use]
pub const fn data(&self) -> Option<&DataBinding> {
match self {
Self::Data(binding) => Some(binding),
Self::Constant { .. } | Self::Keyframes { .. } | Self::Split { .. } => None,
}
}
#[must_use]
pub const fn varies(&self) -> bool {
!matches!(self, Self::Constant { .. })
}
}
pub(crate) fn bindings_of<'a, T: Placed>(
at: &str,
animated: &'a Animated<T>,
visit: &mut dyn FnMut(&str, &'a DataBinding, PlaceType),
) {
match animated {
Animated::Data(binding) => visit(at, binding, T::PLACE),
Animated::Split { channels } => channel_bindings(channels, at, visit),
Animated::Constant { .. } | Animated::Keyframes { .. } => {}
}
}
pub(crate) fn point_bindings_of<'a>(
at: &str,
animated: &'a AnimatedPoint,
visit: &mut dyn FnMut(&str, &'a DataBinding, PlaceType),
) {
match animated {
AnimatedPoint::Data(binding) => visit(at, binding, PlaceType::Point),
AnimatedPoint::Split { channels } => channel_bindings(channels, at, visit),
AnimatedPoint::Path(motion) => {
bindings_of(&format!("{at}.distance"), &motion.distance, visit);
}
AnimatedPoint::Constant { .. } | AnimatedPoint::Keyframes { .. } => {}
}
}
fn channel_bindings<'a>(
channels: &'a [Animated<f32>],
at: &str,
visit: &mut dyn FnMut(&str, &'a DataBinding, PlaceType),
) {
for (index, channel) in channels.iter().enumerate() {
if let Animated::Data(binding) = channel {
visit(&channel_path(at, index), binding, PlaceType::Scalar);
}
}
}
pub(crate) fn channel_path(at: &str, index: usize) -> String {
format!("{at}.channels[{index}]")
}
pub(crate) fn valid_channels(
channels: &[Animated<f32>],
count: std::ops::RangeInclusive<usize>,
check: impl Fn(f32) -> bool,
) -> bool {
count.contains(&channels.len())
&& channels
.iter()
.all(|channel| valid_scalar_values(channel, &check))
}
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
#[serde(tag = "mode", rename_all = "snake_case")]
pub enum AnimatedPoint {
Constant {
value: Vec2,
},
Keyframes {
#[serde(deserialize_with = "crate::bounded::seq::<_, _, { crate::MAX_KEYFRAMES }>")]
#[cfg_attr(feature = "schema", schemars(length(max = crate::MAX_KEYFRAMES)))]
keyframes: Vec<PointKeyframe>,
#[serde(default, skip_serializing_if = "Extrapolation::is_hold")]
before: Extrapolation,
#[serde(default, skip_serializing_if = "Extrapolation::is_hold")]
after: Extrapolation,
},
Split {
#[serde(deserialize_with = "two_channels")]
#[cfg_attr(feature = "schema", schemars(length(min = 2, max = 2)))]
channels: Vec<Animated<f32>>,
},
Path(Box<MotionPath>),
Data(Box<DataBinding>),
}
pub const MAX_MOTION_PATH_VERTICES: usize = 256;
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct MotionPath {
#[serde(deserialize_with = "motion_path")]
#[cfg_attr(feature = "schema", schemars(schema_with = "motion_path_schema"))]
pub path: crate::Path,
pub distance: Animated<f32>,
}
fn motion_path<'de, D: serde::Deserializer<'de>>(deserializer: D) -> Result<crate::Path, D::Error> {
let path = crate::Path::deserialize(deserializer)?;
let vertices = match path.subpaths.as_slice() {
[subpath] => subpath.vertices.len(),
subpaths => {
return Err(serde::de::Error::custom(format_args!(
"the path of a position has 1 subpath, not {}",
subpaths.len()
)));
}
};
if !(2..=MAX_MOTION_PATH_VERTICES).contains(&vertices) {
return Err(serde::de::Error::custom(format_args!(
"the path of a position has 2 to {MAX_MOTION_PATH_VERTICES} vertices, not {vertices}"
)));
}
Ok(path)
}
#[cfg(feature = "schema")]
fn motion_path_schema(generator: &mut schemars::SchemaGenerator) -> schemars::Schema {
let vertex = generator.subschema_for::<crate::PathVertex>();
schemars::json_schema!({
"description": "One subpath of 2 to `MAX_MOTION_PATH_VERTICES` vertices.",
"type": "object",
"properties": {
"subpaths": {
"type": "array",
"minItems": 1,
"maxItems": 1,
"items": {
"type": "object",
"properties": {
"closed": {
"description": "Whether a segment joins the last vertex back to the first.",
"type": "boolean",
"default": false
},
"vertices": {
"description": "The vertices, in order.",
"type": "array",
"minItems": 2,
"maxItems": MAX_MOTION_PATH_VERTICES,
"items": vertex
}
},
"required": ["vertices"],
"additionalProperties": false
}
}
},
"required": ["subpaths"],
"additionalProperties": false
})
}
#[derive(Copy, Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "snake_case")]
pub enum Orient {
#[default]
None,
Path,
}
impl Orient {
#[expect(
clippy::trivially_copy_pass_by_ref,
reason = "serde passes a field by reference"
)]
fn is_none(&self) -> bool {
*self == Self::None
}
}
fn two_channels<'de, D: serde::Deserializer<'de>>(
deserializer: D,
) -> Result<Vec<Animated<f32>>, D::Error> {
let channels = crate::bounded::seq::<_, Animated<f32>, 2>(deserializer)?;
if channels.len() != 2 {
return Err(serde::de::Error::custom(format_args!(
"a `split` position has 2 channels, not {}",
channels.len()
)));
}
Ok(channels)
}
impl Default for AnimatedPoint {
fn default() -> Self {
Self::Constant {
value: Vec2::default(),
}
}
}
impl From<Animated<Vec2>> for AnimatedPoint {
fn from(animation: Animated<Vec2>) -> Self {
match animation {
Animated::Constant { value } => Self::Constant { value },
Animated::Keyframes {
keyframes,
before,
after,
} => Self::Keyframes {
keyframes: keyframes
.into_iter()
.map(|keyframe| PointKeyframe {
time: keyframe.time,
value: keyframe.value,
interpolation: keyframe.interpolation,
out_tangent: Vec2::default(),
in_tangent: Vec2::default(),
})
.collect(),
before,
after,
},
Animated::Split { channels } => Self::Split { channels },
Animated::Data(binding) => Self::Data(binding),
}
}
}
impl Animated<f32> {
#[must_use]
pub fn is_valid(&self) -> bool {
valid_scalar_values(self, |_| true)
}
}
impl AnimatedPoint {
#[must_use]
pub fn is_valid(&self) -> bool {
valid_point_animation(self)
}
#[must_use]
pub const fn keyed(keyframes: Vec<PointKeyframe>) -> Self {
Self::Keyframes {
keyframes,
before: Extrapolation::Hold,
after: Extrapolation::Hold,
}
}
#[must_use]
pub const fn is_animated(&self) -> bool {
!matches!(self, Self::Constant { .. })
}
#[must_use]
pub const fn data(&self) -> Option<&DataBinding> {
match self {
Self::Data(binding) => Some(binding),
Self::Constant { .. } | Self::Keyframes { .. } | Self::Split { .. } | Self::Path(_) => {
None
}
}
}
}
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct PointKeyframe {
pub time: alpha2_time::MediaTime,
pub value: Vec2,
#[serde(deserialize_with = "timing_interpolation")]
#[cfg_attr(feature = "schema", schemars(with = "TimingInterpolation"))]
pub interpolation: Interpolation,
#[serde(default, skip_serializing_if = "Vec2::is_zero")]
pub out_tangent: Vec2,
#[serde(default, skip_serializing_if = "Vec2::is_zero")]
pub in_tangent: Vec2,
}
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
#[cfg_attr(feature = "schema", schemars(rename = "Keyframe_{T}"))]
#[cfg_attr(
feature = "schema",
schemars(bound = "T: schemars::JsonSchema + AnimatedValue")
)]
pub struct Keyframe<T> {
pub time: alpha2_time::MediaTime,
pub value: T,
#[cfg_attr(
feature = "schema",
schemars(schema_with = "interpolation_schema::<T>")
)]
pub interpolation: Interpolation,
}
#[cfg(feature = "schema")]
fn interpolation_schema<T: AnimatedValue>(
generator: &mut schemars::SchemaGenerator,
) -> schemars::Schema {
if T::VALUE_CURVES {
generator.subschema_for::<Interpolation>()
} else {
generator.subschema_for::<TimingInterpolation>()
}
}
fn timing_interpolation<'de, D: serde::Deserializer<'de>>(
deserializer: D,
) -> Result<Interpolation, D::Error> {
let interpolation = Interpolation::deserialize(deserializer)?;
if matches!(interpolation, Interpolation::ValueBezier(_)) {
return Err(serde::de::Error::custom(
"a position takes no `value_bezier`; split it or use a timing curve",
));
}
Ok(interpolation)
}
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(tag = "type", rename_all = "snake_case", from = "InterpolationWire")]
pub enum Interpolation {
Hold,
Linear,
CubicBezier(CubicBezier),
ValueBezier(ValueBezier),
Steps(Steps),
Points {
points: Vec<EasingPoint>,
},
}
#[cfg(feature = "schema")]
pub(crate) struct TimingInterpolation;
#[cfg(feature = "schema")]
impl schemars::JsonSchema for TimingInterpolation {
fn schema_name() -> std::borrow::Cow<'static, str> {
"TimingInterpolation".into()
}
fn schema_id() -> std::borrow::Cow<'static, str> {
"alpha2_model::TimingInterpolation".into()
}
fn json_schema(generator: &mut schemars::SchemaGenerator) -> schemars::Schema {
let mut schema = InterpolationWire::json_schema(generator);
crate::schema::drop_variant(&mut schema, "type", "value_bezier");
schema.insert(
"description".to_owned(),
"Interpolation from one keyframe to the next for a value that is not a number: every \
kind but\nthe value curve."
.into(),
);
schema
}
}
#[derive(Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[cfg_attr(feature = "schema", schemars(rename = "Interpolation"))]
#[serde(tag = "type", rename_all = "snake_case", deny_unknown_fields)]
pub(crate) enum InterpolationWire {
Hold {},
Linear {},
CubicBezier(CubicBezier),
ValueBezier(ValueBezier),
Steps(Steps),
Points {
#[serde(deserialize_with = "crate::bounded::seq::<_, _, { crate::MAX_EASING_POINTS }>")]
#[cfg_attr(feature = "schema", schemars(length(max = crate::MAX_EASING_POINTS)))]
points: Vec<EasingPoint>,
},
}
impl From<InterpolationWire> for Interpolation {
fn from(wire: InterpolationWire) -> Self {
match wire {
InterpolationWire::Hold {} => Self::Hold,
InterpolationWire::Linear {} => Self::Linear,
InterpolationWire::CubicBezier(curve) => Self::CubicBezier(curve),
InterpolationWire::ValueBezier(curve) => Self::ValueBezier(curve),
InterpolationWire::Steps(steps) => Self::Steps(steps),
InterpolationWire::Points { points } => Self::Points { points },
}
}
}
impl From<Easing> for Interpolation {
fn from(easing: Easing) -> Self {
match easing {
Easing::Linear => Self::Linear,
Easing::CubicBezier(curve) => Self::CubicBezier(curve),
Easing::Steps(steps) => Self::Steps(steps),
Easing::Points { points } => Self::Points { points },
}
}
}
#[derive(Copy, Clone, Debug, PartialEq)]
pub enum SegmentShape {
Hold,
Amount(f64),
Value(ValueBezier),
}
impl Interpolation {
#[must_use]
#[inline]
pub fn shape(&self, progress: f64) -> SegmentShape {
match self {
Self::Hold => SegmentShape::Hold,
Self::Linear => SegmentShape::Amount(progress.clamp(0.0, 1.0)),
Self::CubicBezier(curve) => SegmentShape::Amount(curve.apply(progress)),
Self::ValueBezier(curve) => SegmentShape::Value(*curve),
Self::Steps(steps) => SegmentShape::Amount(steps.apply(progress)),
Self::Points { points } => {
SegmentShape::Amount(crate::easing_points_at(points, progress))
}
}
}
#[must_use]
pub fn end_slope(&self, at_end: bool) -> Option<f64> {
match self {
Self::Hold | Self::Steps(_) => Some(0.0),
Self::Linear => Some(1.0),
Self::CubicBezier(curve) => Some(curve.end_slope(at_end)),
Self::ValueBezier(_) => None,
Self::Points { points } => Some(crate::easing_points_slope(
points,
if at_end { 1.0 } else { 0.0 },
)),
}
}
#[must_use]
pub fn is_valid(&self) -> bool {
match self {
Self::Hold | Self::Linear => true,
Self::CubicBezier(curve) => curve.is_valid(),
Self::ValueBezier(curve) => curve.is_valid(),
Self::Steps(steps) => steps.is_valid(),
Self::Points { points } => crate::easing_points_valid(points),
}
}
}
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct VisualProperties {
#[serde(default = "centre_point")]
pub position: AnimatedPoint,
#[serde(default = "centre")]
pub anchor: Vec2,
#[serde(default = "unit_scale")]
pub scale: Animated<Vec2>,
#[serde(default = "no_rotation")]
pub rotation_degrees: Animated<f32>,
#[serde(default = "opaque")]
pub opacity: Animated<f32>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub correction: Option<crate::CorrectionRef>,
#[serde(default, skip_serializing_if = "Orient::is_none")]
pub orient: Orient,
}
impl Default for VisualProperties {
fn default() -> Self {
Self {
position: centre_point(),
anchor: centre(),
scale: unit_scale(),
rotation_degrees: no_rotation(),
opacity: opaque(),
correction: None,
orient: Orient::None,
}
}
}
const fn centre() -> Vec2 {
Vec2::new(0.5, 0.5)
}
const fn centre_point() -> AnimatedPoint {
AnimatedPoint::Constant { value: centre() }
}
pub(crate) const fn unit_scale() -> Animated<Vec2> {
Animated::Constant {
value: Vec2::new(1.0, 1.0),
}
}
const fn no_rotation() -> Animated<f32> {
Animated::Constant { value: 0.0 }
}
pub(crate) const fn opaque() -> Animated<f32> {
Animated::Constant { value: 1.0 }
}
pub(crate) enum Keyed<'a> {
Times(&'a [alpha2_time::MediaTime], Extrapolation, Extrapolation),
Data(&'a DataBinding, PlaceType),
}
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub(crate) enum PlaceType {
Point,
Vec2,
Scalar,
Effect,
Other,
}
pub(crate) trait Placed {
const PLACE: PlaceType;
}
macro_rules! placed {
($place:ident: $($type:ty),+) => {
$(impl Placed for $type {
const PLACE: PlaceType = PlaceType::$place;
})+
};
}
placed!(Scalar: f32);
placed!(Vec2: Vec2);
placed!(Effect: crate::EffectValue);
placed!(
Other: String,
crate::TextContent,
crate::Paint,
crate::Rgba,
crate::Path,
crate::LayoutLength,
crate::LayoutSize,
crate::LayoutOffset,
crate::Insets
);
pub(crate) fn visit_keyed<T: Placed>(
at: &str,
animated: &Animated<T>,
visit: &mut impl FnMut(&str, Keyed<'_>),
) {
match animated {
Animated::Keyframes {
keyframes,
before,
after,
} => {
let times = keyframes
.iter()
.map(|keyframe| keyframe.time)
.collect::<Vec<_>>();
visit(at, Keyed::Times(×, *before, *after));
}
Animated::Split { channels } => visit_keyed_channels(at, channels, visit),
Animated::Data(binding) => visit(at, Keyed::Data(binding, T::PLACE)),
Animated::Constant { .. } => {}
}
}
fn visit_keyed_channels(
at: &str,
channels: &[Animated<f32>],
visit: &mut impl FnMut(&str, Keyed<'_>),
) {
for (index, channel) in channels.iter().enumerate() {
match channel {
Animated::Keyframes {
keyframes,
before,
after,
} => {
let times = keyframes
.iter()
.map(|keyframe| keyframe.time)
.collect::<Vec<_>>();
visit(
&channel_path(at, index),
Keyed::Times(×, *before, *after),
);
}
Animated::Data(binding) => visit(
&channel_path(at, index),
Keyed::Data(binding, PlaceType::Scalar),
),
Animated::Constant { .. } | Animated::Split { .. } => {}
}
}
}
pub(crate) fn visit_keyed_point(
at: &str,
animated: &AnimatedPoint,
visit: &mut impl FnMut(&str, Keyed<'_>),
) {
match animated {
AnimatedPoint::Keyframes {
keyframes,
before,
after,
} => {
let times = keyframes
.iter()
.map(|keyframe| keyframe.time)
.collect::<Vec<_>>();
visit(at, Keyed::Times(×, *before, *after));
}
AnimatedPoint::Split { channels } => visit_keyed_channels(at, channels, visit),
AnimatedPoint::Path(motion) => {
visit_keyed(&format!("{at}.distance"), &motion.distance, visit);
}
AnimatedPoint::Data(binding) => visit(at, Keyed::Data(binding, PlaceType::Point)),
AnimatedPoint::Constant { .. } => {}
}
}
impl VisualProperties {
pub(crate) fn validate(&self) -> bool {
self.anchor.is_finite()
&& valid_point_animation(&self.position)
&& valid_vec2_animation(&self.scale)
&& valid_scalar_animation(&self.rotation_degrees, false)
&& valid_scalar_animation(&self.opacity, true)
}
}
fn valid_vec2_animation(animation: &Animated<Vec2>) -> bool {
match animation {
Animated::Constant { value } => value.is_finite(),
Animated::Keyframes {
keyframes,
before,
after,
} => {
valid_keyframes(keyframes, *before, *after)
&& keyframes.iter().all(|keyframe| keyframe.value.is_finite())
}
Animated::Split { channels } => valid_channels(channels, 2..=2, |_| true),
Animated::Data(_) => true,
}
}
pub(crate) fn valid_point_animation(animation: &AnimatedPoint) -> bool {
match animation {
AnimatedPoint::Constant { value } => value.is_finite(),
AnimatedPoint::Data(_) => true,
AnimatedPoint::Split { channels } => valid_channels(channels, 2..=2, |_| true),
AnimatedPoint::Path(motion) => {
let vertices = match motion.path.subpaths.as_slice() {
[subpath] => subpath.vertices.as_slice(),
_ => &[],
};
(2..=MAX_MOTION_PATH_VERTICES).contains(&vertices.len())
&& vertices.iter().all(|vertex| {
vertex.point.is_finite()
&& vertex.in_tangent.is_finite()
&& vertex.out_tangent.is_finite()
})
&& valid_scalar_values(&motion.distance, |_| true)
}
AnimatedPoint::Keyframes { keyframes, .. } => {
!keyframes.is_empty()
&& keyframes.len() <= MAX_KEYFRAMES
&& keyframes.windows(2).all(|pair| pair[0].time < pair[1].time)
&& keyframes.iter().all(|keyframe| {
keyframe.interpolation.is_valid()
&& !matches!(keyframe.interpolation, Interpolation::ValueBezier(_))
&& keyframe.value.is_finite()
&& keyframe.out_tangent.is_finite()
&& keyframe.in_tangent.is_finite()
})
}
}
}
fn valid_scalar_animation(animation: &Animated<f32>, unit_interval: bool) -> bool {
let domain = if unit_interval {
crate::Domain::UNIT
} else {
crate::Domain::ANY
};
let valid_value = |value: f32| domain.contains(value);
match animation {
Animated::Constant { value } => valid_value(*value),
Animated::Keyframes {
keyframes,
before,
after,
} => {
valid_keyframes(keyframes, *before, *after)
&& keyframes.iter().all(|keyframe| valid_value(keyframe.value))
}
Animated::Split { .. } => false,
Animated::Data(_) => true,
}
}
pub(crate) fn valid_scalar_values(animation: &Animated<f32>, check: impl Fn(f32) -> bool) -> bool {
let valid = |value: f32| value.is_finite() && check(value);
match animation {
Animated::Constant { value } => valid(*value),
Animated::Keyframes {
keyframes,
before,
after,
} => {
valid_keyframes(keyframes, *before, *after)
&& keyframes.iter().all(|keyframe| valid(keyframe.value))
}
Animated::Split { .. } => false,
Animated::Data(_) => true,
}
}
pub(crate) fn valid_keyframes<T: AnimatedValue>(
keyframes: &[Keyframe<T>],
before: Extrapolation,
after: Extrapolation,
) -> bool {
!keyframes.is_empty()
&& keyframes.iter().all(|keyframe| {
keyframe.value.extrapolates(before) && keyframe.value.extrapolates(after)
})
&& keyframes.len() <= MAX_KEYFRAMES
&& keyframes.windows(2).all(|pair| pair[0].time < pair[1].time)
&& keyframes
.iter()
.all(|keyframe| keyframe.interpolation.is_valid())
&& keyframes
.iter()
.zip(keyframes.iter().skip(1).map(Some).chain([None]))
.all(|(keyframe, next)| {
!matches!(keyframe.interpolation, Interpolation::ValueBezier(_))
|| (keyframe.value.takes_value_curve()
&& next.is_none_or(|next| next.value.takes_value_curve()))
})
}