1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
use std::cmp::{Eq, Ord, PartialOrd, PartialEq, Ordering};
use linalg;
use film::Colorf;
#[derive(Debug, Copy, Clone)]
pub struct ColorKeyframe {
pub color: Colorf,
pub time: f32,
}
impl ColorKeyframe {
pub fn new(color: &Colorf, time: f32) -> ColorKeyframe {
ColorKeyframe { color: *color, time: time }
}
}
impl Ord for ColorKeyframe {
fn cmp(&self, other: &ColorKeyframe) -> Ordering {
self.partial_cmp(other).unwrap()
}
}
impl PartialOrd for ColorKeyframe {
fn partial_cmp(&self, other: &ColorKeyframe) -> Option<Ordering> {
self.time.partial_cmp(&other.time)
}
}
impl Eq for ColorKeyframe {}
impl PartialEq for ColorKeyframe {
fn eq(&self, other: &ColorKeyframe) -> bool {
self.time == other.time
}
}
#[derive(Debug, Clone)]
pub struct AnimatedColor {
keyframes: Vec<ColorKeyframe>,
}
impl AnimatedColor {
pub fn with_keyframes(mut keyframes: Vec<ColorKeyframe>) -> AnimatedColor {
keyframes.sort();
AnimatedColor { keyframes: keyframes }
}
pub fn color(&self, time: f32) -> Colorf {
if self.keyframes.is_empty() {
Colorf::black()
} else if self.keyframes.len() == 1 {
self.keyframes[0].color
} else {
let first = self.keyframes.iter().take_while(|k| k.time < time).last();
let second = self.keyframes.iter().skip_while(|k| k.time < time).next();
if first.is_none() {
self.keyframes.first().unwrap().color
} else if second.is_none() {
self.keyframes.last().unwrap().color
} else {
let mut color = Colorf::black();
let fk = first.unwrap();
let sk = second.unwrap();
let t = (time - fk.time) / (sk.time - fk.time);
color.r = linalg::lerp(t, &fk.color.r, &sk.color.r);
color.g = linalg::lerp(t, &fk.color.g, &sk.color.g);
color.b = linalg::lerp(t, &fk.color.b, &sk.color.b);
color.a = linalg::lerp(t, &fk.color.a, &sk.color.a);
color
}
}
}
}