Skip to main content

strata_platform/
surface.rs

1//! Abstract hardware presentation surfaces, swapchain configuration, and frame pacing.
2
3use std::time::{Duration, Instant};
4
5pub use strata_render::swapchain::{
6    PresentError, SoftwareSurfacePresenter, SurfacePresenter, SwapchainCompositor, SwapchainFormat,
7};
8
9/// Presentation mode defining how swapchain images are presented to the display server.
10#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
11pub enum PresentMode {
12    /// Presentation happens immediately without waiting for vertical blanking (may tear).
13    Immediate,
14    /// Triple-buffering with lowest input latency: unpresented frames are replaced by newer frames.
15    Mailbox,
16    /// Standard VSync FIFO presentation queue (zero tearing, 60/120 FPS capped).
17    #[default]
18    Fifo,
19    /// VSync FIFO with adaptive tearing if frame deadline is missed.
20    FifoRelaxed,
21}
22
23/// Target display refresh rate for frame pacing and VSync synchronization.
24#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
25pub enum RefreshRate {
26    #[default]
27    Hz60,
28    Hz90,
29    Hz120,
30    Hz144,
31    Custom(u32),
32}
33
34impl RefreshRate {
35    /// Returns integer frequency in Hertz.
36    pub const fn as_hz(&self) -> u32 {
37        match self {
38            Self::Hz60 => 60,
39            Self::Hz90 => 90,
40            Self::Hz120 => 120,
41            Self::Hz144 => 144,
42            Self::Custom(hz) => *hz,
43        }
44    }
45
46    /// Frame duration interval for this refresh rate.
47    pub fn frame_interval(&self) -> Duration {
48        let hz = self.as_hz().max(1);
49        Duration::from_nanos(1_000_000_000 / hz as u64)
50    }
51}
52
53/// Configuration descriptor for a presentation surface and its swapchain.
54#[derive(Debug, Clone)]
55pub struct SurfaceConfig {
56    pub width: u32,
57    pub height: u32,
58    pub scale_factor: f32,
59    pub format: SwapchainFormat,
60    pub present_mode: PresentMode,
61    pub refresh_rate: RefreshRate,
62}
63
64impl Default for SurfaceConfig {
65    fn default() -> Self {
66        Self {
67            width: 1280,
68            height: 800,
69            scale_factor: 1.0,
70            format: SwapchainFormat::Bgra8Unorm,
71            present_mode: PresentMode::Fifo,
72            refresh_rate: RefreshRate::Hz60,
73        }
74    }
75}
76
77impl SurfaceConfig {
78    /// Physical width in backing store pixels: ⌈logical_width * scale_factor⌉.
79    pub fn physical_width(&self) -> u32 {
80        ((self.width as f32 * self.scale_factor) + 0.5) as u32
81    }
82
83    /// Physical height in backing store pixels: ⌈logical_height * scale_factor⌉.
84    pub fn physical_height(&self) -> u32 {
85        ((self.height as f32 * self.scale_factor) + 0.5) as u32
86    }
87
88    /// Physical dimensions as (width, height) tuple.
89    pub fn physical_size(&self) -> (u32, u32) {
90        (self.physical_width(), self.physical_height())
91    }
92
93    /// Total byte footprint for a single physical frame buffer at this configuration.
94    pub fn buffer_byte_size(&self) -> usize {
95        let (pw, ph) = self.physical_size();
96        (pw as usize) * (ph as usize) * self.format.bytes_per_pixel()
97    }
98}
99
100/// Frame pacing coordinator that stabilizes frame presentation deadlines and calculates sleep intervals.
101#[derive(Debug, Clone)]
102pub struct FramePacer {
103    pub target_refresh: RefreshRate,
104    pub frame_interval: Duration,
105    pub last_frame_instant: Option<Instant>,
106    pub average_frame_duration: Duration,
107    pub frame_count: u64,
108}
109
110impl FramePacer {
111    /// Creates a new frame pacer locked to the given target refresh rate.
112    pub fn new(target_refresh: RefreshRate) -> Self {
113        let frame_interval = target_refresh.frame_interval();
114        Self {
115            target_refresh,
116            frame_interval,
117            last_frame_instant: None,
118            average_frame_duration: Duration::from_micros(500),
119            frame_count: 0,
120        }
121    }
122
123    /// Marks the beginning of a frame tick, returning the current timestamp.
124    pub fn begin_frame(&mut self) -> Instant {
125        Instant::now()
126    }
127
128    /// Marks the completion of a frame, updating exponential moving average of frame duration.
129    pub fn end_frame(&mut self, frame_start: Instant) -> Duration {
130        let duration = frame_start.elapsed();
131        self.frame_count += 1;
132        self.last_frame_instant = Some(Instant::now());
133
134        // EWMA update with alpha = 0.2
135        let alpha = 0.2;
136        let prev_micros = self.average_frame_duration.as_micros() as f64;
137        let curr_micros = duration.as_micros() as f64;
138        let new_micros = (alpha * curr_micros + (1.0 - alpha) * prev_micros).max(10.0);
139        self.average_frame_duration = Duration::from_micros(new_micros as u64);
140
141        duration
142    }
143
144    /// Computes duration until next VSync deadline to avoid busy spinning.
145    pub fn duration_until_next_deadline(&self) -> Duration {
146        if let Some(last) = self.last_frame_instant {
147            let elapsed = last.elapsed();
148            if elapsed < self.frame_interval {
149                self.frame_interval - elapsed
150            } else {
151                Duration::ZERO
152            }
153        } else {
154            Duration::ZERO
155        }
156    }
157
158    /// Synchronizes execution with the hardware VSync signal or refresh rate deadline.
159    pub fn wait_vsync(&mut self) {
160        #[cfg(windows)]
161        {
162            unsafe {
163                extern "system" {
164                    fn LoadLibraryA(lpLibFileName: *const u8) -> *mut std::ffi::c_void;
165                    fn GetProcAddress(
166                        hModule: *mut std::ffi::c_void,
167                        lpProcName: *const u8,
168                    ) -> *mut std::ffi::c_void;
169                    fn FreeLibrary(hLibModule: *mut std::ffi::c_void) -> i32;
170                }
171                let dwmapi = LoadLibraryA(b"dwmapi.dll\0".as_ptr());
172                if !dwmapi.is_null() {
173                    let proc = GetProcAddress(dwmapi, b"DwmFlush\0".as_ptr());
174                    if !proc.is_null() {
175                        let dwm_flush: unsafe extern "system" fn() -> i32 =
176                            std::mem::transmute(proc);
177                        let _ = dwm_flush();
178                    }
179                    FreeLibrary(dwmapi);
180                }
181            }
182        }
183
184        // High-precision deadline sleep for remaining duration until next frame
185        let remaining = self.duration_until_next_deadline();
186        if remaining > Duration::from_micros(500) {
187            std::thread::sleep(remaining - Duration::from_micros(250));
188        }
189        // Sub-millisecond spin loop to nail the deadline
190        while self.duration_until_next_deadline() > Duration::ZERO {
191            std::hint::spin_loop();
192        }
193        self.last_frame_instant = Some(Instant::now());
194    }
195}
196
197/// Abstract opaque handle to a native window surface for presentation.
198#[derive(Debug, Clone, Copy, PartialEq, Eq)]
199pub struct SurfaceHandle {
200    pub window_id: u64,
201    pub raw_window_ptr: usize,
202    pub raw_display_ptr: usize,
203    pub width: u32,
204    pub height: u32,
205    pub scale_factor_snapped: u32, // Fixed-point 1/64th scale factor
206}
207
208impl SurfaceHandle {
209    /// Creates a headless surface handle for testing, CI automation, and offscreen rendering.
210    pub fn new_headless(width: u32, height: u32, scale_factor: f32) -> Self {
211        Self {
212            window_id: 1,
213            raw_window_ptr: 0,
214            raw_display_ptr: 0,
215            width,
216            height,
217            scale_factor_snapped: (scale_factor * 64.0) as u32,
218        }
219    }
220
221    /// Scale factor as a floating-point multiplier.
222    pub fn scale_factor(&self) -> f32 {
223        self.scale_factor_snapped as f32 / 64.0
224    }
225}