nativeview-engine 0.1.0-rc.1

Framework-agnostic scene engine traits, hot-reload cdylib loader, and Frame-0 snapshot codecs.
Documentation
//! Shared frame clock, [`TickDemand`], [`FrameTickHook`], [`FrameWaker`], [`SlotWaker`], and
//! prioritized/deadline [`FrameTickRegistry`].
//!
//! - [`FrameClock`] owns wall-clock `dt_s` computation and the [`MAX_DT_S`] (100 ms) clamp so
//!   hosts and the runtime share one clamp. On `wasm32`, use [`FrameClock::step_at`] with a
//!   host-supplied monotonic timestamp (`performance.now() * 1e-3`).
//! - [`FrameTickRegistry`] tracks registered [`FrameTickHook`]s with stable slot indices, a dense
//!   `u64` active/timed bitmask + inline deadline array for the first 64 slots, a priority-sorted
//!   dispatch order, and an atomic [`FrameWaker`] / [`SlotWaker`] for off-tick wakeups: when every
//!   participant is idle or waiting on a future deadline, the per-frame check is O(1) with zero
//!   allocations and zero `Transaction` setup.

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;

/// Maximum wall-clock delta forwarded to per-frame participants (100 ms).
pub const MAX_DT_S: f32 = 0.1;

/// Clamps `dt_s` to `0.0..=MAX_DT_S` (non-finite or negative values become `0.0`).
#[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
    }
}

/// Unified per-frame scheduling demand reported by [`FrameTickHook`]s and aggregated by
/// [`FrameTickRegistry`] / `SurfaceRuntime::tick_ex`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum TickDemand {
    /// No pending work; hosts may sleep at 0% CPU until woken by input or a waker.
    #[default]
    Idle,
    /// Participant needs the next vsync frame.
    NextFrame,
    /// Participant needs a tick after at least `ms` milliseconds (`AfterMs(0)` normalizes to
    /// [`Self::NextFrame`]).
    AfterMs(u32),
}

impl TickDemand {
    /// Normalizes `AfterMs(0)` into [`Self::NextFrame`].
    #[inline]
    pub const fn normalize(self) -> Self {
        match self {
            Self::AfterMs(0) => Self::NextFrame,
            other => other,
        }
    }

    /// Combines two demands: `NextFrame` dominates everything; `AfterMs(a)` + `AfterMs(b)` keeps
    /// the earlier `AfterMs(a.min(b))`; `Idle` is the identity.
    #[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,
        }
    }

    /// Returns `true` when this demand is [`Self::Idle`].
    #[inline]
    pub const fn is_idle(self) -> bool {
        matches!(self, Self::Idle)
    }

    /// Encodes this demand into the C ABI `(NV_TICK_DEMAND_*, next_tick_ms)` pair.
    #[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),
        }
    }

    /// Decodes a C ABI [`NvTickOutcome`] into a typed [`TickDemand`].
    #[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,
        }
    }
}

/// Dispatch priority band for [`FrameTickHook`]s (lower values run earlier; ties break by
/// registration order / [`TickHookId`] ascending).
#[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);
}

/// Stable identifier returned when registering a [`FrameTickHook`] in [`FrameTickRegistry`].
#[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)
    }

    /// Returns the raw monotonic identifier.
    #[inline]
    pub const fn raw(self) -> u64 {
        self.0
    }
}

/// Generic per-frame mutation hook run inside `nv_runtime::SurfaceRuntime::tick_ex`.
///
/// Optional subsystems (such as `packages/modules/motion`, `packages/modules/date-text`,
/// `packages/modules/progress`, or custom physics) plug into `nativeview-runtime` via this trait
/// so core stays strictly decoupled from every module. All mutations go through the runtime-owned
/// `Transaction` so every table/layout/visual change is committed into a reusable `ChangeSet`, fed
/// into `LaidOutScene::commit`, and published with accurate `dirty_indices`,
/// `NvTableView::{dirty_owners, detached_owners}`, and `frame_id`.
pub trait FrameTickHook: Send {
    /// Reports this hook's current scheduling demand without mutating the store.
    ///
    /// Defaults to [`TickDemand::NextFrame`] for stateless hooks.
    #[inline]
    fn demand(&self) -> TickDemand {
        TickDemand::NextFrame
    }

    /// Store-aware scheduling query invoked when the runtime commits store changes.
    ///
    /// Defaults to [`Self::demand`]. Store-scanning hooks (e.g. `DateTextTickHook`,
    /// `ProgressTickHook`) override this to inspect `store` and `changes` in O(1) with zero
    /// allocations and avoid redundant ticks when unrelated tables change.
    #[inline]
    fn demand_on_commit(&self, _store: &NodeStore, _changes: &ChangeSet) -> TickDemand {
        self.demand()
    }

