bevy_tasks/
usages.rs

1use super::TaskPool;
2use std::{ops::Deref, sync::OnceLock};
3
4macro_rules! taskpool {
5    ($(#[$attr:meta])* ($static:ident, $type:ident)) => {
6        static $static: OnceLock<$type> = OnceLock::new();
7
8        $(#[$attr])*
9        #[derive(Debug)]
10        pub struct $type(TaskPool);
11
12        impl $type {
13            #[doc = concat!(" Gets the global [`", stringify!($type), "`] instance, or initializes it with `f`.")]
14            pub fn get_or_init(f: impl FnOnce() -> TaskPool) -> &'static Self {
15                $static.get_or_init(|| Self(f()))
16            }
17
18            #[doc = concat!(" Attempts to get the global [`", stringify!($type), "`] instance, \
19                or returns `None` if it is not initialized.")]
20            pub fn try_get() -> Option<&'static Self> {
21                $static.get()
22            }
23
24            #[doc = concat!(" Gets the global [`", stringify!($type), "`] instance.")]
25            #[doc = ""]
26            #[doc = " # Panics"]
27            #[doc = " Panics if the global instance has not been initialized yet."]
28            pub fn get() -> &'static Self {
29                $static.get().expect(
30                    concat!(
31                        "The ",
32                        stringify!($type),
33                        " has not been initialized yet. Please call ",
34                        stringify!($type),
35                        "::get_or_init beforehand."
36                    )
37                )
38            }
39        }
40
41        impl Deref for $type {
42            type Target = TaskPool;
43
44            fn deref(&self) -> &Self::Target {
45                &self.0
46            }
47        }
48    };
49}
50
51taskpool! {
52    /// A newtype for a task pool for CPU-intensive work that must be completed to
53    /// deliver the next frame
54    ///
55    /// See [`TaskPool`] documentation for details on Bevy tasks.
56    /// [`AsyncComputeTaskPool`] should be preferred if the work does not have to be
57    /// completed before the next frame.
58    (COMPUTE_TASK_POOL, ComputeTaskPool)
59}
60
61taskpool! {
62    /// A newtype for a task pool for CPU-intensive work that may span across multiple frames
63    ///
64    /// See [`TaskPool`] documentation for details on Bevy tasks.
65    /// Use [`ComputeTaskPool`] if the work must be complete before advancing to the next frame.
66    (ASYNC_COMPUTE_TASK_POOL, AsyncComputeTaskPool)
67}
68
69taskpool! {
70    /// A newtype for a task pool for IO-intensive work (i.e. tasks that spend very little time in a
71    /// "woken" state)
72    ///
73    /// See [`TaskPool`] documentation for details on Bevy tasks.
74    (IO_TASK_POOL, IoTaskPool)
75}
76
77/// A function used by `bevy_core` to tick the global tasks pools on the main thread.
78/// This will run a maximum of 100 local tasks per executor per call to this function.
79///
80/// # Warning
81///
82/// This function *must* be called on the main thread, or the task pools will not be updated appropriately.
83#[cfg(not(target_arch = "wasm32"))]
84pub fn tick_global_task_pools_on_main_thread() {
85    COMPUTE_TASK_POOL
86        .get()
87        .unwrap()
88        .with_local_executor(|compute_local_executor| {
89            ASYNC_COMPUTE_TASK_POOL
90                .get()
91                .unwrap()
92                .with_local_executor(|async_local_executor| {
93                    IO_TASK_POOL
94                        .get()
95                        .unwrap()
96                        .with_local_executor(|io_local_executor| {
97                            for _ in 0..100 {
98                                compute_local_executor.try_tick();
99                                async_local_executor.try_tick();
100                                io_local_executor.try_tick();
101                            }
102                        });
103                });
104        });
105}