nativeview-engine 0.1.0-rc.1

Framework-agnostic scene engine traits, hot-reload cdylib loader, and Frame-0 snapshot codecs.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
//! Pluggable vsync pacing seam ([`VsyncPacer`]) and zero-allocation portable pacers
//! ([`TimerVsyncPacer`], [`ManualVsyncPacer`]).
//!
//! All timestamps and intervals use `u64` / `u32` microseconds so this module compiles cleanly on
//! `wasm32-unknown-unknown` without `std::time::Instant`.
//!
//! Production consumers implementing [`VsyncPacer`] (`[INV:extension-point-has-consumers]`):
//! - `packages/backends/skia-desktop` (`CADisplayLink`/`CVDisplayLink`, `DwmFlush`, Wayland `winit`, timer fallback)
//! - `packages/backends/web-runtime` (`RafVsyncPacer` over `window.requestAnimationFrame`)

use std::sync::atomic::{AtomicBool, AtomicU32, AtomicU64, Ordering};
use std::sync::Arc;

/// Fallback display refresh rate when the OS/monitor does not report one (60 Hz = 60,000 mHz).
pub const DEFAULT_REFRESH_RATE_MILLIHERTZ: u32 = 60_000;

/// Minimum accepted refresh rate in millihertz (1 Hz); lower values clamp to
/// [`DEFAULT_REFRESH_RATE_MILLIHERTZ`].
pub const MIN_REFRESH_RATE_MILLIHERTZ: u32 = 1_000;

/// Maximum accepted refresh rate in millihertz (1000 Hz); higher values clamp here so
/// [`interval_us_from_millihertz`] is strictly `>= 1` microsecond.
pub const MAX_REFRESH_RATE_MILLIHERTZ: u32 = 1_000_000;

/// Clamps `millihertz` into a valid refresh rate (`< 1_000` -> `60_000`, `> 1_000_000` -> `1_000_000`).
#[inline]
pub const fn sanitize_refresh_rate_millihertz(millihertz: u32) -> u32 {
    if millihertz < MIN_REFRESH_RATE_MILLIHERTZ {
        DEFAULT_REFRESH_RATE_MILLIHERTZ
    } else if millihertz > MAX_REFRESH_RATE_MILLIHERTZ {
        MAX_REFRESH_RATE_MILLIHERTZ
    } else {
        millihertz
    }
}

/// Converts a refresh rate in millihertz (e.g. `60_000` for 60 Hz, `120_000` for 120 Hz) into a
/// nominal frame interval in microseconds (`16_666` us for 60 Hz, `8_333` us for 120 Hz),
/// guaranteed strictly `>= 1`.
#[inline]
pub const fn interval_us_from_millihertz(millihertz: u32) -> u32 {
    let mhz = sanitize_refresh_rate_millihertz(millihertz);
    let us = (1_000_000_000u64 / (mhz as u64)) as u32;
    if us == 0 { 1 } else { us }
}

/// Platform-pluggable vsync / frame pacing strategy.
///
/// Push-driven native pacers (`CADisplayLink`, `CVDisplayLink`, `DwmFlush`, browser
/// `requestAnimationFrame`) return `None` from [`Self::next_deadline_us`] and deliver ticks via
/// their platform event loop / wake callback while [`Self::is_active`] is `true`.
///
/// Timer / poll pacers (such as [`TimerVsyncPacer`]) return `Some(deadline_us)` from
/// [`Self::next_deadline_us`] while active so the event loop can sleep until the next frame
/// boundary (`ControlFlow::WaitUntil`) with 0% idle CPU.
pub trait VsyncPacer: Send {
    /// Starts (`true`) or pauses (`false`) frame delivery. Idle pacers MUST consume 0% CPU.
    fn set_active(&mut self, active: bool);

    /// Returns `true` while frame delivery is active.
    fn is_active(&self) -> bool;

    /// Acknowledges receipt of a delivered vsync tick so push-driven pacers can clear their
    /// coalescing latch and emit the next frame tick.
    fn on_tick_received(&self) {}

    /// Nominal frame interval in microseconds if known (e.g. `8_333` for 120 Hz ProMotion).
    fn nominal_interval_us(&self) -> Option<u32> {
        None
    }

    /// Optional next wake deadline in microseconds (`now_us` clock) for timer/poll pacers.
    /// Push-driven native pacers (`CADisplayLink`, `DwmFlush`, `rAF`) return `None`.
    fn next_deadline_us(&self, _last_frame_us: Option<u64>, _now_us: u64) -> Option<u64> {
        None
    }
}

