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
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
use std::{
any::TypeId,
collections::HashMap,
fmt::Display,
ops::{Deref, DerefMut},
};
use hecs::World;
use smallvec::SmallVec;
#[cfg(feature = "parallel")]
use rayon::iter::{IntoParallelRefMutIterator, ParallelIterator};
use crate::{
borrow::{Borrows, MaybeWrite},
Access, CommandBuffer, Context, IntoData, Result, System, Write,
};
#[derive(Default, Debug, Clone, PartialEq)]
pub struct BatchInfo {
systems: Vec<SingleBatchInfo>,
}
#[derive(Default, Debug, Clone, Copy, PartialEq)]
struct SingleBatchInfo {
count: usize,
flush: bool,
}
impl Display for BatchInfo {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "Batches: \n")?;
for systems in &self.systems {
write!(f, " - {}", systems.count)?;
if systems.flush {
write!(f, " + flush")?;
}
write!(f, "\n")?
}
Ok(())
}
}
#[derive(Default)]
pub struct Batch {
systems: SmallVec<[DynamicSystem; 8]>,
has_flush: bool,
}
impl Batch {
fn push(&mut self, system: DynamicSystem) {
self.systems.push(system)
}
pub fn systems(&self) -> &SmallVec<[DynamicSystem; 8]> {
&self.systems
}
}
impl Deref for Batch {
type Target = [DynamicSystem];
fn deref(&self) -> &Self::Target {
&self.systems
}
}
impl DerefMut for Batch {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.systems
}
}
#[doc(hidden)]
pub struct DynamicSystem {
func: Box<dyn FnMut(&Context) -> Result<()> + Send>,
borrows: Borrows,
}
#[doc(hidden)]
impl DynamicSystem {
fn new<S, Args, Ret>(mut system: S) -> Self
where
S: 'static + System<Args, Ret> + Send,
{
let borrows = S::borrows();
Self {
func: Box::new(move |context| system.execute(context)),
borrows,
}
}
fn execute(&mut self, context: &Context) -> Result<()> {
(self.func)(context)
}
}
pub struct Schedule {
batches: Vec<Batch>,
cmd: CommandBuffer,
}
impl Schedule {
pub fn new(batches: Vec<Batch>) -> Self {
Self {
batches,
cmd: Default::default(),
}
}
pub fn batch_info(&self) -> BatchInfo {
let systems = self
.batches
.iter()
.map(|val| SingleBatchInfo {
count: val.systems.len(),
flush: val.has_flush,
})
.collect();
BatchInfo { systems }
}
pub fn builder() -> ScheduleBuilder {
ScheduleBuilder::default()
}
pub fn execute_seq<D: IntoData<CommandBuffer>>(&mut self, data: D) -> Result<()> {
let data = unsafe { data.into_data(&mut self.cmd) };
let context = Context::new(&data);
self.batches.iter_mut().try_for_each(|batch| {
batch
.iter_mut()
.try_for_each(|system| system.execute(&context))
})
}
#[cfg(feature = "parallel")]
pub fn execute<D: IntoData<CommandBuffer> + Send + Sync>(&mut self, data: D) -> Result<()> {
let data = unsafe { data.into_data(&mut self.cmd) };
let context = Context::new(&data);
self.batches.iter_mut().try_for_each(|batch| {
batch
.par_iter_mut()
.try_for_each(|system| system.execute(&context))
})
}
pub fn cmd(&self) -> &CommandBuffer {
&self.cmd
}
pub fn cmd_mut(&mut self) -> &mut CommandBuffer {
&mut self.cmd
}
}
#[derive(Default)]
pub struct ScheduleBuilder {
batches: Vec<Batch>,
current_batch: Batch,
current_borrows: HashMap<TypeId, Access>,
}
impl ScheduleBuilder {
pub fn new() -> Self {
Default::default()
}
pub fn add_system<Args, Ret, S>(&mut self, system: S) -> &mut Self
where
S: 'static + System<Args, Ret> + Send,
{
self.add_internal(DynamicSystem::new(system));
self
}
fn add_internal(&mut self, system: DynamicSystem) {
let borrows = &system.borrows;
if self.check_incompatible(borrows) {
self.barrier();
}
self.add_borrows(borrows);
self.current_batch.push(system);
}
pub fn append(&mut self, other: &mut ScheduleBuilder) -> &mut Self {
other.barrier();
other.batches.drain(..).for_each(|mut batch| {
batch
.systems
.drain(..)
.for_each(|system| self.add_internal(system))
});
self
}
pub fn barrier(&mut self) -> &mut Self {
let batch = std::mem::take(&mut self.current_batch);
self.batches.push(batch);
self.current_borrows.clear();
self
}
pub fn flush(&mut self) -> &mut Self {
self.current_batch.has_flush = true;
self.add_system(flush_system)
}
fn add_borrows(&mut self, borrows: &Borrows) {
self.current_borrows
.extend(borrows.into_iter().map(|val| (val.id(), val.clone())))
}
fn check_incompatible(&self, borrows: &Borrows) -> bool {
for borrow in borrows {
if let Some(curr) = self.current_borrows.get(&borrow.id()) {
return curr.exclusive() || borrow.exclusive();
}
}
false
}
pub fn build(&mut self) -> Schedule {
self.flush();
self.barrier();
let builder = std::mem::take(self);
Schedule::new(builder.batches)
}
}
fn flush_system(mut world: MaybeWrite<World>, mut cmd: Write<CommandBuffer>) -> Result<()> {
if let Some(world) = world.option_mut() {
cmd.execute(world);
}
Ok(())
}