Skip to main content

zaxis/animation/
interpolate.rs

1use crate::{Border, Color, CornerRadius, Gradient, Padding, Rect, Shadow, Transform, Vec2};
2
3/// Implement this for application value types; no engine changes are needed.
4/// Curves can overshoot, so `t` can be outside [0, 1]. Tracks clone endpoints
5/// directly at their boundaries, independent of interpolation rounding.
6pub trait Interpolate: Clone + PartialEq + 'static {
7    fn interpolate(&self, to: &Self, t: f32) -> Self;
8}
9
10impl Interpolate for f32 {
11    fn interpolate(&self, to: &Self, t: f32) -> Self {
12        self + (to - self) * t
13    }
14}
15impl Interpolate for f64 {
16    fn interpolate(&self, to: &Self, t: f32) -> Self {
17        self + (to - self) * f64::from(t)
18    }
19}
20impl Interpolate for Vec2 {
21    fn interpolate(&self, to: &Self, t: f32) -> Self {
22        self.lerp(*to, t)
23    }
24}
25/// RGB is interpolated in linear-light sRGB, alpha linearly in straight-alpha
26/// space, then RGB is encoded back to sRGB and rounded to the nearest byte.
27impl Interpolate for Color {
28    fn interpolate(&self, to: &Self, t: f32) -> Self {
29        if t == 0.0 {
30            return *self;
31        }
32        if t == 1.0 {
33            return *to;
34        }
35        let from = self.linear();
36        let to = to.linear();
37        let mut rgba = [0; 4];
38        for i in 0..4 {
39            let value = from[i].interpolate(&to[i], t).clamp(0.0, 1.0);
40            let encoded = if i == 3 { value } else { encode_srgb(value) };
41            rgba[i] = (encoded * 255.0).round() as u8;
42        }
43        Self(rgba)
44    }
45}
46
47fn encode_srgb(linear: f32) -> f32 {
48    if linear <= 0.0031308 {
49        linear * 12.92
50    } else {
51        1.055 * linear.powf(1.0 / 2.4) - 0.055
52    }
53}
54
55/// A color interpolated in the perceptual Oklab space. Plain `Color` blends in
56/// linear light, which keeps brightness physically right but makes the middle of
57/// saturated pairs (blue to yellow) grey and black-to-white too bright; Oklab
58/// keeps hue and perceived lightness steady. Endpoints are exact.
59#[derive(Clone, Copy, Debug, PartialEq)]
60pub struct Oklab(pub Color);
61
62// The conversion matrices are quoted as published (Björn Ottosson, "A perceptual color
63// space for image processing"); f32 rounds the extra digits.
64#[allow(clippy::excessive_precision)]
65impl Oklab {
66    fn lab(color: Color) -> [f32; 3] {
67        let [r, g, b, _] = color.linear();
68        let l = (0.4122214708 * r + 0.5363325363 * g + 0.0514459929 * b).cbrt();
69        let m = (0.2119034982 * r + 0.6806995451 * g + 0.1073969566 * b).cbrt();
70        let s = (0.0883024619 * r + 0.2817188376 * g + 0.6299787005 * b).cbrt();
71        [
72            0.2104542553 * l + 0.7936177850 * m - 0.0040720468 * s,
73            1.9779984951 * l - 2.4285922050 * m + 0.4505937099 * s,
74            0.0259040371 * l + 0.7827717662 * m - 0.8086757660 * s,
75        ]
76    }
77    fn color(lab: [f32; 3], alpha: f32) -> Color {
78        let [lightness, a, b] = lab;
79        let l = (lightness + 0.3963377774 * a + 0.2158037573 * b).powi(3);
80        let m = (lightness - 0.1055613458 * a - 0.0638541728 * b).powi(3);
81        let s = (lightness - 0.0894841775 * a - 1.2914855480 * b).powi(3);
82        let linear = [
83            4.0767416621 * l - 3.3077115913 * m + 0.2309699292 * s,
84            -1.2684380046 * l + 2.6097574011 * m - 0.3413193965 * s,
85            -0.0041960863 * l - 0.7034186147 * m + 1.7076147010 * s,
86        ];
87        let byte = |v: f32| (encode_srgb(v.clamp(0.0, 1.0)) * 255.0).round() as u8;
88        Color([
89            byte(linear[0]),
90            byte(linear[1]),
91            byte(linear[2]),
92            (alpha.clamp(0.0, 1.0) * 255.0).round() as u8,
93        ])
94    }
95}
96impl Interpolate for Oklab {
97    fn interpolate(&self, to: &Self, t: f32) -> Self {
98        if t == 0.0 {
99            return *self;
100        }
101        if t == 1.0 {
102            return *to;
103        }
104        let (from_lab, to_lab) = (Self::lab(self.0), Self::lab(to.0));
105        let lab = from_lab.interpolate(&to_lab, t);
106        let alpha = f32::from(self.0 .0[3]) / 255.0;
107        let alpha = alpha.interpolate(&(f32::from(to.0 .0[3]) / 255.0), t);
108        Self(Self::color(lab, alpha))
109    }
110}
111impl From<Color> for Oklab {
112    fn from(color: Color) -> Self {
113        Self(color)
114    }
115}
116impl From<Oklab> for Color {
117    fn from(color: Oklab) -> Self {
118        color.0
119    }
120}
121
122/// Implement [`Interpolate`] for a struct by interpolating the named fields,
123/// each of which must itself implement `Interpolate`.
124///
125/// ```
126/// use zaxis::{impl_interpolate, Interpolate, Vec2};
127/// #[derive(Clone, PartialEq)]
128/// struct Pose { offset: Vec2, angle: f32 }
129/// impl_interpolate!(Pose { offset, angle });
130/// let half = Pose { offset: Vec2::ZERO, angle: 0.0 }
131///     .interpolate(&Pose { offset: Vec2::new(10.0, 0.0), angle: 2.0 }, 0.5);
132/// assert_eq!(half.angle, 1.0);
133/// ```
134#[macro_export]
135macro_rules! impl_interpolate {
136    ($ty:ty { $($field:ident),+ $(,)? }) => {
137        impl $crate::Interpolate for $ty {
138            fn interpolate(&self, to: &Self, t: f32) -> Self {
139                Self {
140                    $($field: $crate::Interpolate::interpolate(&self.$field, &to.$field, t)),+
141                }
142            }
143        }
144    };
145}
146
147macro_rules! fields {
148    ($ty:ty, $($field:ident),+ $(,)?) => {
149        impl Interpolate for $ty {
150            fn interpolate(&self, to: &Self, t: f32) -> Self {
151                Self { $($field: self.$field.interpolate(&to.$field, t)),+ }
152            }
153        }
154    };
155}
156fields!(Border, width, color);
157fields!(CornerRadius, top_left, top_right, bottom_left, bottom_right);
158fields!(Shadow, color, offset, blur_radius, spread);
159fields!(Rect, min, max);
160fields!(Padding, left, right, top, bottom);
161fields!(Transform, scale, translation, angle);
162
163impl Interpolate for Gradient {
164    fn interpolate(&self, to: &Self, t: f32) -> Self {
165        Self {
166            start: self.start.interpolate(&to.start, t),
167            end: self.end.interpolate(&to.end, t),
168            // Direction is discrete; retain it until reaching the target.
169            direction: if t >= 1.0 {
170                to.direction
171            } else {
172                self.direction
173            },
174        }
175    }
176}
177impl<T: Interpolate, const N: usize> Interpolate for [T; N] {
178    fn interpolate(&self, to: &Self, t: f32) -> Self {
179        std::array::from_fn(|i| self[i].interpolate(&to[i], t))
180    }
181}
182impl<A: Interpolate, B: Interpolate> Interpolate for (A, B) {
183    fn interpolate(&self, to: &Self, t: f32) -> Self {
184        (self.0.interpolate(&to.0, t), self.1.interpolate(&to.1, t))
185    }
186}
187impl<A: Interpolate, B: Interpolate, C: Interpolate> Interpolate for (A, B, C) {
188    fn interpolate(&self, to: &Self, t: f32) -> Self {
189        (
190            self.0.interpolate(&to.0, t),
191            self.1.interpolate(&to.1, t),
192            self.2.interpolate(&to.2, t),
193        )
194    }
195}
196/// `Some` to `Some` interpolates the values. Appearing or disappearing is
197/// discrete: the `from` state is kept until the end of the transition.
198impl<T: Interpolate> Interpolate for Option<T> {
199    fn interpolate(&self, to: &Self, t: f32) -> Self {
200        match (self, to) {
201            (Some(a), Some(b)) => Some(a.interpolate(b, t)),
202            _ if t >= 1.0 => to.clone(),
203            _ => self.clone(),
204        }
205    }
206}
207/// Element-wise for equal lengths; a changed length is discrete like `Option`.
208impl<T: Interpolate> Interpolate for Vec<T> {
209    fn interpolate(&self, to: &Self, t: f32) -> Self {
210        if self.len() != to.len() {
211            return if t >= 1.0 { to.clone() } else { self.clone() };
212        }
213        self.iter()
214            .zip(to)
215            .map(|(a, b)| a.interpolate(b, t))
216            .collect()
217    }
218}