euv-core 0.47.0

Core cross-platform runtime for euv featuring arena-based fine-grained reactivity, deterministic layout, flat scene graph, multi-mode rendering, and direct OS platform adapters.
Documentation
use super::*;

/// Default high-refresh native-VSync-driven `FramePacingController`.
impl Default for FramePacingController {
    /// Creates a `FramePacingController` configured for the default display refresh rate (`120Hz`) with native VSync and bounded in-flight frames.
    ///
    /// # Returns
    ///
    /// - `Self` - Default frame pacing controller.
    fn default() -> Self {
        Self::for_display_hz(PACING_DEFAULT_DISPLAY_HZ)
    }
}

/// Unified VSync pacing, double-gate elimination, clock rebasing, and in-flight tracking for `FramePacingController`.
impl FramePacingController {
    /// Constructs a native-VSync `FramePacingController` tracking `display_hz` uncapped with bounded in-flight frames.
    ///
    /// # Arguments
    ///
    /// - `f32` - Active hardware display refresh rate in Hertz.
    ///
    /// # Returns
    ///
    /// - `Self` - Uncapped display-synchronized frame pacing controller.
    #[must_use]
    pub fn for_display_hz(display_hz: f32) -> Self {
        Self::new(display_hz, true, None, PACING_DEFAULT_MAX_IN_FLIGHT)
    }

    /// Constructs a `FramePacingController` with explicit display rate, VSync ownership, optional user FPS cap, and in-flight bound.
    ///
    /// # Arguments
    ///
    /// - `f32` - Active display refresh rate in Hertz.
    /// - `bool` - Whether native platform VSync already throttles presentation.
    /// - `Option<u32>` - Optional explicit user FPS cap.
    /// - `u32` - Maximum concurrent in-flight frames (`1..=4`).
    ///
    /// # Returns
    ///
    /// - `Self` - Configured frame pacing controller.
    #[must_use]
    pub fn new(
        display_hz: f32,
        native_vsync_active: bool,
        user_fps_cap: Option<u32>,
        max_in_flight_frames: u32,
    ) -> Self {
        Self {
            display_hz: display_hz.clamp(PACING_MIN_DISPLAY_HZ, PACING_MAX_DISPLAY_HZ),
            native_vsync_active,
            user_fps_cap: user_fps_cap.filter(|cap: &u32| *cap > 0),
            max_in_flight_frames: max_in_flight_frames.clamp(1, 4),
            in_flight_frames: 0,
            last_vsync_ns: 0,
            last_submitted_vsync_ns: 0,
            last_present_ns: 0,
            fixed_step_ns: PACING_DEFAULT_FIXED_STEP_NS,
            oldest_pending_input_ns: 0,
            pending_input_dirty: false,
            pending_layout_dirty: false,
            stats: FramePacingStats::default(),
        }
    }

    /// Returns the optional explicit user FPS cap.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Pacing controller reference.
    ///
    /// # Returns
    ///
    /// - `Option<u32>` - Active user FPS cap if set.
    #[must_use]
    pub const fn active_user_fps_cap(&self) -> Option<u32> {
        let Self { user_fps_cap, .. } = *self;
        user_fps_cap
    }

    /// Returns `true` when software sleep/deadline gating should be bypassed because native VSync already paces presentation at or below the target rate.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Pacing controller reference.
    ///
    /// # Returns
    ///
    /// - `bool` - `true` when software waiting must be skipped to avoid double-gating.
    #[must_use]
    pub fn should_bypass_software_gate(&self) -> bool {
        if !self.get_native_vsync_active() {
            return false;
        }
        match self.active_user_fps_cap() {
            None => true,
            Some(cap) => (cap as f32) >= self.get_display_hz() - 0.5,
        }
    }

    /// Returns the nominal display refresh period in nanoseconds.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Pacing controller reference.
    ///
    /// # Returns
    ///
    /// - `u64` - Nominal VSync period in nanoseconds.
    #[must_use]
    pub fn display_period_ns(&self) -> u64 {
        let hz: f64 = self
            .get_display_hz()
            .clamp(PACING_MIN_DISPLAY_HZ, PACING_MAX_DISPLAY_HZ) as f64;
        (NS_PER_SEC_F64 / hz).round() as u64
    }

