1use std::collections::VecDeque;
4use std::marker::PhantomData;
5
6use crate::prelude::*;
7
8pub struct SystemStages {
10 stages: Vec<Box<dyn SystemStage>>,
12}
13
14impl Default for SystemStages {
15 fn default() -> Self {
16 Self::with_core_stages()
17 }
18}
19
20impl SystemStages {
21 pub fn with_core_stages() -> Self {
23 Self {
24 stages: vec![
25 Box::new(
26 StartupSystemStage::<CoreStageStartupResourceSystemsRan>::new(
27 CoreStage::StartupResource,
28 ),
29 ),
30 Box::new(StartupSystemStage::<CoreStageStartupSystemsRan>::new(
31 CoreStage::Startup,
32 )),
33 Box::new(SimpleSystemStage::new(CoreStage::First)),
34 Box::new(SimpleSystemStage::new(CoreStage::PreUpdate)),
35 Box::new(SimpleSystemStage::new(CoreStage::Update)),
36 Box::new(SimpleSystemStage::new(CoreStage::PostUpdate)),
37 Box::new(SimpleSystemStage::new(CoreStage::Last)),
38 ],
39 }
40 }
41
42 pub fn add_system_to_stage<Args, S>(&mut self, label: impl StageLabel, system: S) -> &mut Self
44 where
45 S: IntoSystem<Args, (), (), Sys = StaticSystem<(), ()>>,
46 {
47 let name = label.name();
48 let id = label.id();
49 let mut stage = None;
50
51 for st in &mut self.stages {
52 if st.id() == id {
53 stage = Some(st);
54 }
55 }
56
57 let Some(stage) = stage else {
58 panic!("Stage with label `{}` ( {} ) doesn't exist.", name, id);
59 };
60
61 stage.add_system(system.system());
62
63 self
64 }
65
66 #[track_caller]
68 pub fn insert_stage_before<L: StageLabel, S: SystemStage + 'static>(
69 &mut self,
70 label: L,
71 stage: S,
72 ) -> &mut Self {
73 let stage_idx = self
74 .stages
75 .iter()
76 .position(|x| x.id() == label.id())
77 .unwrap_or_else(|| panic!("Could not find stage with label `{}`", label.name()));
78 self.stages.insert(stage_idx, Box::new(stage));
79
80 self
81 }
82
83 #[track_caller]
85 pub fn insert_stage_after<L: StageLabel, S: SystemStage + 'static>(
86 &mut self,
87 label: L,
88 stage: S,
89 ) -> &mut Self {
90 let stage_idx = self
91 .stages
92 .iter()
93 .position(|x| x.id() == label.id())
94 .unwrap_or_else(|| panic!("Could not find stage with label `{}`", label.name()));
95 self.stages.insert(stage_idx + 1, Box::new(stage));
96
97 self
98 }
99
100 pub fn run(&mut self, world: &mut World) {
102 for stage in &mut self.stages {
103 stage.run(world);
104 }
105 world.maintain();
107 }
108
109 #[deprecated = "use `.add_system_to_stage(CoreStage::Startup, your_system)` instead"]
113 pub fn add_startup_system<Args, S>(&mut self, system: S) -> &mut Self
114 where
115 S: IntoSystem<Args, (), (), Sys = StaticSystem<(), ()>>,
116 {
117 self.add_system_to_stage(CoreStage::Startup, system.system());
118 self
119 }
120
121 #[deprecated = "use `.add_system_to_stage(First, single_success_system(your_system)"]
127 pub fn add_single_success_system<Args, S>(&mut self, system: S) -> &mut Self
128 where
129 S: IntoSystem<Args, (), Option<()>, Sys = StaticSystem<(), Option<()>>>,
130 {
131 self.add_system_to_stage(First, single_success_system(system));
132 self
133 }
134
135 pub fn init_startup_resource<R: HasSchema + FromWorld>(&mut self) -> &mut Self {
138 self.add_system_to_stage(StartupResource, |world: &World| {
139 world.init_resource::<R>();
140 });
141 self
142 }
143
144 pub fn add_startup_resource<R: HasSchema>(&mut self, resource: R) -> &mut Self {
164 let mut once = Some(SchemaBox::new(resource));
165
166 self.add_system_to_stage(StartupResource, move |world: &World| {
167 if !world.resources.contains::<R>() {
168 let schema_box = if R::schema().clone_fn.is_some() {
169 once.clone()
170 } else {
171 once.take()
172 };
173
174 if let Some(schema_box) = schema_box {
175 world
176 .resources
177 .untyped()
178 .get(R::schema())
179 .insert(schema_box)
180 .unwrap();
181 } else {
182 panic!(
183 "The schema for this type does not allow cloning it.\nSchema: {:#?}; \
184 You may need to add the resource to the `ResetWorld::reset_resources` \
185 to avoid cloning on startup.",
186 R::schema()
187 )
188 };
189 }
190 });
191 self
192 }
193}
194
195impl std::fmt::Debug for SystemStages {
196 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
197 f.debug_struct("SystemStages")
198 .finish()
202 }
203}
204
205pub trait SystemStage: Sync + Send {
207 fn id(&self) -> Ulid;
209 fn name(&self) -> String;
211 fn run(&mut self, world: &World);
213
214 fn add_system(&mut self, system: StaticSystem<(), ()>);
216 fn remove_all_systems(&mut self);
218}
219
220pub struct SimpleSystemStage {
222 pub id: Ulid,
224 pub name: String,
226 pub systems: Vec<StaticSystem<(), ()>>,
230}
231
232impl SimpleSystemStage {
233 pub fn new<L: StageLabel>(label: L) -> Self {
235 Self {
236 id: label.id(),
237 name: label.name(),
238 systems: Default::default(),
239 }
240 }
241}
242
243impl SystemStage for SimpleSystemStage {
244 fn id(&self) -> Ulid {
245 self.id
246 }
247
248 fn name(&self) -> String {
249 self.name.clone()
250 }
251
252 fn run(&mut self, world: &World) {
253 for system in &mut self.systems {
255 system.run(world, ());
256 }
257
258 let queue = world.resources.get_mut::<CommandQueue>();
260 if let Some(mut command_queue) = queue {
261 for mut system in command_queue.queue.drain(..) {
262 system.run(world, ());
263 }
264 }
265 }
266
267 fn add_system(&mut self, system: StaticSystem<(), ()>) {
268 self.systems.push(system);
269 }
270
271 fn remove_all_systems(&mut self) {
272 self.systems.clear();
273 }
274}
275
276#[derive(HasSchema, Clone, Default, Debug)]
279pub struct CoreStageStartupSystemsRan;
280
281#[derive(HasSchema, Clone, Default, Debug)]
284pub struct CoreStageStartupResourceSystemsRan;
285
286pub struct StartupSystemStage<T: HasSchema + Default + Clone> {
288 pub id: Ulid,
290 pub name: String,
292 pub systems: Vec<StaticSystem<(), ()>>,
296 _phantom_data: PhantomData<T>,
297}
298impl<T: HasSchema + Clone + Default> StartupSystemStage<T> {
299 pub fn new<L: StageLabel>(label: L) -> Self {
301 Self {
302 id: label.id(),
303 name: label.name(),
304 systems: Default::default(),
305 _phantom_data: PhantomData,
306 }
307 }
308}
309impl<T: HasSchema + Clone + Default> SystemStage for StartupSystemStage<T> {
310 fn id(&self) -> Ulid {
311 self.id
312 }
313
314 fn name(&self) -> String {
315 self.name.clone()
316 }
317
318 fn run(&mut self, world: &World) {
319 if world.get_resource_mut::<T>().is_none() {
320 for system in &mut self.systems {
322 system.run(world, ());
323 }
324 world.insert_resource(T::default());
325 }
326
327 let queue = world.resources.get_mut::<CommandQueue>();
329 if let Some(mut command_queue) = queue {
330 for mut system in command_queue.queue.drain(..) {
331 system.run(world, ());
332 }
333 }
334 }
335
336 fn add_system(&mut self, system: StaticSystem<(), ()>) {
337 self.systems.push(system);
338 }
339
340 fn remove_all_systems(&mut self) {
341 self.systems.clear();
342 }
343}
344
345pub fn single_success_system<Args, S>(system: S) -> StaticSystem<(), ()>
353where
354 S: IntoSystem<Args, (), Option<()>, Sys = StaticSystem<(), Option<()>>>,
355{
356 use std::sync::atomic::{AtomicU64, Ordering};
357 static SINGLE_SUCCESS_SYSTEM_ID_GEN: AtomicU64 = AtomicU64::new(0);
358
359 let id = SINGLE_SUCCESS_SYSTEM_ID_GEN.fetch_add(1, Ordering::SeqCst);
360 let mut system = system.system();
361 (move |world: &World| {
362 if !world.init_resource::<SingleSuccessSystems>().contains(&id)
363 && system.run(world, ()).is_some()
364 {
365 world.init_resource::<SingleSuccessSystems>().insert(id);
366 }
367 })
368 .system()
369}
370
371#[derive(HasSchema, Clone, Default, Deref, DerefMut)]
374pub struct SingleSuccessSystems(pub HashSet<u64>);
375
376pub trait StageLabel {
378 fn name(&self) -> String;
380 fn id(&self) -> Ulid;
382}
383
384#[derive(Copy, Clone, Debug, PartialEq, Eq)]
386pub enum CoreStage {
387 StartupResource,
389 Startup,
391 First,
393 PreUpdate,
395 Update,
397 PostUpdate,
399 Last,
401}
402
403impl StageLabel for CoreStage {
404 fn name(&self) -> String {
405 format!("{:?}", self)
406 }
407
408 fn id(&self) -> Ulid {
409 match self {
410 CoreStage::StartupResource => Ulid(2162940536129995539438442124983465554),
411 CoreStage::Startup => Ulid(2149923225027836290977818907354065512),
412 CoreStage::First => Ulid(2021715391084198804812356024998495966),
413 CoreStage::PreUpdate => Ulid(2021715401330719559452824437611089988),
414 CoreStage::Update => Ulid(2021715410160177201728645950400543948),
415 CoreStage::PostUpdate => Ulid(2021715423103233646561968734173322317),
416 CoreStage::Last => Ulid(2021715433398666914977687392909851554),
417 }
418 }
419}
420
421#[derive(HasSchema, Default)]
425pub struct CommandQueue {
426 pub queue: VecDeque<StaticSystem<(), ()>>,
428}
429
430impl Clone for CommandQueue {
431 fn clone(&self) -> Self {
432 if self.queue.is_empty() {
433 Self {
434 queue: VecDeque::with_capacity(self.queue.capacity()),
435 }
436 } else {
437 panic!(
438 "Cannot clone CommandQueue. This probably happened because you are \
439 trying to clone a World while a system stage is still executing."
440 )
441 }
442 }
443}
444
445impl CommandQueue {
446 pub fn add<Args, S>(&mut self, system: S)
448 where
449 S: IntoSystem<Args, (), (), Sys = StaticSystem<(), ()>>,
450 {
451 self.queue.push_back(system.system());
452 }
453}
454
455#[derive(Deref, DerefMut)]
460pub struct Commands<'a>(RefMut<'a, CommandQueue>);
461
462impl<'a> SystemParam for Commands<'a> {
463 type State = AtomicResource<CommandQueue>;
464 type Param<'s> = Commands<'s>;
465
466 fn get_state(world: &World) -> Self::State {
467 let cell = world.resources.get_cell::<CommandQueue>();
468 cell.init(world);
469 cell
470 }
471
472 fn borrow<'s>(_world: &'s World, state: &'s mut Self::State) -> Self::Param<'s> {
473 Commands(state.borrow_mut().unwrap())
474 }
475}