use core::future::Future;
use core::pin::Pin;
use core::task::{Context, Poll};
use core::time::Duration;
use crate::engine::VeloxEngine;
use crate::platform::{AsyncPlatform, PlatformControlFlow};
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
pub struct SchedulerCapabilities {
pub name: &'static str,
pub supports_background_threads: bool,
pub supports_dynamic_spawn: bool,
pub deterministic_clock: bool,
}
#[derive(Default)]
pub struct YieldNow {
yielded: bool,
}
impl YieldNow {
#[inline(always)]
pub const fn new() -> Self {
Self { yielded: false }
}
}
impl Unpin for YieldNow {}
impl Future for YieldNow {
type Output = ();
#[inline]
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
if self.yielded {
Poll::Ready(())
} else {
self.yielded = true;
cx.waker().wake_by_ref();
Poll::Pending
}
}
}
pub trait SchedulerClock {
fn now_ms(&self) -> u64;
fn sleep(&self, duration: Duration) -> impl Future<Output = ()>;
}
pub trait AsyncDriver: SchedulerClock {
fn capabilities(&self) -> SchedulerCapabilities;
fn wait_for_event(&self) -> impl Future<Output = ()>;
#[inline]
fn yield_now(&self) -> impl Future<Output = ()> {
YieldNow::new()
}
}
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
pub struct AsyncLoopConfig {
pub frame_interval: Duration,
pub max_steps: Option<u32>,
pub exit_on_idle: bool,
}
impl Default for AsyncLoopConfig {
#[inline(always)]
fn default() -> Self {
Self {
frame_interval: Duration::from_millis(16),
max_steps: None,
exit_on_idle: false,
}
}
}
impl AsyncLoopConfig {
#[inline(always)]
pub const fn new(frame_interval: Duration) -> Self {
Self {
frame_interval,
max_steps: None,
exit_on_idle: false,
}
}
#[inline(always)]
pub const fn with_max_steps(mut self, max_steps: u32) -> Self {
self.max_steps = Some(max_steps);
self
}
#[inline(always)]
pub const fn with_exit_on_idle(mut self, exit_on_idle: bool) -> Self {
self.exit_on_idle = exit_on_idle;
self
}
}
#[derive(Copy, Clone, PartialEq, Eq, Debug, Default)]
pub struct AsyncLoopReport {
pub steps: u32,
pub idle_waits: u32,
pub last_control_flow: Option<PlatformControlFlow>,
}
pub async fn run_async_event_loop<P, D>(
platform: &mut P,
engine: &mut VeloxEngine,
driver: &D,
config: AsyncLoopConfig,
) -> AsyncLoopReport
where
P: AsyncPlatform,
D: AsyncDriver,
{
let mut report = AsyncLoopReport::default();
let mut last_ms = driver.now_ms();
let frame_ms = config.frame_interval.as_millis().min(u64::MAX as u128) as u64;
loop {
if let Some(limit) = config.max_steps {
if report.steps >= limit {
break;
}
}
let step_start_ms = driver.now_ms();
let dt_ms = step_start_ms.saturating_sub(last_ms).clamp(1, 100) as u16;
last_ms = step_start_ms;
let flow = platform.step_platform_async(engine, dt_ms).await;
report.steps = report.steps.saturating_add(1);
report.last_control_flow = Some(flow);
match flow {
PlatformControlFlow::Exit => break,
PlatformControlFlow::Wait => {
if engine.needs_redraw() {
driver.yield_now().await;
continue;
}
report.idle_waits = report.idle_waits.saturating_add(1);
if config.exit_on_idle {
break;
}
driver.wait_for_event().await;
last_ms = driver.now_ms();
}
PlatformControlFlow::Poll => {
let elapsed_ms = driver.now_ms().saturating_sub(step_start_ms);
if frame_ms > 0 && elapsed_ms < frame_ms {
driver
.sleep(Duration::from_millis(frame_ms - elapsed_ms))
.await;
} else {
driver.yield_now().await;
}
}
}
}
report
}