/// Portable, zero-allocation refresh-rate timer pacer computing `next_deadline_us` in
/// microseconds for event loops that sleep via `WaitUntil`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct TimerVsyncPacer {
    millihertz: u32,
    active: bool,
}

impl Default for TimerVsyncPacer {
    #[inline]
    fn default() -> Self {
        Self::new(DEFAULT_REFRESH_RATE_MILLIHERTZ)
    }
}

impl TimerVsyncPacer {
    /// Creates a stopped timer pacer configured for `millihertz` (clamping `< 1_000` to `60_000`).
    #[inline]
    pub const fn new(millihertz: u32) -> Self {
        Self {
            millihertz: sanitize_refresh_rate_millihertz(millihertz),
            active: false,
        }
    }

    /// Returns the active refresh rate in millihertz.
    #[inline]
    pub const fn refresh_rate_millihertz(&self) -> u32 {
        self.millihertz
    }

    /// Updates the configured refresh rate in millihertz (clamping `< 1_000` to `60_000`).
    #[inline]
    pub fn set_refresh_rate_millihertz(&mut self, millihertz: u32) {
        self.millihertz = sanitize_refresh_rate_millihertz(millihertz);
    }
}

impl VsyncPacer for TimerVsyncPacer {
    #[inline]
    fn set_active(&mut self, active: bool) {
        self.active = active;
    }

    #[inline]
    fn is_active(&self) -> bool {
        self.active
    }

    #[inline]
    fn nominal_interval_us(&self) -> Option<u32> {
        Some(interval_us_from_millihertz(self.millihertz))
    }

    #[inline]
    fn next_deadline_us(&self, last_frame_us: Option<u64>, now_us: u64) -> Option<u64> {
        if !self.active {
            return None;
        }
        let interval = u64::from(interval_us_from_millihertz(self.millihertz));
        let target = match last_frame_us {
            Some(prev) => {
                // Clamp skewed/future `prev > now_us` back to `now_us` to avoid multi-second stalls.
                let anchor = if prev > now_us { now_us } else { prev };
                let next = anchor.saturating_add(interval);
                if next > now_us { next } else { now_us }
            }
            None => now_us.saturating_add(interval),
        };
        Some(target)
    }
}

struct ManualVsyncState {
    active: AtomicBool,
    tick_pending: AtomicBool,
    active_transitions: AtomicU64,
    ticks_triggered: AtomicU64,
    ticks_received: AtomicU64,
    nominal_interval_us: AtomicU32,
    on_trigger: Option<Arc<dyn Fn() + Send + Sync>>,
}

impl ManualVsyncState {
    #[inline]
    fn ack_tick(&self) {
        self.tick_pending.store(false, Ordering::Release);
        self.ticks_received.fetch_add(1, Ordering::AcqRel);
    }
}

/// Shared atomic control handle paired with [`ManualVsyncPacer`] for deterministic tests.
///
/// All steady-state operations are strictly atomic (`CountingAlloc == 0`).
#[derive(Clone)]
pub struct ManualVsyncHandle {
    state: Arc<ManualVsyncState>,
}

impl std::fmt::Debug for ManualVsyncHandle {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ManualVsyncHandle")
            .field("active", &self.is_active())
            .field("active_transitions", &self.active_transitions())
            .field("ticks_triggered", &self.ticks_triggered())
            .field("ticks_received", &self.ticks_received())
            .field("tick_pending", &self.is_tick_pending())
            .finish()
    }
}

impl ManualVsyncHandle {
    /// Returns whether the pacer is currently active.
    #[inline]
    pub fn is_active(&self) -> bool {
        self.state.active.load(Ordering::Acquire)
    }

    /// Returns the number of `active` state transitions observed (`false -> true` or `true -> false`).
    #[inline]
    pub fn active_transitions(&self) -> u64 {
        self.state.active_transitions.load(Ordering::Acquire)
    }

    /// Returns how many coalesced ticks have been triggered via [`Self::trigger_tick`].
    #[inline]
    pub fn ticks_triggered(&self) -> u64 {
        self.state.ticks_triggered.load(Ordering::Acquire)
    }

    /// Returns how many ticks have been acknowledged via `on_tick_received`.
    #[inline]
    pub fn ticks_received(&self) -> u64 {
        self.state.ticks_received.load(Ordering::Acquire)
    }

    /// Returns `true` when a triggered tick has not yet been acknowledged via `on_tick_received`.
    #[inline]
    pub fn is_tick_pending(&self) -> bool {
        self.state.tick_pending.load(Ordering::Acquire)
    }

