Skip to main content

nativeview_engine/ext/frame/
registry.rs

1//! Stable-slot, priority-ordered, deadline-aware [`FrameTickRegistry`].
2
3use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
4use std::sync::Arc;
5
6use nativeview_store::{ChangeSet, NodeStore, Transaction};
7
8use super::{FrameTickHook, FrameWaker, SlotWaker, TickDemand, TickHookId, TickPriority};
9
10struct HookSlot {
11    id: TickHookId,
12    priority: TickPriority,
13    hook: Box<dyn FrameTickHook>,
14}
15
16#[repr(transparent)]
17#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
18struct SlotBitMask(u64);
19
20impl SlotBitMask {
21    const EMPTY: Self = Self(0);
22
23    #[inline]
24    const fn raw(self) -> u64 {
25        self.0
26    }
27
28    #[inline]
29    const fn is_empty(self) -> bool {
30        self.0 == 0
31    }
32
33    #[inline]
34    const fn contains(self, slot: usize) -> bool {
35        (self.0 & (1u64 << slot)) != 0
36    }
37
38    #[inline]
39    fn set(&mut self, slot: usize) {
40        self.0 |= 1u64 << slot;
41    }
42
43    #[inline]
44    fn clear(&mut self, slot: usize) {
45        self.0 &= !(1u64 << slot);
46    }
47
48    #[inline]
49    fn union_raw(&mut self, bits: u64) {
50        self.0 |= bits;
51    }
52
53    #[inline]
54    fn clear_raw(&mut self, bits: u64) {
55        self.0 &= !bits;
56    }
57}
58
59#[repr(transparent)]
60#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord)]
61struct MonotonicMs(u64);
62
63impl MonotonicMs {
64    const NEVER: Self = Self(u64::MAX);
65
66    #[inline]
67    const fn raw(self) -> u64 {
68        self.0
69    }
70}
71
72#[derive(Debug, Clone, Copy, Default)]
73struct OverflowState {
74    active: bool,
75    timed: bool,
76    deadline_ms: MonotonicMs,
77}
78
79/// Stable-slot, priority-ordered registry of [`FrameTickHook`] participants with O(1) idle and
80/// future-deadline checks and zero steady-state allocations.
81///
82/// Slot indices are monotonically assigned and never shifted on priority insert or removal so
83/// external [`SlotWaker`] handles always address their exact slot (wakes for removed slots are
84/// masked out via `live_mask`).
85pub struct FrameTickRegistry {
86    slots: Vec<Option<HookSlot>>,
87    /// Live slot indices sorted by `(priority ASC, id ASC)`.
88    order: Vec<usize>,
89    next_id: TickHookId,
90    /// Bit `i` (`i < 64`) is set iff `slots[i]` holds a live hook.
91    live_mask: SlotBitMask,
92    /// Bit `i` (`i < 64`) is set while slot `i` demands [`TickDemand::NextFrame`].
93    active_mask: SlotBitMask,
94    /// Bit `i` (`i < 64`) is set while slot `i` is waiting on `deadlines_ms[i]`.
95    timed_mask: SlotBitMask,
96    /// Monotonic deadlines (`now_ms.saturating_add(delay_ms)`) for timed slots `< 64`.
97    deadlines_ms: [MonotonicMs; 64],
98    /// Minimum deadline across all timed slots (`< 64` and overflow); `None` when no timed slot is armed.
99    earliest_deadline_ms: Option<MonotonicMs>,
100    /// Per-slot scheduling state for slots `>= 64` (`slots[64 + i]`); empty unless `slots.len() > 64`.
101    overflow: Vec<OverflowState>,
102    /// Number of live overflow slots (`>= 64`) currently demanding `NextFrame`.
103    overflow_active_count: usize,
104    /// Number of live overflow slots (`>= 64`).
105    overflow_live_count: usize,
106    /// Last monotonic timestamp observed by `refresh_active`, `has_due`, `next_demand`, or `tick_active`.
107    last_now_ms: Option<MonotonicMs>,
108    /// External wakeups for slots `0..64` from [`FrameWaker`].
109    woken_mask: Arc<AtomicU64>,
110    /// External wakeups for overflow slots `>= 64` from [`FrameWaker`].
111    woken_overflow: Arc<AtomicBool>,
112    /// Optional host wake callback attached to every [`FrameWaker`] / [`SlotWaker`] handed out.
113    on_wake: Option<Arc<dyn Fn() + Send + Sync>>,
114}
115
116impl Default for FrameTickRegistry {
117    fn default() -> Self {
118        Self::new()
119    }
120}
121
122impl FrameTickRegistry {
123    /// Creates an empty registry.
124    #[inline]
125    pub fn new() -> Self {
126        Self::with_optional_on_wake(None)
127    }
128
129    /// Creates an empty registry whose [`Self::waker`] and [`Self::slot_waker`] invoke `on_wake`.
130    #[inline]
131    pub fn with_on_wake(on_wake: Arc<dyn Fn() + Send + Sync>) -> Self {
132        Self::with_optional_on_wake(Some(on_wake))
133    }
134
135    #[inline]
136    fn with_optional_on_wake(on_wake: Option<Arc<dyn Fn() + Send + Sync>>) -> Self {
137        Self {
138            slots: Vec::new(),
139            order: Vec::new(),
140            next_id: TickHookId::new(1),
141            live_mask: SlotBitMask::EMPTY,
142            active_mask: SlotBitMask::EMPTY,
143            timed_mask: SlotBitMask::EMPTY,
144            deadlines_ms: [MonotonicMs::NEVER; 64],
145            earliest_deadline_ms: None,
146            overflow: Vec::new(),
147            overflow_active_count: 0,
148            overflow_live_count: 0,
149            last_now_ms: None,
150            woken_mask: Arc::new(AtomicU64::new(0)),
151            woken_overflow: Arc::new(AtomicBool::new(false)),
152            on_wake,
153        }
154    }
155
156    /// Creates a registry from `hooks` registered at [`TickPriority::NORMAL`].
157    pub fn from_hooks(hooks: Vec<Box<dyn FrameTickHook>>) -> Self {
158        let mut reg = Self::new();
159        reg.slots.reserve(hooks.len());
160        reg.order.reserve(hooks.len());
161        for hook in hooks {
162            reg.push(hook);
163        }
164        reg
165    }
166
167    /// Creates a registry from `(priority, hook)` pairs with a bound `on_wake` callback.
168    pub fn from_entries_with_on_wake(
169        entries: Vec<(TickPriority, Box<dyn FrameTickHook>)>,
170        on_wake: Arc<dyn Fn() + Send + Sync>,
171    ) -> Self {
172        let mut reg = Self::with_on_wake(on_wake);
173        reg.slots.reserve(entries.len());
174        reg.order.reserve(entries.len());
175        for (priority, hook) in entries {
176            reg.push_with_priority(priority, hook);
177        }
178        reg
179    }
180
181    /// Returns a thread-safe [`FrameWaker`] for waking slots from outside `tick()`.
182    #[inline]
183    pub fn waker(&self) -> FrameWaker {
184        FrameWaker {
185            woken_mask: Arc::clone(&self.woken_mask),
186            woken_overflow: Arc::clone(&self.woken_overflow),
187            on_wake: self.on_wake.as_ref().map(Arc::clone),
188        }
189    }
190
191    /// Returns a thread-safe, zero-alloc [`SlotWaker`] bound to `slot`.
192    #[inline]
193    pub fn slot_waker(&self, slot: usize) -> SlotWaker {
194        SlotWaker::new(self.waker(), slot)
195    }
196
197    /// Number of live registered hooks.
198    #[inline]
199    pub fn len(&self) -> usize {
200        self.order.len()
201    }
202
203    /// Returns `true` when no live hooks are registered.
204    #[inline]
205    pub fn is_empty(&self) -> bool {
206        self.order.is_empty()
207    }
208
209    /// Returns the last monotonic timestamp observed by this registry, if any.
210    #[inline]
211    pub fn last_now_ms(&self) -> Option<u64> {
212        self.last_now_ms.map(MonotonicMs::raw)
213    }
214
215    /// Registers a hook at [`TickPriority::NORMAL`], returning `(id, stable_slot, initial_demand)`.
216    pub fn push(&mut self, hook: Box<dyn FrameTickHook>) -> (TickHookId, usize, TickDemand) {
217        self.push_with_priority(TickPriority::NORMAL, hook)
218    }
219
220    /// Registers a hook at `priority` without shifting any existing slot index, returning
221    /// `(id, stable_slot, initial_demand)`.
222    pub fn push_with_priority(
223        &mut self,
224        priority: TickPriority,
225        hook: Box<dyn FrameTickHook>,
226    ) -> (TickHookId, usize, TickDemand) {
227        let base_ms = self.last_now_ms.map_or(0, MonotonicMs::raw);
228        self.push_with_priority_impl(priority, hook, base_ms)
229    }
230
231    /// Registers a hook at `priority` anchoring any initial [`TickDemand::AfterMs`] deadline to
232    /// monotonic `now_ms` (and advancing `last_now_ms` monotonically).
233    pub fn push_with_priority_at(&mut self, priority: TickPriority, hook: Box<dyn FrameTickHook>, now_ms: u64) -> (TickHookId, usize, TickDemand) {
234        let base_ms = self.last_now_ms.map_or(now_ms, |prev| prev.raw().max(now_ms));
235        self.last_now_ms = Some(MonotonicMs(base_ms));
236        self.push_with_priority_impl(priority, hook, base_ms)
237    }
238
239    fn push_with_priority_impl(
240        &mut self,
241        priority: TickPriority,
242        hook: Box<dyn FrameTickHook>,
243        base_ms: u64,
244    ) -> (TickHookId, usize, TickDemand) {
245        let slot = self.slots.len();
246        let id = self.next_id;
247        self.next_id = TickHookId::new(self.next_id.raw().wrapping_add(1).max(1));
248        let demand = hook.demand().normalize();
249        self.slots.push(Some(HookSlot { id, priority, hook }));
250
251        let pos = self
252            .order
253            .partition_point(|&existing_slot| {
254                let Some(entry) = self.slots[existing_slot].as_ref() else {
255                    return false;
256                };
257                (entry.priority, entry.id) < (priority, id)
258            });
259        self.order.insert(pos, slot);
260
261        if slot < 64 {
262            self.live_mask.set(slot);
263            self.deadlines_ms[slot] = MonotonicMs::NEVER;
264        } else {
265            self.overflow.push(OverflowState {
266                active: false,
267                timed: false,
268                deadline_ms: MonotonicMs::NEVER,
269            });
270            self.overflow_live_count += 1;
271        }
272
273        self.set_slot_demand(slot, demand, base_ms);
274        if let TickDemand::AfterMs(_) = demand {
275            self.recompute_earliest_deadline();
276        }
277        (id, slot, demand)
278    }
279
280    /// Removes the hook identified by `id` without shifting any other slot's index.
281    pub fn remove(&mut self, id: TickHookId) -> bool {
282        let Some(order_pos) = self.order.iter().position(|&slot| {
283            self.slots[slot]
284                .as_ref()
285                .is_some_and(|entry| entry.id == id)
286        }) else {
287            return false;
288        };
289        let slot = self.order.remove(order_pos);
290        self.slots[slot] = None;
291        if slot < 64 {
292            let bit = 1u64 << slot;
293            self.live_mask.clear(slot);
294            self.active_mask.clear(slot);
295            self.timed_mask.clear(slot);
296            self.deadlines_ms[slot] = MonotonicMs::NEVER;
297            self.woken_mask.fetch_and(!bit, Ordering::AcqRel);
298        } else {
299            let ov = &mut self.overflow[slot - 64];
300            if ov.active {
301                self.overflow_active_count -= 1;
302            }
303            *ov = OverflowState {
304                active: false,
305                timed: false,
306                deadline_ms: MonotonicMs::NEVER,
307            };
308            self.overflow_live_count -= 1;
309            if self.overflow_live_count == 0 {
310                self.woken_overflow.store(false, Ordering::Release);
311            }
312        }
313        self.recompute_earliest_deadline();
314        true
315    }
316
317    #[inline]
318    fn set_slot_demand(&mut self, slot: usize, demand: TickDemand, now_ms: u64) {
319        if slot < 64 {
320            match demand {
321                TickDemand::Idle => {
322                    self.active_mask.clear(slot);
323                    self.timed_mask.clear(slot);
324                    self.deadlines_ms[slot] = MonotonicMs::NEVER;
325                }
326                TickDemand::NextFrame => {
327                    self.active_mask.set(slot);
328                    self.timed_mask.clear(slot);
329                    self.deadlines_ms[slot] = MonotonicMs::NEVER;
330                }
331                TickDemand::AfterMs(ms) => {
332                    let deadline = MonotonicMs(now_ms.saturating_add(u64::from(ms)));
333                    self.active_mask.clear(slot);
334                    self.timed_mask.set(slot);
335                    self.deadlines_ms[slot] = deadline;
336                }
337            }
338        } else {
339            let ov = &mut self.overflow[slot - 64];
340            let was_active = ov.active;
341            match demand {
342                TickDemand::Idle => {
343                    ov.active = false;
344                    ov.timed = false;
345                    ov.deadline_ms = MonotonicMs::NEVER;
346                }
347                TickDemand::NextFrame => {
348                    ov.active = true;
349                    ov.timed = false;
350                    ov.deadline_ms = MonotonicMs::NEVER;
351                }
352                TickDemand::AfterMs(ms) => {
353                    ov.active = false;
354                    ov.timed = true;
355                    ov.deadline_ms = MonotonicMs(now_ms.saturating_add(u64::from(ms)));
356                }
357            }
358            match (was_active, ov.active) {
359                (false, true) => self.overflow_active_count += 1,
360                (true, false) => self.overflow_active_count -= 1,
361                _ => {}
362            }
363        }
364    }
365
366    /// Sticky merge used by `refresh_active`: promotes `Idle` -> `AfterMs`/`NextFrame` and
367    /// tightens an existing deadline, never dropping previously woken/active slots or pushing
368    /// existing deadlines forward.
369    #[inline]
370    fn merge_slot_demand_sticky(&mut self, slot: usize, demand: TickDemand, now_ms: u64) -> bool {
371        match demand {
372            TickDemand::Idle => false,
373            TickDemand::NextFrame => {
374                if slot < 64 {
375                    let was_timed = self.timed_mask.contains(slot);
376                    self.active_mask.set(slot);
377                    self.timed_mask.clear(slot);
378                    self.deadlines_ms[slot] = MonotonicMs::NEVER;
379                    was_timed
380                } else {
381                    let ov = &mut self.overflow[slot - 64];
382                    let was_timed = ov.timed;
383                    if !ov.active {
384                        ov.active = true;
385                        self.overflow_active_count += 1;
386                    }
387                    ov.timed = false;
388                    ov.deadline_ms = MonotonicMs::NEVER;
389                    was_timed
390                }
391            }
392            TickDemand::AfterMs(ms) => {
393                let cand = MonotonicMs(now_ms.saturating_add(u64::from(ms)));
394                if slot < 64 {
395                    if self.active_mask.contains(slot) {
396                        return false;
397                    }
398                    if self.timed_mask.contains(slot) {
399                        if cand < self.deadlines_ms[slot] {
400                            self.deadlines_ms[slot] = cand;
401                            return true;
402                        }
403                        return false;
404                    }
405                    self.timed_mask.set(slot);
406                    self.deadlines_ms[slot] = cand;
407                    true
408                } else {
409                    let ov = &mut self.overflow[slot - 64];
410                    if ov.active {
411                        return false;
412                    }
413                    if ov.timed {
414                        if cand < ov.deadline_ms {
415                            ov.deadline_ms = cand;
416                            return true;
417                        }
418                        return false;
419                    }
420                    ov.timed = true;
421                    ov.deadline_ms = cand;
422                    true
423                }
424            }
425        }
426    }
427
428    #[inline]
429    fn recompute_earliest_deadline(&mut self) {
430        let mut earliest: Option<MonotonicMs> = None;
431        let mut tm = self.timed_mask.raw();
432        while tm != 0 {
433            let slot = tm.trailing_zeros() as usize;
434            tm &= tm - 1;
435            let d = self.deadlines_ms[slot];
436            earliest = Some(earliest.map_or(d, |cur| cur.min(d)));
437        }
438        if self.overflow_live_count > 0 {
439            for ov in &self.overflow {
440                if ov.timed {
441                    earliest = Some(earliest.map_or(ov.deadline_ms, |cur| cur.min(ov.deadline_ms)));
442                }
443            }
444        }
445        self.earliest_deadline_ms = earliest;
446    }
447
448    #[inline]
449    fn drain_woken(&mut self) {
450        let mut timed_changed = false;
451        let woken = self.woken_mask.swap(0, Ordering::AcqRel);
452        let live_woken = woken & self.live_mask.raw();
453        if live_woken != 0 {
454            self.active_mask.union_raw(live_woken);
455            let cleared_timed = self.timed_mask.raw() & live_woken;
456            if cleared_timed != 0 {
457                self.timed_mask.clear_raw(live_woken);
458                let mut m = cleared_timed;
459                while m != 0 {
460                    let slot = m.trailing_zeros() as usize;
461                    m &= m - 1;
462                    self.deadlines_ms[slot] = MonotonicMs::NEVER;
463                }
464                timed_changed = true;
465            }
466        }
467        if self.woken_overflow.swap(false, Ordering::AcqRel) && self.overflow_live_count > 0 {
468            for (off, ov) in self.overflow.iter_mut().enumerate() {
469                if self.slots[64 + off].is_some() {
470                    if !ov.active {
471                        ov.active = true;
472                        self.overflow_active_count += 1;
473                    }
474                    if ov.timed {
475                        ov.timed = false;
476                        ov.deadline_ms = MonotonicMs::NEVER;
477                        timed_changed = true;
478                    }
479                }
480            }
481        }
482        if timed_changed {
483            self.recompute_earliest_deadline();
484        }
485    }
486
487    #[inline]
488    fn drain_woken_if_pending(&mut self) {
489        if self.woken_mask.load(Ordering::Acquire) != 0
490            || self.woken_overflow.load(Ordering::Acquire)
491        {
492            self.drain_woken();
493        }
494    }
495
496    /// Returns `true` if a [`FrameWaker`] woke a live slot since the last drain.
497    #[inline]
498    pub fn has_pending_wakes(&self) -> bool {
499        (self.woken_mask.load(Ordering::Acquire) & self.live_mask.raw()) != 0
500            || (self.overflow_live_count > 0 && self.woken_overflow.load(Ordering::Acquire))
501    }
502
503    /// Queries every live hook's [`FrameTickHook::demand`] after a store commit and merges any
504    /// newly active/timed demands into the schedule (sticky: never clears woken slots or pushes
505    /// existing deadlines forward).
506    #[inline]
507    pub fn refresh_active(&mut self, now_ms: u64) {
508        self.last_now_ms = Some(MonotonicMs(now_ms));
509        if self.order.is_empty() {
510            return;
511        }
512        let mut timed_changed = false;
513        for i in 0..self.order.len() {
514            let slot = self.order[i];
515            let Some(entry) = self.slots[slot].as_ref() else {
516                continue;
517            };
518            let demand = entry.hook.demand().normalize();
519            timed_changed |= self.merge_slot_demand_sticky(slot, demand, now_ms);
520        }
521        if timed_changed {
522            self.recompute_earliest_deadline();
523        }
524    }
525
526    /// Store-aware variant of [`Self::refresh_active`] calling [`FrameTickHook::demand_on_commit`]
527    /// so store-scanning hooks skip unrelated commits with zero allocations.
528    #[inline]
529    pub fn refresh_active_with_store(
530        &mut self,
531        store: &NodeStore,
532        changes: &ChangeSet,
533        now_ms: u64,
534    ) {
535        self.last_now_ms = Some(MonotonicMs(now_ms));
536        if self.order.is_empty() {
537            return;
538        }
539        let mut timed_changed = false;
540        for i in 0..self.order.len() {
541            let slot = self.order[i];
542            let Some(entry) = self.slots[slot].as_ref() else {
543                continue;
544            };
545            let demand = entry.hook.demand_on_commit(store, changes).normalize();
546            timed_changed |= self.merge_slot_demand_sticky(slot, demand, now_ms);
547        }
548        if timed_changed {
549            self.recompute_earliest_deadline();
550        }
551    }
552
553    /// Returns `true` if any live hook is due at `now_ms` (O(1) fast path when idle or waiting
554    /// on a future deadline).
555    #[inline]
556    pub fn has_due(&mut self, now_ms: u64) -> bool {
557        let now = MonotonicMs(now_ms);
558        self.last_now_ms = Some(now);
559        if self.order.is_empty() {
560            return false;
561        }
562        self.drain_woken_if_pending();
563        !self.active_mask.is_empty()
564            || self.overflow_active_count > 0
565            || self.earliest_deadline_ms.is_some_and(|d| d <= now)
566    }
567
568    /// Returns the aggregate [`TickDemand`] across all live hooks at `now_ms` in O(1) time with
569    /// zero allocations.
570    #[inline]
571    pub fn next_demand(&mut self, now_ms: u64) -> TickDemand {
572        let now = MonotonicMs(now_ms);
573        self.last_now_ms = Some(now);
574        if self.order.is_empty() {
575            return TickDemand::Idle;
576        }
577        self.drain_woken_if_pending();
578        if !self.active_mask.is_empty() || self.overflow_active_count > 0 {
579            return TickDemand::NextFrame;
580        }
581        match self.earliest_deadline_ms {
582            None => TickDemand::Idle,
583            Some(d) if d <= now => TickDemand::NextFrame,
584            Some(d) => TickDemand::AfterMs((d.raw() - now_ms).min(u64::from(u32::MAX)) as u32),
585        }
586    }
587
588    /// Ticks all due hooks in strict `(priority ASC, id ASC)` order and returns the merged
589    /// [`TickDemand`] across ALL live hooks (including non-due timed hooks).
590    pub fn tick_active(
591        &mut self,
592        tx: &mut Transaction<'_>,
593        dt_s: f32,
594        now_ms: u64,
595    ) -> TickDemand {
596        let now = MonotonicMs(now_ms);
597        self.last_now_ms = Some(now);
598        if self.order.is_empty() {
599            return TickDemand::Idle;
600        }
601        self.drain_woken_if_pending();
602
603        let mut due_low = self.active_mask.raw();
604        if !self.timed_mask.is_empty() && self.earliest_deadline_ms.is_some_and(|d| d <= now) {
605            let mut tm = self.timed_mask.raw();
606            while tm != 0 {
607                let slot = tm.trailing_zeros() as usize;
608                tm &= tm - 1;
609                if self.deadlines_ms[slot] <= now {
610                    due_low |= 1u64 << slot;
611                }
612            }
613        }
614
615        if due_low == 0
616            && self.overflow_active_count == 0
617            && self.earliest_deadline_ms.is_none_or(|d| d > now)
618        {
619            return self.next_demand(now_ms);
620        }
621
622        for i in 0..self.order.len() {
623            let slot = self.order[i];
624            let is_due = if slot < 64 {
625                (due_low & (1u64 << slot)) != 0
626            } else {
627                let ov = &self.overflow[slot - 64];
628                ov.active || (ov.timed && ov.deadline_ms <= now)
629            };
630            if !is_due {
631                continue;
632            }
633            let demand = self.slots[slot]
634                .as_mut()
635                .expect("order only indexes live slots")
636                .hook
637                .tick(tx, dt_s, now_ms)
638                .normalize();
639            self.set_slot_demand(slot, demand, now_ms);
640        }
641
642        self.recompute_earliest_deadline();
643        self.next_demand(now_ms)
644    }
645}