    /// Updates the display refresh rate mode and rebases the monotonic clock to avoid synthetic dt spikes.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable pacing controller.
    /// - `f32` - New active hardware refresh rate in Hertz.
    /// - `u64` - Current monotonic timestamp in nanoseconds.
    pub fn set_display_mode(&mut self, display_hz: f32, timestamp_ns: u64) {
        self.set_display_hz(display_hz.clamp(PACING_MIN_DISPLAY_HZ, PACING_MAX_DISPLAY_HZ));
        self.rebase_clock(timestamp_ns);
    }

    /// Handles a dynamic OS display refresh-rate switch (e.g. ProMotion or multi-monitor drag) by clamping `new_hz` and resetting the monotonic timebase cleanly.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable pacing controller.
    /// - `f32` - Newly reported hardware display refresh rate in Hertz.
    pub fn on_display_mode_changed(&mut self, new_hz: f32) {
        self.set_display_hz(new_hz.clamp(PACING_MIN_DISPLAY_HZ, PACING_MAX_DISPLAY_HZ));
        self.rebase_clock(0);
    }

    /// Handles application foreground resume by clearing stale VSync timestamps, resetting in-flight backpressure, and preventing post-suspend missed-VSync or dt spikes.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable pacing controller.
    pub fn on_resume(&mut self) {
        self.set_in_flight_frames(0);
        self.set_oldest_pending_input_ns(0);
        self.set_pending_input_dirty(false);
        self.set_pending_layout_dirty(true);
        self.rebase_clock(0);
    }

    /// Rebases the monotonic VSync reference timestamp (e.g. after foreground resume or refresh-rate switch).
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable pacing controller.
    /// - `u64` - Current monotonic timestamp in nanoseconds.
    pub fn rebase_clock(&mut self, timestamp_ns: u64) {
        self.set_last_vsync_ns(timestamp_ns);
        self.set_last_submitted_vsync_ns(0);
        self.set_last_present_ns(0);
        let mut stats: FramePacingStats = self.get_stats();
        stats.set_timebase_rebases(stats.get_timebase_rebases().saturating_add(1));
        self.set_stats(stats);
    }

    /// Notifies the controller that one submitted frame finished presenting, freeing an in-flight slot.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable pacing controller.
    pub fn notify_present_completed(&mut self) {
        let next: u32 = self.get_in_flight_frames().saturating_sub(1);
        self.set_in_flight_frames(next);
    }

    /// Evaluates a scheduling `trigger` at monotonic `timestamp_ns` and returns a single authoritative `PacingDecision`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable pacing controller.
    /// - `FramePacingTrigger` - Incoming scheduling event kind.
    /// - `u64` - Monotonic clock timestamp in nanoseconds.
    ///
    /// # Returns
    ///
    /// - `PacingDecision` - Whether to step simulation, render, wait in flight, or defer to VSync.
    pub fn evaluate(&mut self, trigger: FramePacingTrigger, timestamp_ns: u64) -> PacingDecision {
        match trigger {
            FramePacingTrigger::InputEvent => {
                self.set_pending_input_dirty(true);
                if self.get_oldest_pending_input_ns() == 0 {
                    self.set_oldest_pending_input_ns(timestamp_ns);
                }
                let mut stats: FramePacingStats = self.get_stats();
                stats.set_deferred_non_vsync_events(
                    stats.get_deferred_non_vsync_events().saturating_add(1),
                );
                self.set_stats(stats);
                PacingDecision::new(
                    PacingAction::DeferToNextVsync,
                    0.0,
                    0,
                    timestamp_ns,
                    0.0,
                    false,
                    false,
                )
            }
            FramePacingTrigger::SafeAreaChanged | FramePacingTrigger::FullscreenChanged => {
                self.set_pending_layout_dirty(true);
                let mut stats: FramePacingStats = self.get_stats();
                stats.set_deferred_non_vsync_events(
                    stats.get_deferred_non_vsync_events().saturating_add(1),
                );
                self.set_stats(stats);
                PacingDecision::new(
                    PacingAction::DeferToNextVsync,
                    0.0,
                    0,
                    timestamp_ns,
                    0.0,
                    false,
                    false,
                )
            }
            FramePacingTrigger::TimebaseReset => {
                self.rebase_clock(timestamp_ns);
                PacingDecision::new(
                    PacingAction::DeferToNextVsync,
                    0.0,
                    0,
                    timestamp_ns,
                    0.0,
                    false,
                    false,
                )
            }
            FramePacingTrigger::LifecycleFirstFrame => {
                self.set_pending_layout_dirty(false);
                PacingDecision::new(
                    PacingAction::RenderWithoutSimAdvance,
                    0.0,
                    0,
                    timestamp_ns,
                    0.0,
                    true,
                    false,
                )
            }
            FramePacingTrigger::Vsync => self.evaluate_vsync(timestamp_ns),
        }
    }