    /// Triggers one coalesced tick if the pacer is active and no tick is already in flight.
    /// Returns `true` when a new tick was emitted.
    #[inline]
    pub fn trigger_tick(&self) -> bool {
        if !self.state.active.load(Ordering::Acquire) {
            return false;
        }
        if self
            .state
            .tick_pending
            .compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire)
            .is_err()
        {
            return false;
        }
        self.state.ticks_triggered.fetch_add(1, Ordering::AcqRel);
        if let Some(cb) = &self.state.on_trigger {
            cb();
        }
        true
    }

    /// Updates the reported nominal frame interval in microseconds (`None` or `Some(0)` clears it).
    #[inline]
    pub fn set_nominal_interval_us(&self, interval_us: Option<u32>) {
        self.state
            .nominal_interval_us
            .store(interval_us.unwrap_or(0), Ordering::Release);
    }

    /// Acknowledges receipt of a tick directly through the handle (mirrors [`VsyncPacer::on_tick_received`]).
    #[inline]
    pub fn on_tick_received(&self) {
        self.state.ack_tick();
    }
}

/// Deterministic, zero-allocation push-driven [`VsyncPacer`] for unit and integration tests.
pub struct ManualVsyncPacer {
    state: Arc<ManualVsyncState>,
}

impl std::fmt::Debug for ManualVsyncPacer {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ManualVsyncPacer")
            .field("active", &self.is_active())
            .finish()
    }
}

impl Default for ManualVsyncPacer {
    fn default() -> Self {
        Self::new().0
    }
}

impl ManualVsyncPacer {
    /// Creates a new inactive [`ManualVsyncPacer`] and its shared [`ManualVsyncHandle`].
    pub fn new() -> (Self, ManualVsyncHandle) {
        Self::with_on_trigger_opt(None)
    }

    /// Creates a new inactive [`ManualVsyncPacer`] whose [`ManualVsyncHandle::trigger_tick`]
    /// invokes `on_trigger` whenever a coalesced tick is emitted.
    pub fn with_on_trigger(on_trigger: Arc<dyn Fn() + Send + Sync>) -> (Self, ManualVsyncHandle) {
        Self::with_on_trigger_opt(Some(on_trigger))
    }

    fn with_on_trigger_opt(
        on_trigger: Option<Arc<dyn Fn() + Send + Sync>>,
    ) -> (Self, ManualVsyncHandle) {
        let state = Arc::new(ManualVsyncState {
            active: AtomicBool::new(false),
            tick_pending: AtomicBool::new(false),
            active_transitions: AtomicU64::new(0),
            ticks_triggered: AtomicU64::new(0),
            ticks_received: AtomicU64::new(0),
            nominal_interval_us: AtomicU32::new(0),
            on_trigger,
        });
        (
            Self {
                state: Arc::clone(&state),
            },
            ManualVsyncHandle { state },
        )
    }

    /// Clones a [`ManualVsyncHandle`] sharing this pacer's atomic state.
    #[inline]
    pub fn handle(&self) -> ManualVsyncHandle {
        ManualVsyncHandle {
            state: Arc::clone(&self.state),
        }
    }
}

impl VsyncPacer for ManualVsyncPacer {
    #[inline]
    fn set_active(&mut self, active: bool) {
        let prev = self.state.active.swap(active, Ordering::AcqRel);
        if prev != active {
            self.state.active_transitions.fetch_add(1, Ordering::AcqRel);
            self.state.tick_pending.store(false, Ordering::Release);
        }
    }

    #[inline]
    fn is_active(&self) -> bool {
        self.state.active.load(Ordering::Acquire)
    }

    #[inline]
    fn on_tick_received(&self) {
        self.state.ack_tick();
    }