    /// Advances time by `dt_s` seconds (clamped to [`MAX_DT_S`] = 100 ms) at monotonic clock
    /// `now_ms`, reading `tx.store()` and writing any mutations into `tx`. Returns this hook's
    /// next [`TickDemand`].
    fn tick(&mut self, tx: &mut Transaction<'_>, dt_s: f32, now_ms: u64) -> TickDemand;
}

/// Zero-allocation wall-clock epoch source mapping monotonic `now_ms` to Unix epoch milliseconds.
///
/// Shared by wall-clock [`FrameTickHook`] consumers (`date-text`, `progress`). On `wasm32`,
/// `std::time::SystemTime::now()` is unavailable, so callers construct an explicit
/// [`Self::offset_ms`] or [`Self::custom`] clock instead of falling back to 1970.
#[derive(Debug, Clone, Copy)]
pub enum WallClock {
    /// Reads `std::time::SystemTime::now()` on native targets.
    #[cfg(not(target_arch = "wasm32"))]
    System,
    /// Deterministic wall clock anchored at `epoch_ms_at_zero + now_ms`.
    OffsetMs(i64),
    /// Zero-allocation callback mapping monotonic `now_ms` to Unix epoch milliseconds.
    Custom(fn(u64) -> i64),
}

impl WallClock {
    /// Uses the OS wall clock (`SystemTime::now()`). Unavailable on `wasm32`.
    #[cfg(not(target_arch = "wasm32"))]
    #[inline]
    pub const fn system() -> Self {
        Self::System
    }

    /// Deterministic wall clock anchored at `epoch_ms_at_zero + now_ms`.
    #[inline]
    pub const fn offset_ms(epoch_ms_at_zero: i64) -> Self {
        Self::OffsetMs(epoch_ms_at_zero)
    }

    /// Custom zero-allocation clock mapping monotonic `now_ms` to Unix epoch milliseconds.
    #[inline]
    pub const fn custom(f: fn(u64) -> i64) -> Self {
        Self::Custom(f)
    }

    /// Evaluates the Unix epoch timestamp in milliseconds at monotonic `now_ms`.
    #[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),
        }
    }
}

/// Wall-clock delta timer shared by `SurfaceRuntime` and desktop hosts (`skia-shell`).
#[derive(Debug, Default, Clone, Copy)]
pub struct FrameClock {
    #[cfg(not(target_arch = "wasm32"))]
    last_tick: Option<Instant>,
    last_now_s: Option<f64>,
}

impl FrameClock {
    /// Creates a stopped clock.
    #[inline]
    pub const fn new() -> Self {
        Self {
            #[cfg(not(target_arch = "wasm32"))]
            last_tick: None,
            last_now_s: None,
        }
    }

    /// Advances the clock using `Instant::now()` when `active` is `true`, returning `Some(dt_s)`
    /// clamped to [`MAX_DT_S`] (`0.0` on the first active frame). Resets and returns `None` when
    /// `active` is `false`.
    #[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)
    }

    /// Deterministic/portable version of [`Self::step`] taking a monotonic timestamp in seconds
    /// (works on `wasm32-unknown-unknown` and in unit tests). Non-finite timestamps are ignored
    /// without corrupting the stored baseline.
    #[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)
    }

    /// Stops the clock so the next active frame starts with `dt_s == 0.0`.
    #[inline]
    pub fn reset(&mut self) {
        #[cfg(not(target_arch = "wasm32"))]
        {
            self.last_tick = None;
        }
        self.last_now_s = None;
    }
}

/// Thread-safe handle to wake one or all slots of a [`FrameTickRegistry`] from outside `tick()`.
#[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 {
    /// Attaches a host wake callback (e.g. `WakeBridge::trigger`) invoked on every wake.
    pub fn with_on_wake(mut self, cb: Arc<dyn Fn() + Send + Sync>) -> Self {
        self.on_wake = Some(cb);
        self
    }

    /// Binds this waker to a single stable `slot` index as a zero-alloc [`SlotWaker`].
    #[inline]
    pub fn slot(&self, slot: usize) -> SlotWaker {
        SlotWaker {
            waker: self.clone(),
            slot,
        }
    }

    /// Marks `slot` as active for the next tick. Slots `>= 64` wake overflow slots only.
    #[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();
        }
    }

    /// Marks every registered slot (both `< 64` and overflow) as active for the next tick.
    #[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();
        }
    }
}

/// Thread-safe, zero-allocation waker bound to a single stable slot in [`FrameTickRegistry`].
#[derive(Clone, Debug)]
pub struct SlotWaker {
    waker: FrameWaker,
    slot: usize,
}

impl SlotWaker {
    /// Creates a [`SlotWaker`] targeting `slot` on `waker`.
    #[inline]
    pub fn new(waker: FrameWaker, slot: usize) -> Self {
        Self { waker, slot }
    }

    /// Returns the stable slot index targeted by this waker.
    #[inline]
    pub const fn slot(&self) -> usize {
        self.slot
    }

    /// Wakes the bound slot for the next tick with zero heap allocations.
    #[inline]
    pub fn wake(&self) {
        self.waker.wake_slot(self.slot);
    }
}