Skip to main content

ferrokit_core/
sync.rs

1//! Keeping native frame changes and the host's GPU frame in step (risk 2).
2//!
3//! Background (measured on 60 fps video in the prototype): winit redraws from a
4//! run-loop observer that runs *after* Core Animation's commit observer. Native
5//! frames set during the host's draw therefore wait for the next run-loop pass
6//! to commit, while the GPU frame presents on its own schedule.
7//!
8//! Two independent switches, both off by default:
9//! - [`set_flush_after_draw`]: commits the pending Core Animation transaction
10//!   right after the host's redraw. During the draw, `place` queues a block on
11//!   the main run loop and wakes it; the block runs as soon as the host's
12//!   redraw (and its GPU present) returns. (A plain run-loop observer at the
13//!   host's own order ran *before* the host's redraw, ~16 ms after the
14//!   previous draw, so it couldn't be used.)
15//! - [`set_layer_presents_with_transaction`]: asks the Metal layer to present
16//!   inside that transaction. Only honoured by wgpu 28 and later, which read
17//!   the flag from the layer each frame; wgpu 27 (Iced 0.14) resets it.
18
19use crate::kept::{UiCell, UiLocal};
20use std::cell::Cell;
21use std::time::{Duration, Instant};
22
23use block2::RcBlock;
24use objc2::runtime::AnyObject;
25use objc2::{class, msg_send};
26use objc2_app_kit::NSWindowOcclusionState;
27use objc2_core_foundation::{CFRunLoop, kCFRunLoopCommonModes};
28
29/// When the flush observer may start flushing. Flushing the first frames
30/// while the window is still being put on screen lost the last startup frame
31/// in the spike (the window kept a stale frame until the next redraw).
32#[derive(Debug, Clone, Copy, PartialEq)]
33pub enum StartGate {
34    /// Flush from the first frame.
35    Immediately,
36    /// Once the window reports itself visible (occlusion state).
37    WindowVisible,
38    /// A fixed delay after the first observed draw (the spike's workaround).
39    After(Duration),
40}
41
42#[derive(Debug, Clone, Copy, Default)]
43/// Counters for the flush switch (diagnostics).
44pub struct SyncStats {
45    /// Flush blocks that ran (at most one per drawn frame).
46    pub passes_after_draw: u64,
47    /// Of those, blocks that ran within 4 ms of the last `place` (i.e. right
48    /// after the host's redraw, as intended).
49    pub passes_right_after_draw: u64,
50    /// Flushes done.
51    pub flushes: u64,
52    /// Passes held back by the start gate.
53    pub gated: u64,
54}
55
56thread_local! {
57    static SCHEDULED: Cell<bool> = const { Cell::new(false) };
58    static ENABLED: Cell<bool> = const { Cell::new(false) };
59    static GATE: Cell<StartGate> = const { Cell::new(StartGate::WindowVisible) };
60    static OPEN: Cell<bool> = const { Cell::new(false) };
61    static FIRST_PLACE: Cell<Option<Instant>> = const { Cell::new(None) };
62    static LAST_PLACE: Cell<Option<Instant>> = const { Cell::new(None) };
63    static DIRTY: Cell<bool> = const { Cell::new(false) };
64    /// Time from the last `place` to each flush block, in microseconds.
65    static GAPS: UiCell<Vec<u32>> = const { UiCell::new(Vec::new()) };
66    static STATS: Cell<SyncStats> = const { Cell::new(SyncStats { passes_after_draw: 0, passes_right_after_draw: 0, flushes: 0, gated: 0 }) };
67}
68
69pub(crate) fn note_place() {
70    let now = Instant::now();
71    FIRST_PLACE.with(|f| if f.get().is_none() { f.set(Some(now)) });
72    LAST_PLACE.with(|l| l.set(Some(now)));
73    DIRTY.with(|d| d.set(true));
74    if ENABLED.with(Cell::get) && !SCHEDULED.with(|s| s.replace(true)) {
75        let main = CFRunLoop::main().expect("main run loop");
76        let block = RcBlock::new(|| {
77            SCHEDULED.with(|s| s.set(false));
78            on_pass();
79        });
80        // SAFETY: the block only touches main-thread state and runs on the
81        // main run loop; common modes include live-resize event tracking.
82        unsafe { main.perform_block(kCFRunLoopCommonModes.map(|m| m.as_ref()), Some(&block)) };
83        main.wake_up();
84    }
85}
86
87/// Percentiles (p10, p50, p90) of the time from the last `place` to the
88/// flush block, in microseconds. Diagnostic.
89pub fn gap_percentiles() -> Option<(u32, u32, u32)> {
90    GAPS.with_borrow(|g| {
91        let mut v = g.clone();
92        v.sort_unstable();
93        let at = |q: usize| v[(v.len() - 1) * q / 100];
94        (!v.is_empty()).then(|| (at(10), at(50), at(90)))
95    })
96}
97
98/// Counters so far.
99pub fn stats() -> SyncStats {
100    STATS.with(Cell::get)
101}
102
103/// Turns flushing right after each host redraw on or off.
104pub fn set_flush_after_draw(enabled: bool, gate: StartGate) {
105    let _ = crate::host::mtm();
106    ENABLED.with(|e| e.set(enabled));
107    GATE.with(|g| g.set(gate));
108}
109
110fn on_pass() {
111    if !DIRTY.with(|d| d.replace(false)) {
112        return;
113    }
114    let mut stats = STATS.with(Cell::get);
115    stats.passes_after_draw += 1;
116    if let Some(t) = LAST_PLACE.with(Cell::get) {
117        let gap = t.elapsed();
118        GAPS.with_borrow_mut(|g| g.push(gap.as_micros().min(u32::MAX as u128) as u32));
119        if gap < Duration::from_millis(4) {
120            stats.passes_right_after_draw += 1;
121        }
122    }
123    if ENABLED.with(Cell::get) {
124        if gate_open() {
125            flush();
126            stats.flushes += 1;
127        } else {
128            stats.gated += 1;
129        }
130    }
131    STATS.with(|s| s.set(stats));
132}
133
134fn gate_open() -> bool {
135    if OPEN.with(Cell::get) {
136        return true;
137    }
138    let open = match GATE.with(Cell::get) {
139        StartGate::Immediately => true,
140        StartGate::After(d) => FIRST_PLACE.with(Cell::get).is_some_and(|t| t.elapsed() >= d),
141        StartGate::WindowVisible => crate::host::content_view()
142            .and_then(|v| v.window())
143            .is_some_and(|w| w.occlusionState().contains(NSWindowOcclusionState::Visible)),
144    };
145    OPEN.with(|o| o.set(open));
146    open
147}
148
149/// Commits the current Core Animation transaction now.
150pub fn flush() {
151    // SAFETY: class method with no arguments.
152    let () = unsafe { msg_send![class!(CATransaction), flush] };
153}
154
155/// Sets `presentsWithTransaction` on the content view's Metal layer. Returns
156/// false if there is no such layer. See the module docs for which wgpu
157/// versions honour it; on wgpu 27 it freezes the GPU output.
158pub fn set_layer_presents_with_transaction(on: bool) -> bool {
159    let Some(content) = crate::host::content_view() else { return false };
160    let Some(layer) = content.layer() else { return false };
161    let layer: &AnyObject = &layer;
162    // SAFETY: checked with respondsToSelector before calling the setter.
163    unsafe {
164        let responds: bool = msg_send![layer, respondsToSelector: objc2::sel!(setPresentsWithTransaction:)];
165        if !responds {
166            return false;
167        }
168        let () = msg_send![layer, setPresentsWithTransaction: on];
169    }
170    true
171}