use bevy_ecs::prelude::World;
use std::future::Future;
#[cfg(feature = "single_threaded_async")]
mod single_threaded_execution;
#[cfg(feature = "single_threaded_async")]
pub(crate) use single_threaded_execution::SingleThreadedExecution;
#[cfg(feature = "single_threaded_async")]
use single_threaded_execution::SingleThreadedExecutionSender;
pub(crate) use bevy_tasks::Task as TaskHandle;
#[cfg(not(feature = "single_threaded_async"))]
pub(crate) type CancelSender = AsyncComputeTaskPoolSender;
#[cfg(feature = "single_threaded_async")]
pub(crate) type CancelSender = SingleThreadedExecutionSender;
pub(crate) fn spawn_task<T>(
future: impl Future<Output = T> + Sendish + 'static,
_world: &mut World,
) -> TaskHandle<T>
where
T: Send + 'static,
{
#[cfg(not(feature = "single_threaded_async"))]
{
use bevy_tasks::AsyncComputeTaskPool;
AsyncComputeTaskPool::get().spawn(future)
}
#[cfg(feature = "single_threaded_async")]
{
SingleThreadedExecution::get(_world).spawn(future)
}
}
pub(crate) fn task_cancel_sender(_world: &mut World) -> CancelSender {
#[cfg(not(feature = "single_threaded_async"))]
{
AsyncComputeTaskPoolSender
}
#[cfg(feature = "single_threaded_async")]
{
SingleThreadedExecution::get(_world).cancel_sender()
}
}
#[cfg(not(feature = "single_threaded_async"))]
pub(crate) struct AsyncComputeTaskPoolSender;
#[cfg(not(feature = "single_threaded_async"))]
impl AsyncComputeTaskPoolSender {
pub(crate) fn send<F>(&self, f: impl FnOnce() -> F)
where
F: Future + Send + 'static,
F::Output: Send + 'static,
{
use bevy_tasks::AsyncComputeTaskPool;
AsyncComputeTaskPool::get().spawn(f()).detach();
}
}
#[cfg(not(feature = "single_threaded_async"))]
pub trait Sendish: Send {}
#[cfg(not(feature = "single_threaded_async"))]
impl<T: Send> Sendish for T {}
#[cfg(feature = "single_threaded_async")]
pub trait Sendish {}
#[cfg(feature = "single_threaded_async")]
impl<T> Sendish for T {}