Skip to main content

sg_guest/
display.rs

1//! Presentation settings and HDR output (see `sg_abi::display` and `sg_abi::hdr`).
2//!
3//! Present mode and frame latency can also be set the usual wgpu way, in
4//! `SurfaceConfiguration`; `set_present` changes them later without the game
5//! reconfiguring (the host re-applies the game's configuration). The user's
6//! launch settings always take precedence ([`status::LOCKED`]).
7
8use crate::sys;
9pub use sg_abi::display::{fullscreen as fullscreen_mode, mode, status, HdrMetadata};
10pub use sg_abi::hdr::{negotiate, Output, OutputMode, WGSL as HDR_WGSL};
11
12fn json(f: unsafe extern "C" fn(*mut u8, usize) -> i64) -> serde_json::Value {
13    let mut buf = vec![0u8; 2048];
14    loop {
15        let n = unsafe { f(buf.as_mut_ptr(), buf.len()) };
16        if n < 0 {
17            return serde_json::Value::Null;
18        }
19        if n as usize <= buf.len() {
20            buf.truncate(n as usize);
21            return serde_json::from_slice(&buf).unwrap_or(serde_json::Value::Null);
22        }
23        buf.resize(n as usize, 0);
24    }
25}
26
27/// Present modes, the active mode and latency, frame cap, refresh rate,
28/// fullscreen state, HDR formats and which settings the user locked.
29pub fn info() -> serde_json::Value {
30    json(sys::display_info)
31}
32
33/// Rolling timing statistics (present interval, acquire/present blocking,
34/// display latency where the platform reports present times).
35pub fn stats() -> serde_json::Value {
36    json(sys::frame_stats)
37}
38
39/// `latency` 1..=3, or 0 to keep it.
40pub fn set_present(m: wgpu::PresentMode, latency: u32) -> i32 {
41    unsafe { sys::present_config(m as u32, latency) }
42}
43
44pub fn set_frame_latency(latency: u32) -> i32 {
45    unsafe { sys::present_config(mode::KEEP, latency) }
46}
47
48/// Frames per second; 0 removes the cap.
49pub fn set_frame_cap(fps: f64) -> i32 {
50    unsafe { sys::frame_cap(fps) }
51}
52
53/// Needs a recent user gesture (key or click) and is rate limited.
54pub fn set_fullscreen(m: u32) -> i32 {
55    unsafe { sys::fullscreen(m) }
56}
57
58pub fn set_hdr_metadata(m: &HdrMetadata) -> i32 {
59    let b = m.to_bytes();
60    unsafe { sys::hdr_metadata(b.as_ptr(), b.len()) }
61}
62
63/// Picks format, color space and encoding for `caps` (HDR if offered and `allow_hdr`).
64pub fn negotiate_output(caps: &wgpu::SurfaceCapabilities, allow_hdr: bool) -> Option<Output> {
65    let f: Vec<_> = caps.format_capabilities.iter().map(|fc| (fc.format, fc.color_spaces)).collect();
66    negotiate(&f, allow_hdr, None)
67}