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
use std::{fmt, rc::Rc};
use crate::engine::d2::{util::Disposable, Component};
use super::Action;
/// Manages a set of actions that are updated over time. Scripts simplify writing composable
/// animations.
pub struct Script {
pub inner: Component,
handles: Vec<Handle>,
}
impl Script {
pub fn new() -> Self {
Self {
inner: Component::default(),
handles: Vec::new(),
}
}
/// Add an action to this Script.
/// @returns A handle that can be disposed to stop the action.
pub fn run(&mut self, action: Rc<dyn Action>) -> impl Disposable {
let handle = Handle::new(action);
self.handles.push(handle.clone());
handle
}
/// Remove all actions from this Script.
pub fn stop_all(&mut self) {
self.handles.clear();
}
// override
pub fn on_update(&mut self, dt: f32) {
let mut idx = 0;
while idx < self.handles.len() {
if let Some(handle) = self.handles.get_mut(idx) {
// removed mean action is none
if let Some(ref mut action) = handle.action {
if let Some(owner) = self.inner.owner {
let entity = owner.entity();
if action.update(dt, &mut owner.entity()) >= 0.0 {
self.handles.remove(idx);
} else {
idx += 1;
}
} else {
idx += 1;
}
} else {
idx += 1;
}
}
}
}
}
impl AsRef<Component> for Script {
fn as_ref(&self) -> &Component {
&self.inner
}
}
#[derive(Default, Clone)]
pub struct Handle {
pub action: Option<Rc<dyn Action>>,
}
impl Handle {
pub fn new(action: Rc<dyn Action>) -> Self {
Self {
action: Some(action),
}
}
}
impl Disposable for Handle {
fn dispose(&self) {
// TODO: should deal with it
// self.action = None;
}
}
impl fmt::Debug for Handle {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Handle")
// .field("x", &self.x)
// .field("y", &self.y)
.finish()
}
}