-
Notifications
You must be signed in to change notification settings - Fork 85
/
Copy pathchange_tracker.rs
212 lines (188 loc) · 6.76 KB
/
change_tracker.rs
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
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
use core::mem;
use alloc::vec::Vec;
use crate::{Component, Entity, PreparedQuery, With, Without, World};
/// Helper to track changes in `T` components
///
/// For each entity with a `T` component, a private component is inserted which stores the value as
/// of the most recent call to `track`. This provides robust, exact change detection at the cost of
/// visiting each possibly-changed entity. It is a good fit for entities that will typically be
/// visited regardless, and components having fast [`Clone`] and [`PartialEq`] impls. For components
/// which are expensive to compare and/or clone, consider instead tracking changes manually, e.g.
/// by setting a flag in the component's `DerefMut` implementation.
///
/// Always use exactly one `ChangeTracker` per [`World`] per component type of interest. Using
/// multiple trackers of the same `T` on the same world, or using the same tracker across multiple
/// worlds, will produce unpredictable results.
pub struct ChangeTracker<T: Component> {
added: PreparedQuery<Without<&'static T, &'static Previous<T>>>,
changed: PreparedQuery<(&'static T, &'static mut Previous<T>)>,
removed: PreparedQuery<Without<With<(), &'static Previous<T>>, &'static T>>,
added_components: Vec<(Entity, T)>,
removed_components: Vec<Entity>,
}
impl<T: Component> ChangeTracker<T> {
/// Create a change tracker for `T` components
pub fn new() -> Self {
Self {
added: PreparedQuery::new(),
changed: PreparedQuery::new(),
removed: PreparedQuery::new(),
added_components: Vec::new(),
removed_components: Vec::new(),
}
}
/// Determine the changes in `T` components in `world` since the previous call
pub fn track<'a>(&'a mut self, world: &'a mut World) -> Changes<'a, T>
where
T: Clone + PartialEq,
{
Changes {
tracker: self,
world,
added: false,
changed: false,
removed: false,
}
}
}
impl<T: Component> Default for ChangeTracker<T> {
fn default() -> Self {
Self::new()
}
}
struct Previous<T>(T);
/// Collection of iterators over changes in `T` components
pub struct Changes<'a, T>
where
T: Component + Clone + PartialEq,
{
tracker: &'a mut ChangeTracker<T>,
world: &'a mut World,
added: bool,
changed: bool,
removed: bool,
}
impl<T> Changes<'_, T>
where
T: Component + Clone + PartialEq,
{
/// Iterate over entities which were given a new `T` component after the preceding
/// [`track`](ChangeTracker::track) call, including newly spawned entities
pub fn added(&mut self) -> impl ExactSizeIterator<Item = (Entity, &T)> + '_ {
self.tracker.added_components.clear();
self.added = true;
DrainOnDrop(
self.tracker
.added
.query_mut(self.world)
.inspect(|&(e, x)| self.tracker.added_components.push((e, x.clone()))),
)
}
/// Iterate over `(entity, old, new)` for entities whose `T` component has changed according to
/// [`PartialEq`] after the preceding [`track`](ChangeTracker::track) call
pub fn changed(&mut self) -> impl Iterator<Item = (Entity, T, &T)> + '_ {
self.changed = true;
DrainOnDrop(
self.tracker
.changed
.query_mut(self.world)
.filter_map(|(e, (new, old))| {
(*new != old.0).then(|| {
let old = mem::replace(&mut old.0, new.clone());
(e, old, new)
})
}),
)
}
/// Iterate over entities which lost their `T` component after the preceding
/// [`track`](ChangeTracker::track) call, excluding any entities which were despawned
pub fn removed(&mut self) -> impl ExactSizeIterator<Item = (Entity, T)> + '_ {
self.tracker.removed_components.clear();
self.removed = true;
// TODO: We could make this much more efficient by introducing a mechanism for queries to
// take ownership of components directly.
self.tracker
.removed_components
.extend(self.tracker.removed.query_mut(self.world).map(|(e, ())| e));
DrainOnDrop(
self.tracker
.removed_components
.drain(..)
.map(|e| (e, self.world.remove_one::<Previous<T>>(e).unwrap().0)),
)
}
}
impl<T: Component> Drop for Changes<'_, T>
where
T: Component + Clone + PartialEq,
{
fn drop(&mut self) {
if !self.added {
_ = self.added();
}
for (entity, component) in self.tracker.added_components.drain(..) {
self.world.insert_one(entity, Previous(component)).unwrap();
}
if !self.changed {
_ = self.changed();
}
if !self.removed {
_ = self.removed();
}
}
}
/// Helper to ensure an iterator visits every element so that we can rely on the iterator's side
/// effects
struct DrainOnDrop<T: Iterator>(T);
impl<T: Iterator> Iterator for DrainOnDrop<T> {
type Item = T::Item;
fn next(&mut self) -> Option<Self::Item> {
self.0.next()
}
}
impl<T: ExactSizeIterator> ExactSizeIterator for DrainOnDrop<T> {
fn len(&self) -> usize {
self.0.len()
}
}
impl<T: Iterator> Drop for DrainOnDrop<T> {
fn drop(&mut self) {
for _ in &mut self.0 {}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn smoke() {
let mut world = World::new();
let a = world.spawn((42,));
let b = world.spawn((17, false));
let c = world.spawn((true,));
let mut tracker = ChangeTracker::<i32>::new();
{
let mut changes = tracker.track(&mut world);
let added = changes.added().collect::<Vec<_>>();
assert_eq!(added.len(), 2);
assert!(added.contains(&(a, &42)));
assert!(added.contains(&(b, &17)));
assert_eq!(changes.changed().count(), 0);
assert_eq!(changes.removed().count(), 0);
}
world.remove_one::<i32>(a).unwrap();
*world.get::<&mut i32>(b).unwrap() = 26;
world.insert_one(c, 74).unwrap();
{
let mut changes = tracker.track(&mut world);
assert_eq!(changes.removed().collect::<Vec<_>>(), [(a, 42)]);
assert_eq!(changes.changed().collect::<Vec<_>>(), [(b, 17, &26)]);
assert_eq!(changes.added().collect::<Vec<_>>(), [(c, &74)]);
}
{
let mut changes = tracker.track(&mut world);
assert_eq!(changes.removed().collect::<Vec<_>>(), []);
assert_eq!(changes.changed().collect::<Vec<_>>(), []);
assert_eq!(changes.added().collect::<Vec<_>>(), []);
}
}
}