    #[inline]
    fn nominal_interval_us(&self) -> Option<u32> {
        let v = self.state.nominal_interval_us.load(Ordering::Acquire);
        (v != 0).then_some(v)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn timer_pacer_sanitizes_millihertz_and_clamps_overdue_deadlines() {
        let mut pacer = TimerVsyncPacer::default();
        assert_eq!(pacer.refresh_rate_millihertz(), 60_000);
        assert_eq!(pacer.nominal_interval_us(), Some(16_666));
        assert!(!pacer.is_active());
        assert_eq!(pacer.next_deadline_us(None, 1_000), None);

        pacer.set_refresh_rate_millihertz(0);
        assert_eq!(pacer.refresh_rate_millihertz(), 60_000);
        pacer.set_refresh_rate_millihertz(u32::MAX);
        assert_eq!(pacer.refresh_rate_millihertz(), MAX_REFRESH_RATE_MILLIHERTZ);
        assert!(interval_us_from_millihertz(u32::MAX) >= 1);
        assert_eq!(pacer.nominal_interval_us(), Some(1_000));
        pacer.set_refresh_rate_millihertz(999);
        assert_eq!(pacer.refresh_rate_millihertz(), 60_000);
        pacer.set_refresh_rate_millihertz(120_000);
        assert_eq!(pacer.refresh_rate_millihertz(), 120_000);
        assert_eq!(pacer.nominal_interval_us(), Some(8_333));

        pacer.set_active(true);
        assert!(pacer.is_active());
        assert_eq!(pacer.next_deadline_us(None, 10_000), Some(18_333));
        assert_eq!(pacer.next_deadline_us(Some(10_000), 12_000), Some(18_333));
        // Overdue frame clamps to `now_us`.
        assert_eq!(pacer.next_deadline_us(Some(10_000), 25_000), Some(25_000));

        // Backward / skewed `last_frame_us > now_us` anchors to `now_us` cleanly.
        assert_eq!(pacer.next_deadline_us(Some(999_999), 100_000), Some(108_333));
        // Saturated `now_us == u64::MAX` never overflows or panics.
        assert_eq!(pacer.next_deadline_us(None, u64::MAX), Some(u64::MAX));
        assert_eq!(pacer.next_deadline_us(Some(u64::MAX), u64::MAX), Some(u64::MAX));

        pacer.set_active(false);
        assert_eq!(pacer.next_deadline_us(Some(10_000), 12_000), None);
    }

    #[test]
    fn manual_pacer_set_active_clears_stale_tick_pending_on_both_transitions() {
        let (mut pacer, handle) = ManualVsyncPacer::new();
        pacer.set_active(true);
        assert!(handle.trigger_tick());
        assert!(handle.is_tick_pending());
        pacer.set_active(false);
        assert!(!handle.is_tick_pending());
        // Simulate a stale pending latch before re-activating -> `set_active(true)` clears it.
        pacer.state.tick_pending.store(true, Ordering::Release);
        pacer.set_active(true);
        assert!(!handle.is_tick_pending());
        assert!(handle.trigger_tick());
    }

    #[test]
    fn manual_pacer_coalesces_tracks_transitions_and_is_zero_alloc() {
        let trigger_hits = Arc::new(AtomicU64::new(0));
        let hits = Arc::clone(&trigger_hits);
        let (mut pacer, handle) = ManualVsyncPacer::with_on_trigger(Arc::new(move || {
            hits.fetch_add(1, Ordering::Relaxed);
        }));

        assert!(!pacer.is_active());
        assert!(!handle.is_active());
        assert_eq!(handle.active_transitions(), 0);
        assert_eq!(pacer.nominal_interval_us(), None);
        assert_eq!(pacer.next_deadline_us(None, 1_000), None);
        assert!(!handle.trigger_tick(), "inactive pacer must not emit ticks");

        handle.set_nominal_interval_us(Some(8_333));
        assert_eq!(pacer.nominal_interval_us(), Some(8_333));

        let (_, allocs) = nativeview_test_support::count_allocs(|| {
            pacer.set_active(true);
            pacer.set_active(true); // duplicate no-op
            assert!(handle.is_active());
            assert_eq!(handle.active_transitions(), 1);

            assert!(handle.trigger_tick());
            assert!(!handle.trigger_tick(), "in-flight tick must coalesce");
            assert!(handle.is_tick_pending());
            assert_eq!(handle.ticks_triggered(), 1);

            pacer.on_tick_received();
            assert!(!handle.is_tick_pending());
            assert_eq!(handle.ticks_received(), 1);

            assert!(handle.trigger_tick());
            handle.on_tick_received();
            assert_eq!(handle.ticks_triggered(), 2);
            assert_eq!(handle.ticks_received(), 2);

            pacer.set_active(false);
            pacer.set_active(false); // duplicate no-op
            assert!(!handle.is_active());
            assert_eq!(handle.active_transitions(), 2);
            assert!(!handle.trigger_tick());
            handle.set_nominal_interval_us(None);
            assert_eq!(pacer.nominal_interval_us(), None);
        });

        assert_eq!(allocs, 0, "ManualVsyncPacer steady-state ops must be 0-alloc");
        assert_eq!(trigger_hits.load(Ordering::Relaxed), 2);
    }
}