    /// Evaluates an authoritative VSync opportunity at monotonic `timestamp_ns`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable pacing controller.
    /// - `u64` - Monotonic VSync timestamp in nanoseconds.
    ///
    /// # Returns
    ///
    /// - `PacingDecision` - Pacing verdict for this VSync interval.
    fn evaluate_vsync(&mut self, timestamp_ns: u64) -> PacingDecision {
        let mut stats: FramePacingStats = self.get_stats();
        stats.set_vsync_signals(stats.get_vsync_signals().saturating_add(1));
        let period_ns: u64 = self.display_period_ns().max(1);
        let prev_vsync_ns: u64 = self.get_last_vsync_ns();
        let raw_vsync_dt_ns: u64 = if prev_vsync_ns == 0 || timestamp_ns <= prev_vsync_ns {
            period_ns
        } else {
            timestamp_ns - prev_vsync_ns
        };
        if prev_vsync_ns != 0 && raw_vsync_dt_ns > (period_ns.saturating_mul(3) / 2) {
            let missed: u64 = (raw_vsync_dt_ns / period_ns).saturating_sub(1);
            stats.set_missed_vsync_intervals(
                stats.get_missed_vsync_intervals().saturating_add(missed),
            );
        }
        self.set_last_vsync_ns(timestamp_ns);
        if self.get_in_flight_frames() >= self.get_max_in_flight_frames() {
            stats.set_in_flight_waits(stats.get_in_flight_waits().saturating_add(1));
            self.set_stats(stats);
            return PacingDecision::new(
                PacingAction::WaitInFlight,
                0.0,
                0,
                timestamp_ns,
                0.0,
                false,
                false,
            );
        }
        let prev_submitted_ns: u64 = self.get_last_submitted_vsync_ns();
        if !self.should_bypass_software_gate()
            && let Some(cap_hz) = self.active_user_fps_cap()
            && prev_submitted_ns != 0
        {
            let cap_period_ns: u64 = (NS_PER_SEC_F64 / (cap_hz as f64)).round() as u64;
            let elapsed_present: u64 = timestamp_ns.saturating_sub(prev_submitted_ns);
            if elapsed_present.saturating_add(period_ns / 4) < cap_period_ns {
                stats.set_user_cap_skips(stats.get_user_cap_skips().saturating_add(1));
                self.set_stats(stats);
                return PacingDecision::new(
                    PacingAction::SkipUserCap,
                    0.0,
                    0,
                    timestamp_ns,
                    0.0,
                    false,
                    false,
                );
            }
        }
        let raw_sim_dt_ns: u64 = if prev_submitted_ns != 0 && timestamp_ns > prev_submitted_ns {
            timestamp_ns - prev_submitted_ns
        } else {
            raw_vsync_dt_ns
        };
        let fixed_ns: u64 = self.get_fixed_step_ns().max(PACING_MIN_FIXED_STEP_NS);
        let max_sim_dt_ns: u64 = fixed_ns
            .saturating_mul(PACING_MAX_SIM_DT_MULT)
            .min(PACING_MAX_FRAME_DT_NS);
        let sim_dt_ns: u64 = raw_sim_dt_ns.min(max_sim_dt_ns);
        let sim_dt_secs: f32 = ((sim_dt_ns as f64) / NS_PER_SEC_F64)
            .clamp(0.0, PACING_MAX_FRAME_DT_SECS as f64) as f32;
        let input_age_ms: f32 = if self.get_oldest_pending_input_ns() != 0
            && timestamp_ns >= self.get_oldest_pending_input_ns()
        {
            ((timestamp_ns - self.get_oldest_pending_input_ns()) as f64 / 1_000_000.0) as f32
        } else {
            0.0
        };
        self.set_last_submitted_vsync_ns(timestamp_ns);
        self.set_last_present_ns(timestamp_ns);
        self.set_oldest_pending_input_ns(0);
        self.set_pending_input_dirty(false);
        self.set_pending_layout_dirty(false);
        self.set_in_flight_frames(self.get_in_flight_frames().saturating_add(1));
        stats.set_frames_submitted(stats.get_frames_submitted().saturating_add(1));
        self.set_stats(stats);
        PacingDecision::new(
            PacingAction::StepAndRender,
            sim_dt_secs,
            sim_dt_ns,
            timestamp_ns,
            input_age_ms,
            true,
            true,
        )
    }
}