nativeview_engine/ext/frame/mod.rs
1//! Shared frame clock, [`TickDemand`], [`FrameTickHook`], [`FrameWaker`], [`SlotWaker`], and
2//! prioritized/deadline [`FrameTickRegistry`].
3//!
4//! - [`FrameClock`] owns wall-clock `dt_s` computation and the [`MAX_DT_S`] (100 ms) clamp so
5//! hosts and the runtime share one clamp. On `wasm32`, use [`FrameClock::step_at`] with a
6//! host-supplied monotonic timestamp (`performance.now() * 1e-3`).
7//! - [`FrameTickRegistry`] tracks registered [`FrameTickHook`]s with stable slot indices, a dense
8//! `u64` active/timed bitmask + inline deadline array for the first 64 slots, a priority-sorted
9//! dispatch order, and an atomic [`FrameWaker`] / [`SlotWaker`] for off-tick wakeups: when every
10//! participant is idle or waiting on a future deadline, the per-frame check is O(1) with zero
11//! allocations and zero `Transaction` setup.
12
13mod registry;
14#[cfg(test)]
15mod tests;
16
17use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
18use std::sync::Arc;
19#[cfg(not(target_arch = "wasm32"))]
20use std::time::Instant;
21
22use nativeview_abi::{
23 NvTickOutcome, NV_TICK_DEMAND_AFTER_MS, NV_TICK_DEMAND_IDLE, NV_TICK_DEMAND_NEXT_FRAME,
24};
25use nativeview_store::{ChangeSet, NodeStore, Transaction};
26
27pub use registry::FrameTickRegistry;
28
29/// Maximum wall-clock delta forwarded to per-frame participants (100 ms).
30pub const MAX_DT_S: f32 = 0.1;
31
32/// Clamps `dt_s` to `0.0..=MAX_DT_S` (non-finite or negative values become `0.0`).
33#[inline]
34pub fn clamp_dt_s(dt_s: f32) -> f32 {
35 if dt_s.is_finite() && dt_s > 0.0 {
36 dt_s.min(MAX_DT_S)
37 } else {
38 0.0
39 }
40}
41
42/// Unified per-frame scheduling demand reported by [`FrameTickHook`]s and aggregated by
43/// [`FrameTickRegistry`] / `SurfaceRuntime::tick_ex`.
44#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
45pub enum TickDemand {
46 /// No pending work; hosts may sleep at 0% CPU until woken by input or a waker.
47 #[default]
48 Idle,
49 /// Participant needs the next vsync frame.
50 NextFrame,
51 /// Participant needs a tick after at least `ms` milliseconds (`AfterMs(0)` normalizes to
52 /// [`Self::NextFrame`]).
53 AfterMs(u32),
54}
55
56impl TickDemand {
57 /// Normalizes `AfterMs(0)` into [`Self::NextFrame`].
58 #[inline]
59 pub const fn normalize(self) -> Self {
60 match self {
61 Self::AfterMs(0) => Self::NextFrame,
62 other => other,
63 }
64 }
65
66 /// Combines two demands: `NextFrame` dominates everything; `AfterMs(a)` + `AfterMs(b)` keeps
67 /// the earlier `AfterMs(a.min(b))`; `Idle` is the identity.
68 #[inline]
69 pub const fn merge(self, other: Self) -> Self {
70 match (self.normalize(), other.normalize()) {
71 (Self::NextFrame, _) | (_, Self::NextFrame) => Self::NextFrame,
72 (Self::AfterMs(a), Self::AfterMs(b)) => {
73 Self::AfterMs(if a < b { a } else { b })
74 }
75 (Self::AfterMs(ms), Self::Idle) | (Self::Idle, Self::AfterMs(ms)) => {
76 Self::AfterMs(ms)
77 }
78 (Self::Idle, Self::Idle) => Self::Idle,
79 }
80 }
81
82 /// Returns `true` when this demand is [`Self::Idle`].
83 #[inline]
84 pub const fn is_idle(self) -> bool {
85 matches!(self, Self::Idle)
86 }
87
88 /// Encodes this demand into the C ABI `(NV_TICK_DEMAND_*, next_tick_ms)` pair.
89 #[inline]
90 pub const fn to_abi(self) -> (u32, u32) {
91 match self.normalize() {
92 Self::Idle => (NV_TICK_DEMAND_IDLE, 0),
93 Self::NextFrame => (NV_TICK_DEMAND_NEXT_FRAME, 0),
94 Self::AfterMs(ms) => (NV_TICK_DEMAND_AFTER_MS, ms),
95 }
96 }
97
98 /// Decodes a C ABI [`NvTickOutcome`] into a typed [`TickDemand`].
99 #[inline]
100 pub const fn from_outcome(outcome: NvTickOutcome) -> Option<Self> {
101 match outcome.demand {
102 NV_TICK_DEMAND_IDLE => Some(Self::Idle),
103 NV_TICK_DEMAND_NEXT_FRAME => Some(Self::NextFrame),
104 NV_TICK_DEMAND_AFTER_MS => Some(Self::AfterMs(outcome.next_tick_ms).normalize()),
105 _ => None,
106 }
107 }
108}
109
110/// Dispatch priority band for [`FrameTickHook`]s (lower values run earlier; ties break by
111/// registration order / [`TickHookId`] ascending).
112#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
113pub struct TickPriority(pub i16);
114
115impl Default for TickPriority {
116 #[inline]
117 fn default() -> Self {
118 Self::NORMAL
119 }
120}
121
122impl TickPriority {
123 pub const INPUT: Self = Self(-100);
124 pub const PHYSICS: Self = Self(0);
125 pub const NORMAL: Self = Self(0);
126 pub const MOTION: Self = Self(10);
127 pub const TIMER: Self = Self(50);
128}
129
130/// Stable identifier returned when registering a [`FrameTickHook`] in [`FrameTickRegistry`].
131#[repr(transparent)]
132#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
133pub struct TickHookId(u64);
134
135impl TickHookId {
136 #[inline]
137 pub(crate) const fn new(raw: u64) -> Self {
138 Self(raw)
139 }
140
141 /// Returns the raw monotonic identifier.
142 #[inline]
143 pub const fn raw(self) -> u64 {
144 self.0
145 }
146}
147
148/// Generic per-frame mutation hook run inside `nv_runtime::SurfaceRuntime::tick_ex`.
149///
150/// Optional subsystems (such as `packages/modules/motion`, `packages/modules/date-text`,
151/// `packages/modules/progress`, or custom physics) plug into `nativeview-runtime` via this trait
152/// so core stays strictly decoupled from every module. All mutations go through the runtime-owned
153/// `Transaction` so every table/layout/visual change is committed into a reusable `ChangeSet`, fed
154/// into `LaidOutScene::commit`, and published with accurate `dirty_indices`,
155/// `NvTableView::{dirty_owners, detached_owners}`, and `frame_id`.
156pub trait FrameTickHook: Send {
157 /// Reports this hook's current scheduling demand without mutating the store.
158 ///
159 /// Defaults to [`TickDemand::NextFrame`] for stateless hooks.
160 #[inline]
161 fn demand(&self) -> TickDemand {
162 TickDemand::NextFrame
163 }
164
165 /// Store-aware scheduling query invoked when the runtime commits store changes.
166 ///
167 /// Defaults to [`Self::demand`]. Store-scanning hooks (e.g. `DateTextTickHook`,
168 /// `ProgressTickHook`) override this to inspect `store` and `changes` in O(1) with zero
169 /// allocations and avoid redundant ticks when unrelated tables change.
170 #[inline]
171 fn demand_on_commit(&self, _store: &NodeStore, _changes: &ChangeSet) -> TickDemand {
172 self.demand()
173 }
174
175 /// Advances time by `dt_s` seconds (clamped to [`MAX_DT_S`] = 100 ms) at monotonic clock
176 /// `now_ms`, reading `tx.store()` and writing any mutations into `tx`. Returns this hook's
177 /// next [`TickDemand`].
178 fn tick(&mut self, tx: &mut Transaction<'_>, dt_s: f32, now_ms: u64) -> TickDemand;
179}
180
181/// Zero-allocation wall-clock epoch source mapping monotonic `now_ms` to Unix epoch milliseconds.
182///
183/// Shared by wall-clock [`FrameTickHook`] consumers (`date-text`, `progress`). On `wasm32`,
184/// `std::time::SystemTime::now()` is unavailable, so callers construct an explicit
185/// [`Self::offset_ms`] or [`Self::custom`] clock instead of falling back to 1970.
186#[derive(Debug, Clone, Copy)]
187pub enum WallClock {
188 /// Reads `std::time::SystemTime::now()` on native targets.
189 #[cfg(not(target_arch = "wasm32"))]
190 System,
191 /// Deterministic wall clock anchored at `epoch_ms_at_zero + now_ms`.
192 OffsetMs(i64),
193 /// Zero-allocation callback mapping monotonic `now_ms` to Unix epoch milliseconds.
194 Custom(fn(u64) -> i64),
195}
196
197impl WallClock {
198 /// Uses the OS wall clock (`SystemTime::now()`). Unavailable on `wasm32`.
199 #[cfg(not(target_arch = "wasm32"))]
200 #[inline]
201 pub const fn system() -> Self {
202 Self::System
203 }
204
205 /// Deterministic wall clock anchored at `epoch_ms_at_zero + now_ms`.
206 #[inline]
207 pub const fn offset_ms(epoch_ms_at_zero: i64) -> Self {
208 Self::OffsetMs(epoch_ms_at_zero)
209 }
210
211 /// Custom zero-allocation clock mapping monotonic `now_ms` to Unix epoch milliseconds.
212 #[inline]
213 pub const fn custom(f: fn(u64) -> i64) -> Self {
214 Self::Custom(f)
215 }
216
217 /// Evaluates the Unix epoch timestamp in milliseconds at monotonic `now_ms`.
218 #[inline]
219 pub fn now_epoch_ms(self, now_ms: u64) -> i64 {
220 match self {
221 #[cfg(not(target_arch = "wasm32"))]
222 Self::System => {
223 let _ = now_ms;
224 std::time::SystemTime::now()
225 .duration_since(std::time::UNIX_EPOCH)
226 .map_or(0, |d| i64::try_from(d.as_millis()).unwrap_or(i64::MAX))
227 }
228 Self::OffsetMs(base) => {
229 base.saturating_add(i64::try_from(now_ms).unwrap_or(i64::MAX))
230 }
231 Self::Custom(f) => f(now_ms),
232 }
233 }
234}
235
236/// Wall-clock delta timer shared by `SurfaceRuntime` and desktop hosts (`skia-shell`).
237#[derive(Debug, Default, Clone, Copy)]
238pub struct FrameClock {
239 #[cfg(not(target_arch = "wasm32"))]
240 last_tick: Option<Instant>,
241 last_now_s: Option<f64>,
242}
243
244impl FrameClock {
245 /// Creates a stopped clock.
246 #[inline]
247 pub const fn new() -> Self {
248 Self {
249 #[cfg(not(target_arch = "wasm32"))]
250 last_tick: None,
251 last_now_s: None,
252 }
253 }
254
255 /// Advances the clock using `Instant::now()` when `active` is `true`, returning `Some(dt_s)`
256 /// clamped to [`MAX_DT_S`] (`0.0` on the first active frame). Resets and returns `None` when
257 /// `active` is `false`.
258 #[cfg(not(target_arch = "wasm32"))]
259 #[inline]
260 pub fn step(&mut self, active: bool) -> Option<f32> {
261 if !active {
262 self.reset();
263 return None;
264 }
265 let now = Instant::now();
266 let dt_s = self
267 .last_tick
268 .replace(now)
269 .map_or(0.0, |prev| now.duration_since(prev).as_secs_f32().min(MAX_DT_S));
270 Some(dt_s)
271 }
272
273 /// Deterministic/portable version of [`Self::step`] taking a monotonic timestamp in seconds
274 /// (works on `wasm32-unknown-unknown` and in unit tests). Non-finite timestamps are ignored
275 /// without corrupting the stored baseline.
276 #[inline]
277 pub fn step_at(&mut self, active: bool, now_s: f64) -> Option<f32> {
278 if !active {
279 self.reset();
280 return None;
281 }
282 if !now_s.is_finite() {
283 return Some(0.0);
284 }
285 let dt_s = self
286 .last_now_s
287 .replace(now_s)
288 .map_or(0.0, |prev| (now_s - prev).clamp(0.0, f64::from(MAX_DT_S)) as f32);
289 Some(dt_s)
290 }
291
292 /// Stops the clock so the next active frame starts with `dt_s == 0.0`.
293 #[inline]
294 pub fn reset(&mut self) {
295 #[cfg(not(target_arch = "wasm32"))]
296 {
297 self.last_tick = None;
298 }
299 self.last_now_s = None;
300 }
301}
302
303/// Thread-safe handle to wake one or all slots of a [`FrameTickRegistry`] from outside `tick()`.
304#[derive(Clone)]
305pub struct FrameWaker {
306 pub(crate) woken_mask: Arc<AtomicU64>,
307 pub(crate) woken_overflow: Arc<AtomicBool>,
308 pub(crate) on_wake: Option<Arc<dyn Fn() + Send + Sync>>,
309}
310
311impl std::fmt::Debug for FrameWaker {
312 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
313 f.debug_struct("FrameWaker")
314 .field("woken_mask", &self.woken_mask.load(Ordering::Relaxed))
315 .field("woken_overflow", &self.woken_overflow.load(Ordering::Relaxed))
316 .finish()
317 }
318}
319
320impl FrameWaker {
321 /// Attaches a host wake callback (e.g. `WakeBridge::trigger`) invoked on every wake.
322 pub fn with_on_wake(mut self, cb: Arc<dyn Fn() + Send + Sync>) -> Self {
323 self.on_wake = Some(cb);
324 self
325 }
326
327 /// Binds this waker to a single stable `slot` index as a zero-alloc [`SlotWaker`].
328 #[inline]
329 pub fn slot(&self, slot: usize) -> SlotWaker {
330 SlotWaker {
331 waker: self.clone(),
332 slot,
333 }
334 }
335
336 /// Marks `slot` as active for the next tick. Slots `>= 64` wake overflow slots only.
337 #[inline]
338 pub fn wake_slot(&self, slot: usize) {
339 if slot < 64 {
340 self.woken_mask.fetch_or(1u64 << slot, Ordering::Release);
341 } else {
342 self.woken_overflow.store(true, Ordering::Release);
343 }
344 if let Some(cb) = &self.on_wake {
345 cb();
346 }
347 }
348
349 /// Marks every registered slot (both `< 64` and overflow) as active for the next tick.
350 #[inline]
351 pub fn wake_all(&self) {
352 self.woken_mask.store(u64::MAX, Ordering::Release);
353 self.woken_overflow.store(true, Ordering::Release);
354 if let Some(cb) = &self.on_wake {
355 cb();
356 }
357 }
358}
359
360/// Thread-safe, zero-allocation waker bound to a single stable slot in [`FrameTickRegistry`].
361#[derive(Clone, Debug)]
362pub struct SlotWaker {
363 waker: FrameWaker,
364 slot: usize,
365}
366
367impl SlotWaker {
368 /// Creates a [`SlotWaker`] targeting `slot` on `waker`.
369 #[inline]
370 pub fn new(waker: FrameWaker, slot: usize) -> Self {
371 Self { waker, slot }
372 }
373
374 /// Returns the stable slot index targeted by this waker.
375 #[inline]
376 pub const fn slot(&self) -> usize {
377 self.slot
378 }
379
380 /// Wakes the bound slot for the next tick with zero heap allocations.
381 #[inline]
382 pub fn wake(&self) {
383 self.waker.wake_slot(self.slot);
384 }
385}