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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
use std::time::{ Duration };
use dotrix_math::{ SquareMatrix, Mat4 };
use crate::{ Pose, Id, Assets, Frame, World };
use crate::assets::Animation;
use crate::ecs::Const;
#[derive(Copy, Clone, Eq, PartialEq)]
pub enum State {
Play(Duration),
Loop(Duration),
Stop,
}
pub struct Animator {
animation: Id<Animation>,
state: State,
pub speed: f32,
}
impl Animator {
pub fn new(animation: Id<Animation>) -> Self {
Self {
animation,
state: State::Stop,
speed: 1.0,
}
}
pub fn play(animation: Id<Animation>) -> Self {
Self {
animation,
state: State::Play(Duration::from_secs(0)),
speed: 1.0,
}
}
pub fn looped(animation: Id<Animation>) -> Self {
Self {
animation,
state: State::Loop(Duration::from_secs(0)),
speed: 1.0,
}
}
pub fn start(&mut self) {
self.state = State::Play(Duration::from_secs(0));
}
pub fn start_loop(&mut self) {
self.state = State::Loop(Duration::from_secs(0));
}
pub fn stop(&mut self) {
self.state = State::Stop;
}
pub fn animate(&mut self, animation: Id<Animation>) {
self.animation = animation;
self.state = State::Stop;
}
pub fn animation(&self) -> Id<Animation> {
self.animation
}
pub fn state(&self) -> State {
self.state
}
fn update(&mut self, delta: Duration, duration: Duration) -> Option<Duration> {
self.state = match self.state {
State::Play(current) => {
let new_duration = current + delta.mul_f32(self.speed);
if new_duration < duration {
State::Play(new_duration)
} else {
State::Stop
}
},
State::Loop(current) => {
let new_duration = current + delta.mul_f32(self.speed);
State::Loop(
if new_duration < duration {
new_duration
} else {
Duration::from_secs_f32(new_duration.as_secs_f32() % duration.as_secs_f32())
}
)
},
State::Stop => State::Stop
};
match self.state {
State::Play(current) => Some(current),
State::Loop(current) => Some(current),
State::Stop => None,
}
}
}
pub fn skeletal(frame: Const<Frame>, world: Const<World>, assets: Const<Assets>) {
for (animator, pose) in world.query::<(&mut Animator, &mut Pose)>() {
let global_transform = Mat4::identity();
if let Some(skin) = assets.get(pose.skin) {
let mut local_transforms = None;
if let Some(animation) = assets.get::<Animation>(animator.animation) {
if let Some(duration) = animator.update(frame.delta(), animation.duration()) {
local_transforms = Some(animation.sample(duration.as_secs_f32()));
}
}
skin.transform(pose, &global_transform, local_transforms);
}
}
}