Skip to main content

euv_core/game/pacing/
impl.rs

1use super::*;
2
3/// Default 120Hz native-VSync-driven `FramePacingController`.
4impl Default for FramePacingController {
5    /// Creates a `FramePacingController` configured for 60Hz native VSync with 2 max in-flight frames.
6    ///
7    /// # Returns
8    ///
9    /// - `Self` - Default frame pacing controller.
10    fn default() -> Self {
11        Self::new(60.0, true, None, PACING_DEFAULT_MAX_IN_FLIGHT)
12    }
13}
14
15/// Unified VSync pacing, double-gate elimination, clock rebasing, and in-flight tracking for `FramePacingController`.
16impl FramePacingController {
17    /// Constructs a `FramePacingController` with explicit display rate, VSync ownership, optional user FPS cap, and in-flight bound.
18    ///
19    /// # Arguments
20    ///
21    /// - `f32` - Active display refresh rate in Hertz.
22    /// - `bool` - Whether native platform VSync already throttles presentation.
23    /// - `Option<u32>` - Optional explicit user FPS cap.
24    /// - `u32` - Maximum concurrent in-flight frames (`1..=4`).
25    ///
26    /// # Returns
27    ///
28    /// - `Self` - Configured frame pacing controller.
29    #[must_use]
30    pub fn new(
31        display_hz: f32,
32        native_vsync_active: bool,
33        user_fps_cap: Option<u32>,
34        max_in_flight_frames: u32,
35    ) -> Self {
36        Self {
37            display_hz: display_hz.clamp(PACING_MIN_DISPLAY_HZ, PACING_MAX_DISPLAY_HZ),
38            native_vsync_active,
39            user_fps_cap: user_fps_cap.filter(|cap: &u32| *cap > 0),
40            max_in_flight_frames: max_in_flight_frames.clamp(1, 4),
41            in_flight_frames: 0,
42            last_vsync_ns: 0,
43            last_present_ns: 0,
44            oldest_pending_input_ns: 0,
45            pending_input_dirty: false,
46            pending_layout_dirty: false,
47            stats: FramePacingStats::default(),
48        }
49    }
50
51    /// Returns the optional explicit user FPS cap.
52    ///
53    /// # Arguments
54    ///
55    /// - `&Self` - Pacing controller reference.
56    ///
57    /// # Returns
58    ///
59    /// - `Option<u32>` - Active user FPS cap if set.
60    #[must_use]
61    pub const fn active_user_fps_cap(&self) -> Option<u32> {
62        let Self { user_fps_cap, .. } = *self;
63        user_fps_cap
64    }
65
66    /// Returns `true` when software sleep/deadline gating should be bypassed because native VSync already paces presentation at or below the target rate.
67    ///
68    /// # Arguments
69    ///
70    /// - `&Self` - Pacing controller reference.
71    ///
72    /// # Returns
73    ///
74    /// - `bool` - `true` when software waiting must be skipped to avoid double-gating.
75    #[must_use]
76    pub fn should_bypass_software_gate(&self) -> bool {
77        if !self.get_native_vsync_active() {
78            return false;
79        }
80        match self.active_user_fps_cap() {
81            None => true,
82            Some(cap) => (cap as f32) >= self.get_display_hz() - 0.5,
83        }
84    }
85
86    /// Returns the nominal display refresh period in nanoseconds.
87    ///
88    /// # Arguments
89    ///
90    /// - `&Self` - Pacing controller reference.
91    ///
92    /// # Returns
93    ///
94    /// - `u64` - Nominal VSync period in nanoseconds.
95    #[must_use]
96    pub fn display_period_ns(&self) -> u64 {
97        let hz: f64 = self
98            .get_display_hz()
99            .clamp(PACING_MIN_DISPLAY_HZ, PACING_MAX_DISPLAY_HZ) as f64;
100        (NS_PER_SEC_F64 / hz).round() as u64
101    }
102
103    /// Updates the display refresh rate mode and rebases the monotonic clock to avoid synthetic dt spikes.
104    ///
105    /// # Arguments
106    ///
107    /// - `&Self` - Mutable pacing controller.
108    /// - `f32` - New active hardware refresh rate in Hertz.
109    /// - `u64` - Current monotonic timestamp in nanoseconds.
110    pub fn set_display_mode(&mut self, display_hz: f32, timestamp_ns: u64) {
111        self.set_display_hz(display_hz.clamp(PACING_MIN_DISPLAY_HZ, PACING_MAX_DISPLAY_HZ));
112        self.rebase_clock(timestamp_ns);
113    }
114
115    /// Rebases the monotonic VSync reference timestamp (e.g. after foreground resume or refresh-rate switch).
116    ///
117    /// # Arguments
118    ///
119    /// - `&Self` - Mutable pacing controller.
120    /// - `u64` - Current monotonic timestamp in nanoseconds.
121    pub fn rebase_clock(&mut self, timestamp_ns: u64) {
122        self.set_last_vsync_ns(timestamp_ns);
123        self.set_last_present_ns(0);
124        let mut stats: FramePacingStats = self.get_stats();
125        stats.set_timebase_rebases(stats.get_timebase_rebases().saturating_add(1));
126        self.set_stats(stats);
127    }
128
129    /// Notifies the controller that one submitted frame finished presenting, freeing an in-flight slot.
130    ///
131    /// # Arguments
132    ///
133    /// - `&Self` - Mutable pacing controller.
134    pub fn notify_present_completed(&mut self) {
135        let next: u32 = self.get_in_flight_frames().saturating_sub(1);
136        self.set_in_flight_frames(next);
137    }
138
139    /// Evaluates a scheduling `trigger` at monotonic `timestamp_ns` and returns a single authoritative `PacingDecision`.
140    ///
141    /// # Arguments
142    ///
143    /// - `&Self` - Mutable pacing controller.
144    /// - `FramePacingTrigger` - Incoming scheduling event kind.
145    /// - `u64` - Monotonic clock timestamp in nanoseconds.
146    ///
147    /// # Returns
148    ///
149    /// - `PacingDecision` - Whether to step simulation, render, wait in flight, or defer to VSync.
150    pub fn evaluate(&mut self, trigger: FramePacingTrigger, timestamp_ns: u64) -> PacingDecision {
151        match trigger {
152            FramePacingTrigger::InputEvent => {
153                self.set_pending_input_dirty(true);
154                if self.get_oldest_pending_input_ns() == 0 {
155                    self.set_oldest_pending_input_ns(timestamp_ns);
156                }
157                let mut stats: FramePacingStats = self.get_stats();
158                stats.set_deferred_non_vsync_events(
159                    stats.get_deferred_non_vsync_events().saturating_add(1),
160                );
161                self.set_stats(stats);
162                PacingDecision::new(
163                    PacingAction::DeferToNextVsync,
164                    0.0,
165                    timestamp_ns,
166                    0.0,
167                    false,
168                    false,
169                )
170            }
171            FramePacingTrigger::SafeAreaChanged | FramePacingTrigger::FullscreenChanged => {
172                self.set_pending_layout_dirty(true);
173                let mut stats: FramePacingStats = self.get_stats();
174                stats.set_deferred_non_vsync_events(
175                    stats.get_deferred_non_vsync_events().saturating_add(1),
176                );
177                self.set_stats(stats);
178                PacingDecision::new(
179                    PacingAction::DeferToNextVsync,
180                    0.0,
181                    timestamp_ns,
182                    0.0,
183                    false,
184                    false,
185                )
186            }
187            FramePacingTrigger::TimebaseReset => {
188                self.rebase_clock(timestamp_ns);
189                PacingDecision::new(
190                    PacingAction::DeferToNextVsync,
191                    0.0,
192                    timestamp_ns,
193                    0.0,
194                    false,
195                    false,
196                )
197            }
198            FramePacingTrigger::LifecycleFirstFrame => {
199                self.set_pending_layout_dirty(false);
200                PacingDecision::new(
201                    PacingAction::RenderWithoutSimAdvance,
202                    0.0,
203                    timestamp_ns,
204                    0.0,
205                    true,
206                    false,
207                )
208            }
209            FramePacingTrigger::Vsync => self.evaluate_vsync(timestamp_ns),
210        }
211    }
212
213    /// Evaluates an authoritative VSync opportunity at monotonic `timestamp_ns`.
214    ///
215    /// # Arguments
216    ///
217    /// - `&Self` - Mutable pacing controller.
218    /// - `u64` - Monotonic VSync timestamp in nanoseconds.
219    ///
220    /// # Returns
221    ///
222    /// - `PacingDecision` - Pacing verdict for this VSync interval.
223    fn evaluate_vsync(&mut self, timestamp_ns: u64) -> PacingDecision {
224        let mut stats: FramePacingStats = self.get_stats();
225        stats.set_vsync_signals(stats.get_vsync_signals().saturating_add(1));
226        let period_ns: u64 = self.display_period_ns().max(1);
227        let prev_ns: u64 = self.get_last_vsync_ns();
228        let dt_ns: u64 = if prev_ns == 0 || timestamp_ns <= prev_ns {
229            period_ns
230        } else {
231            timestamp_ns - prev_ns
232        };
233        if prev_ns != 0 && dt_ns > (period_ns.saturating_mul(3) / 2) {
234            let missed: u64 = (dt_ns / period_ns).saturating_sub(1);
235            stats.set_missed_vsync_intervals(
236                stats.get_missed_vsync_intervals().saturating_add(missed),
237            );
238        }
239        if self.get_in_flight_frames() >= self.get_max_in_flight_frames() {
240            stats.set_in_flight_waits(stats.get_in_flight_waits().saturating_add(1));
241            self.set_stats(stats);
242            return PacingDecision::new(
243                PacingAction::WaitInFlight,
244                0.0,
245                timestamp_ns,
246                0.0,
247                false,
248                false,
249            );
250        }
251        if !self.should_bypass_software_gate()
252            && let Some(cap_hz) = self.active_user_fps_cap()
253            && self.get_last_present_ns() != 0
254        {
255            let cap_period_ns: u64 = (NS_PER_SEC_F64 / (cap_hz as f64)).round() as u64;
256            let elapsed_present: u64 = timestamp_ns.saturating_sub(self.get_last_present_ns());
257            if elapsed_present.saturating_add(period_ns / 4) < cap_period_ns {
258                stats.set_user_cap_skips(stats.get_user_cap_skips().saturating_add(1));
259                self.set_stats(stats);
260                return PacingDecision::new(
261                    PacingAction::SkipUserCap,
262                    0.0,
263                    timestamp_ns,
264                    0.0,
265                    false,
266                    false,
267                );
268            }
269        }
270        let sim_dt_secs: f32 =
271            ((dt_ns as f64) / NS_PER_SEC_F64).clamp(0.0, PACING_MAX_FRAME_DT_SECS as f64) as f32;
272        let input_age_ms: f32 = if self.get_oldest_pending_input_ns() != 0
273            && timestamp_ns >= self.get_oldest_pending_input_ns()
274        {
275            ((timestamp_ns - self.get_oldest_pending_input_ns()) as f64 / 1_000_000.0) as f32
276        } else {
277            0.0
278        };
279        self.set_last_vsync_ns(timestamp_ns);
280        self.set_last_present_ns(timestamp_ns);
281        self.set_oldest_pending_input_ns(0);
282        self.set_pending_input_dirty(false);
283        self.set_pending_layout_dirty(false);
284        self.set_in_flight_frames(self.get_in_flight_frames().saturating_add(1));
285        stats.set_frames_submitted(stats.get_frames_submitted().saturating_add(1));
286        self.set_stats(stats);
287        PacingDecision::new(
288            PacingAction::StepAndRender,
289            sim_dt_secs,
290            timestamp_ns,
291            input_age_ms,
292            true,
293            true,
294        )
295    }
296}