mod registry;
#[cfg(test)]
mod tests;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::Arc;
#[cfg(not(target_arch = "wasm32"))]
use std::time::Instant;
use nativeview_abi::{
NvTickOutcome, NV_TICK_DEMAND_AFTER_MS, NV_TICK_DEMAND_IDLE, NV_TICK_DEMAND_NEXT_FRAME,
};
use nativeview_store::{ChangeSet, NodeStore, Transaction};
pub use registry::FrameTickRegistry;
pub const MAX_DT_S: f32 = 0.1;
#[inline]
pub fn clamp_dt_s(dt_s: f32) -> f32 {
if dt_s.is_finite() && dt_s > 0.0 {
dt_s.min(MAX_DT_S)
} else {
0.0
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum TickDemand {
#[default]
Idle,
NextFrame,
AfterMs(u32),
}
impl TickDemand {
#[inline]
pub const fn normalize(self) -> Self {
match self {
Self::AfterMs(0) => Self::NextFrame,
other => other,
}
}
#[inline]
pub const fn merge(self, other: Self) -> Self {
match (self.normalize(), other.normalize()) {
(Self::NextFrame, _) | (_, Self::NextFrame) => Self::NextFrame,
(Self::AfterMs(a), Self::AfterMs(b)) => {
Self::AfterMs(if a < b { a } else { b })
}
(Self::AfterMs(ms), Self::Idle) | (Self::Idle, Self::AfterMs(ms)) => {
Self::AfterMs(ms)
}
(Self::Idle, Self::Idle) => Self::Idle,
}
}
#[inline]
pub const fn is_idle(self) -> bool {
matches!(self, Self::Idle)
}
#[inline]
pub const fn to_abi(self) -> (u32, u32) {
match self.normalize() {
Self::Idle => (NV_TICK_DEMAND_IDLE, 0),
Self::NextFrame => (NV_TICK_DEMAND_NEXT_FRAME, 0),
Self::AfterMs(ms) => (NV_TICK_DEMAND_AFTER_MS, ms),
}
}
#[inline]
pub const fn from_outcome(outcome: NvTickOutcome) -> Option<Self> {
match outcome.demand {
NV_TICK_DEMAND_IDLE => Some(Self::Idle),
NV_TICK_DEMAND_NEXT_FRAME => Some(Self::NextFrame),
NV_TICK_DEMAND_AFTER_MS => Some(Self::AfterMs(outcome.next_tick_ms).normalize()),
_ => None,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct TickPriority(pub i16);
impl Default for TickPriority {
#[inline]
fn default() -> Self {
Self::NORMAL
}
}
impl TickPriority {
pub const INPUT: Self = Self(-100);
pub const PHYSICS: Self = Self(0);
pub const NORMAL: Self = Self(0);
pub const MOTION: Self = Self(10);
pub const TIMER: Self = Self(50);
}
#[repr(transparent)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct TickHookId(u64);
impl TickHookId {
#[inline]
pub(crate) const fn new(raw: u64) -> Self {
Self(raw)
}
#[inline]
pub const fn raw(self) -> u64 {
self.0
}
}
pub trait FrameTickHook: Send {
#[inline]
fn demand(&self) -> TickDemand {
TickDemand::NextFrame
}
#[inline]
fn demand_on_commit(&self, _store: &NodeStore, _changes: &ChangeSet) -> TickDemand {
self.demand()
}
fn tick(&mut self, tx: &mut Transaction<'_>, dt_s: f32, now_ms: u64) -> TickDemand;
}
#[derive(Debug, Clone, Copy)]
pub enum WallClock {
#[cfg(not(target_arch = "wasm32"))]
System,
OffsetMs(i64),
Custom(fn(u64) -> i64),
}
impl WallClock {
#[cfg(not(target_arch = "wasm32"))]
#[inline]
pub const fn system() -> Self {
Self::System
}
#[inline]
pub const fn offset_ms(epoch_ms_at_zero: i64) -> Self {
Self::OffsetMs(epoch_ms_at_zero)
}
#[inline]
pub const fn custom(f: fn(u64) -> i64) -> Self {
Self::Custom(f)
}
#[inline]
pub fn now_epoch_ms(self, now_ms: u64) -> i64 {
match self {
#[cfg(not(target_arch = "wasm32"))]
Self::System => {
let _ = now_ms;
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map_or(0, |d| i64::try_from(d.as_millis()).unwrap_or(i64::MAX))
}
Self::OffsetMs(base) => {
base.saturating_add(i64::try_from(now_ms).unwrap_or(i64::MAX))
}
Self::Custom(f) => f(now_ms),
}
}
}
#[derive(Debug, Default, Clone, Copy)]
pub struct FrameClock {
#[cfg(not(target_arch = "wasm32"))]
last_tick: Option<Instant>,
last_now_s: Option<f64>,
}
impl FrameClock {
#[inline]
pub const fn new() -> Self {
Self {
#[cfg(not(target_arch = "wasm32"))]
last_tick: None,
last_now_s: None,
}
}
#[cfg(not(target_arch = "wasm32"))]
#[inline]
pub fn step(&mut self, active: bool) -> Option<f32> {
if !active {
self.reset();
return None;
}
let now = Instant::now();
let dt_s = self
.last_tick
.replace(now)
.map_or(0.0, |prev| now.duration_since(prev).as_secs_f32().min(MAX_DT_S));
Some(dt_s)
}
#[inline]
pub fn step_at(&mut self, active: bool, now_s: f64) -> Option<f32> {
if !active {
self.reset();
return None;
}
if !now_s.is_finite() {
return Some(0.0);
}
let dt_s = self
.last_now_s
.replace(now_s)
.map_or(0.0, |prev| (now_s - prev).clamp(0.0, f64::from(MAX_DT_S)) as f32);
Some(dt_s)
}
#[inline]
pub fn reset(&mut self) {
#[cfg(not(target_arch = "wasm32"))]
{
self.last_tick = None;
}
self.last_now_s = None;
}
}
#[derive(Clone)]
pub struct FrameWaker {
pub(crate) woken_mask: Arc<AtomicU64>,
pub(crate) woken_overflow: Arc<AtomicBool>,
pub(crate) on_wake: Option<Arc<dyn Fn() + Send + Sync>>,
}
impl std::fmt::Debug for FrameWaker {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("FrameWaker")
.field("woken_mask", &self.woken_mask.load(Ordering::Relaxed))
.field("woken_overflow", &self.woken_overflow.load(Ordering::Relaxed))
.finish()
}
}
impl FrameWaker {
pub fn with_on_wake(mut self, cb: Arc<dyn Fn() + Send + Sync>) -> Self {
self.on_wake = Some(cb);
self
}
#[inline]
pub fn slot(&self, slot: usize) -> SlotWaker {
SlotWaker {
waker: self.clone(),
slot,
}
}
#[inline]
pub fn wake_slot(&self, slot: usize) {
if slot < 64 {
self.woken_mask.fetch_or(1u64 << slot, Ordering::Release);
} else {
self.woken_overflow.store(true, Ordering::Release);
}
if let Some(cb) = &self.on_wake {
cb();
}
}
#[inline]
pub fn wake_all(&self) {
self.woken_mask.store(u64::MAX, Ordering::Release);
self.woken_overflow.store(true, Ordering::Release);
if let Some(cb) = &self.on_wake {
cb();
}
}
}
#[derive(Clone, Debug)]
pub struct SlotWaker {
waker: FrameWaker,
slot: usize,
}
impl SlotWaker {
#[inline]
pub fn new(waker: FrameWaker, slot: usize) -> Self {
Self { waker, slot }
}
#[inline]
pub const fn slot(&self) -> usize {
self.slot
}
#[inline]
pub fn wake(&self) {
self.waker.wake_slot(self.slot);
}
}