use super::{time, to_text};
use crate::curves::{self, AutoTangent, CurveError, SegmentKind};
use alpha2_model::{Animated, AnimatedPoint, Interpolation, ValueBezier};
use alpha2_time::{MediaTime, TimeRange};
use serde_json::{Value, json};
fn number(json: &str) -> Result<Animated<f32>, String> {
let animation: Animated<f32> =
serde_json::from_str(json).map_err(|error| format!("invalid curve: {error}"))?;
if !animation.is_valid() {
return Err("invalid curve: not an animated number a project can hold".into());
}
Ok(animation)
}
fn refused(error: CurveError) -> String {
format!("invalid curve: {error}")
}
fn range(start: f64, end: f64) -> Result<TimeRange, String> {
TimeRange::new(time(start)?, time(end)?)
.map_err(|_| "invalid curve: the range ends before it starts".to_owned())
}
fn finite(values: &[f64]) -> Result<(), String> {
if values.iter().all(|value| value.is_finite()) {
Ok(())
} else {
Err("invalid curve: a number is not finite".into())
}
}
fn length(seconds: f64) -> Result<(), String> {
if seconds.is_finite() && seconds > 0.0 {
Ok(())
} else {
Err(format!(
"invalid curve: a segment is longer than no time, not {seconds} seconds"
))
}
}
fn value_curve(curve: ValueBezier) -> Result<String, String> {
to_text(&Interpolation::ValueBezier(curve))
}
pub(crate) const fn kind_name(kind: SegmentKind) -> &'static str {
match kind {
SegmentKind::Hold => "hold",
SegmentKind::Linear => "linear",
SegmentKind::Timing => "timing",
SegmentKind::Value => "value",
SegmentKind::Steps => "steps",
SegmentKind::Points => "points",
}
}
pub(crate) fn tangent_mode(mode: &str) -> Result<AutoTangent, String> {
match mode {
"smooth" => Ok(AutoTangent::Smooth),
"monotone" => Ok(AutoTangent::Monotone),
"flat" => Ok(AutoTangent::Flat),
"linear" => Ok(AutoTangent::Linear),
other => Err(format!(
"invalid curve: a tangent mode is smooth, monotone, flat or linear, not {other}"
)),
}
}
pub fn curve_segments(animation_json: &str) -> Result<String, String> {
let point = |(time, value): (f64, f64)| json!({ "time": time, "value": value });
#[expect(clippy::cast_precision_loss, reason = "ticks as a JSON number")]
let key = |(time, value): (i64, f64)| point((time as f64, value));
let segments: Vec<Value> = curves::segments(&number(animation_json)?)
.into_iter()
.map(|segment| {
json!({
"kind": kind_name(segment.kind),
"start": key(segment.start),
"end": key(segment.end),
"controls": segment.controls.map(|[first, second]| json!([point(first), point(second)])),
})
})
.collect();
to_text(&segments)
}
pub fn sample_curve(animation_json: &str, times: &[i64]) -> Result<String, String> {
let times: Vec<MediaTime> = times.iter().copied().map(MediaTime).collect();
let samples: Vec<Value> = curves::sample(&number(animation_json)?, ×)
.into_iter()
.map(|sample| json!([sample.value, sample.velocity]))
.collect();
to_text(&samples)
}
pub fn curve_range(animation_json: &str, start: f64, end: f64) -> Result<String, String> {
to_text(&curves::range(&number(animation_json)?, range(start, end)?))
}
pub fn insert_key(animation_json: &str, ticks: f64) -> Result<String, String> {
let mut animation = number(animation_json)?;
curves::insert_key(&mut animation, time(ticks)?).map_err(refused)?;
to_text(&animation)
}
pub fn insert_point_key(
point_json: &str,
ticks: f64,
width: u32,
height: u32,
) -> Result<String, String> {
let size = super::canvas(width, height)?;
let mut point: AnimatedPoint =
serde_json::from_str(point_json).map_err(|error| format!("invalid curve: {error}"))?;
if !point.is_valid() {
return Err("invalid curve: not a position a project can hold".into());
}
curves::insert_point_key(&mut point, time(ticks)?, super::aspect(size)).map_err(refused)?;
to_text(&point)
}
pub fn to_value_curves(animation_json: &str) -> Result<String, String> {
let mut animation = number(animation_json)?;
curves::to_value_curves(&mut animation);
to_text(&animation)
}
pub fn to_timing_curves(animation_json: &str) -> Result<String, String> {
let mut animation = number(animation_json)?;
curves::to_timing_curves(&mut animation).map_err(refused)?;
to_text(&animation)
}
pub fn auto_tangents(
animation_json: &str,
mode: &str,
keys: Option<&[i64]>,
) -> Result<String, String> {
let mode = tangent_mode(mode)?;
let mut animation = number(animation_json)?;
let keys: Option<Vec<MediaTime>> =
keys.map(|keys| keys.iter().copied().map(MediaTime).collect());
curves::auto_tangents(&mut animation, mode, keys.as_deref());
to_text(&animation)
}
pub fn curve_from_speed_influence(
seconds: f64,
leave: (f64, f64),
arrive: (f64, f64),
) -> Result<String, String> {
length(seconds)?;
finite(&[leave.0, leave.1, arrive.0, arrive.1])?;
value_curve(curves::from_speed_influence(seconds, leave, arrive))
}
pub fn curve_from_slopes(seconds: f64, leave: f64, arrive: f64) -> Result<String, String> {
length(seconds)?;
finite(&[leave, arrive])?;
value_curve(curves::from_slopes(seconds, leave, arrive))
}
pub fn curve_from_handle_points(points: &[f64]) -> Result<String, String> {
let &[t0, v0, t1, v1, t2, v2, t3, v3] = points else {
return Err(format!(
"invalid curve: four control points are 8 numbers, not {}",
points.len()
));
};
finite(points)?;
length(t3 - t0)?;
value_curve(curves::from_handle_points(
(t0, v0),
(t1, v1),
(t2, v2),
(t3, v3),
))
}
pub fn contain_curve(interpolation_json: &str) -> Result<String, String> {
let interpolation: Interpolation = serde_json::from_str(interpolation_json)
.map_err(|error| format!("invalid curve: {error}"))?;
to_text(&match interpolation {
Interpolation::ValueBezier(curve) => Interpolation::ValueBezier(curves::contain(curve)),
other => other,
})
}
pub fn path_angle(point_json: &str, ticks: f64, width: u32, height: u32) -> Result<f64, String> {
let size = super::canvas(width, height)?;
let point: AnimatedPoint =
serde_json::from_str(point_json).map_err(|error| format!("invalid curve: {error}"))?;
if !point.is_valid() {
return Err("invalid curve: not a position a project can hold".into());
}
Ok(crate::path_angle(
&point,
time(ticks)?,
super::aspect(size),
&crate::SampleContext::NONE,
))
}
pub fn easing_preset(name: &str) -> Result<String, String> {
let easing = alpha2_model::easing_presets::named(name).ok_or_else(|| {
format!(
"invalid curve: no easing is named {name}; the names are the CSS ones, step-start, \
step-end, and ease-in-, ease-out- or ease-in-out- before one of {}",
alpha2_model::easing_presets::EASING_FAMILIES.join(", ")
)
})?;
to_text(&easing)
}
pub fn spring_easing(
(mass, stiffness, damping, velocity): (f64, f64, f64, f64),
tolerance: f64,
max_points: u32,
) -> Result<String, String> {
if !(tolerance.is_finite() && tolerance > 0.0) {
return Err(format!(
"invalid curve: a tolerance is above 0, not {tolerance}"
));
}
let made = alpha2_model::easing_presets::spring(
alpha2_model::easing_presets::Spring {
mass,
stiffness,
damping,
velocity,
},
tolerance,
max_points as usize,
)
.ok_or_else(|| {
format!(
"invalid curve: a spring has a mass, a stiffness and a damping above 0, and settles \
within {} seconds",
alpha2_model::easing_presets::MAX_SPRING_SECONDS
)
})?;
to_text(&json!({ "easing": made.easing, "settleSeconds": made.settle_seconds }))
}
pub fn materialize_curve(animation_json: &str, start: f64, end: f64) -> Result<String, String> {
let mut animation = number(animation_json)?;
curves::materialize(&mut animation, range(start, end)?).map_err(refused)?;
to_text(&animation)
}
pub fn path_to_keys(
point_json: &str,
start: f64,
end: f64,
width: u32,
height: u32,
) -> Result<String, String> {
let size = super::canvas(width, height)?;
let point: AnimatedPoint =
serde_json::from_str(point_json).map_err(|error| format!("invalid curve: {error}"))?;
if !point.is_valid() {
return Err("invalid curve: not a position a project can hold".into());
}
let AnimatedPoint::Path(motion) = point else {
return Err("invalid curve: the position is not on a path".into());
};
let keys =
curves::path_to_keys(&motion, range(start, end)?, super::aspect(size)).map_err(refused)?;
to_text(&keys)
}
#[must_use]
pub fn parity_cases() -> Vec<(&'static str, String)> {
let number = r#"{ "mode": "keyframes", "after": "ping_pong", "keyframes": [
{ "time": 0, "value": 0.25,
"interpolation": { "type": "cubic_bezier", "x1": 0.9, "y1": -0.5, "x2": 0, "y2": 1.5 } },
{ "time": 1200, "value": 2,
"interpolation": { "type": "value_bezier", "x1": 0.25, "leave": 1.5, "x2": 0.5, "arrive": -3 } },
{ "time": 3000, "value": -1, "interpolation": { "type": "linear" } },
{ "time": 3600, "value": 0.5, "interpolation": { "type": "hold" } },
{ "time": 4800, "value": 1, "interpolation": { "type": "linear" } } ] }"#;
let position = r#"{ "mode": "keyframes", "keyframes": [
{ "time": 0, "value": { "x": 0.2, "y": 0.5 },
"interpolation": { "type": "cubic_bezier", "x1": 0.42, "y1": 0, "x2": 0.58, "y2": 1 },
"out_tangent": { "x": 0.1, "y": -0.3 } },
{ "time": 1000, "value": { "x": 0.8, "y": 0.5 }, "interpolation": { "type": "hold" },
"in_tangent": { "x": -0.1, "y": -0.3 } } ] }"#;
let valued = to_value_curves(number).expect("value curves");
vec![
("curveSegments", curve_segments(number).expect("segments")),
(
"sampleCurve",
sample_curve(number, &[-300, 0, 600, 1200, 2100, 3300, 4800, 5400, 9000])
.expect("samples"),
),
(
"curveRange",
curve_range(number, -1000.0, 12_000.0).expect("range"),
),
("insertKey", insert_key(number, 700.0).expect("a key")),
("insertValueKey", insert_key(number, 2000.0).expect("a key")),
(
"insertPointKey",
insert_point_key(position, 400.0, 320, 180).expect("a position key"),
),
(
"toTimingCurves",
to_timing_curves(&valued).expect("timing curves"),
),
("toValueCurves", valued),
(
"autoTangents",
["smooth", "monotone", "flat", "linear"]
.map(|mode| auto_tangents(number, mode, None).expect("tangents"))
.join("\n"),
),
(
"autoTangentsAtOneKey",
auto_tangents(number, "smooth", Some(&[1200])).expect("tangents"),
),
(
"curveFromSpeedInfluence",
curve_from_speed_influence(0.5, (3.0, 20.0), (-1.0, 50.0)).expect("a curve"),
),
(
"curveFromSlopes",
curve_from_slopes(2.0, 1.5, -0.5).expect("a curve"),
),
(
"curveFromHandlePoints",
curve_from_handle_points(&[10.0, 1.0, 24.0, 4.0, 8.0, -2.0, 18.0, 3.0])
.expect("a curve"),
),
(
"containCurve",
contain_curve(
r#"{ "type": "value_bezier", "x1": 1.75, "leave": 3, "x2": -0.25, "arrive": -2 }"#,
)
.expect("a curve"),
),
(
"materializeCurve",
materialize_curve(number, 0.0, 12_000.0).expect("keyframes"),
),
(
"pathToKeys",
path_to_keys(PATH_POSITION, 0.0, 12_000.0, 320, 180).expect("position keys"),
),
]
.into_iter()
.chain(stepped_and_made_cases())
.collect()
}
const PATH_POSITION: &str = r#"{ "mode": "path",
"path": { "subpaths": [ { "closed": true, "vertices": [
{ "point": { "x": 0.2, "y": 0.3 }, "out_tangent": { "x": 0.3, "y": 0 } },
{ "point": { "x": 0.8, "y": 0.7 }, "in_tangent": { "x": 0, "y": -0.25 } },
{ "point": { "x": 0.3, "y": 0.8 } } ] } ] },
"distance": { "mode": "keyframes", "after": "ping_pong", "keyframes": [
{ "time": 0, "value": -0.1,
"interpolation": { "type": "cubic_bezier", "x1": 0.42, "y1": -0.4, "x2": 0.58, "y2": 1 } },
{ "time": 6000, "value": 1.2,
"interpolation": { "type": "value_bezier", "leave": 0.5, "arrive": 0.5 } },
{ "time": 9000, "value": 1.2, "interpolation": { "type": "hold" } } ] } }"#;
fn stepped_and_made_cases() -> Vec<(&'static str, String)> {
let stepped = r#"{ "mode": "keyframes", "before": "ping_pong", "keyframes": [
{ "time": 100, "value": 0.5,
"interpolation": { "type": "steps", "count": 3, "position": "start" } },
{ "time": 160, "value": 2, "interpolation": { "type": "points", "points": [
{ "x": 0.25, "y": 1.5 }, { "x": 0.625, "y": -0.5 } ] } },
{ "time": 240, "value": 0.25, "interpolation": { "type": "linear" } } ] }"#;
vec![
(
"steppedSegments",
curve_segments(stepped).expect("segments"),
),
(
"steppedSamples",
sample_curve(stepped, &[40, 99, 100, 101, 120, 140, 159, 180, 210, 240])
.expect("samples"),
),
(
"insertSteppedKey",
insert_key(stepped, 130.0).expect("held keys"),
),
(
"insertTableKey",
insert_key(stepped, 200.0).expect("two tables"),
),
(
"materializeStepped",
materialize_curve(stepped, 0.0, 240.0).expect("keyframes"),
),
(
"easingPresets",
alpha2_model::easing_presets::easing_names()
.iter()
.map(|name| easing_preset(name).expect("a preset"))
.collect::<Vec<_>>()
.join("\n"),
),
(
"springEasing",
[(10.0, 0.0), (20.0, 0.0), (45.0, -3.0)]
.map(|(damping, velocity)| {
spring_easing((1.0, 100.0, damping, velocity), 5e-4, 64).expect("a spring")
})
.join("\n"),
),
]
}
#[cfg(test)]
#[path = "curves_tests.rs"]
mod tests;