libbhoo 0.3.1

Minimal UI foundations for SpectreOS
Documentation
//! Opt-in asynchronous GLES GPU timer queries (`GL_EXT_disjoint_timer_query`).
//! Zero overhead when disabled; never calls `glFinish` or blocks during timed runs.

use glow::HasContext;
use std::collections::VecDeque;

const MAX_IN_FLIGHT: usize = 8;
const GPU_DISJOINT_EXT: u32 = 0x8FBB;

#[derive(Clone, Copy, Debug)]
pub struct GpuFrameTiming {
    pub frame: u64,
    pub bg_ns: Option<u64>,
    pub fg_ns: Option<u64>,
    pub disjoint: bool,
}

struct PendingSlot {
    frame: u64,
    bg: Option<glow::Query>,
    fg: Option<glow::Query>,
}

pub(super) struct GpuTimers {
    supported: bool,
    enabled: bool,
    pool: Vec<glow::Query>,
    in_flight: VecDeque<PendingSlot>,
    active_bg: Option<glow::Query>,
    active_fg: Option<glow::Query>,
    current_frame: u64,
    frame_active: bool,
}

impl GpuTimers {
    pub(super) fn new(gl: &glow::Context) -> Self {
        let supported = gl
            .supported_extensions()
            .contains("GL_EXT_disjoint_timer_query");
        Self {
            supported,
            enabled: false,
            pool: Vec::new(),
            in_flight: VecDeque::new(),
            active_bg: None,
            active_fg: None,
            current_frame: 0,
            frame_active: false,
        }
    }

    pub(super) fn supported(&self) -> bool {
        self.supported
    }

    pub(super) fn has_pending(&self) -> bool {
        !self.in_flight.is_empty()
    }

    pub(super) fn set_enabled(&mut self, gl: &glow::Context, enabled: bool) {
        if !self.supported {
            self.enabled = false;
            return;
        }
        self.enabled = enabled;
        if enabled {
            // Clear any sticky disjoint flag once before starting measurements.
            unsafe {
                let _ = gl.get_parameter_i32(GPU_DISJOINT_EXT);
                while gl.get_error() != glow::NO_ERROR {}
            }
        }
    }

    fn alloc_query(&mut self, gl: &glow::Context) -> Option<glow::Query> {
        if let Some(q) = self.pool.pop() {
            return Some(q);
        }
        // SAFETY: caller holds current GLES context.
        unsafe { gl.create_query().ok() }
    }

    pub(super) fn begin_frame(&mut self, frame: u64) {
        self.current_frame = frame;
        self.active_bg = None;
        self.active_fg = None;
        self.frame_active = self.enabled && self.supported && self.in_flight.len() < MAX_IN_FLIGHT;
    }

    pub(super) fn begin_bg(&mut self, gl: &glow::Context) {
        if !self.frame_active {
            return;
        }
        if let Some(q) = self.alloc_query(gl) {
            // SAFETY: GL_EXT_disjoint_timer_query is checked; query is not currently active.
            unsafe {
                gl.begin_query(glow::TIME_ELAPSED, q);
            }
            self.active_bg = Some(q);
        }
    }

    pub(super) fn end_bg(&mut self, gl: &glow::Context) {
        if self.active_bg.is_some() {
            // SAFETY: matches active begin_bg.
            unsafe {
                gl.end_query(glow::TIME_ELAPSED);
            }
        }
    }

    pub(super) fn begin_fg(&mut self, gl: &glow::Context) {
        if !self.frame_active {
            return;
        }
        if let Some(q) = self.alloc_query(gl) {
            // SAFETY: bg query has already ended before fg starts.
            unsafe {
                gl.begin_query(glow::TIME_ELAPSED, q);
            }
            self.active_fg = Some(q);
        }
    }

    pub(super) fn end_fg(&mut self, gl: &glow::Context) {
        if self.active_fg.is_some() {
            // SAFETY: matches active begin_fg.
            unsafe {
                gl.end_query(glow::TIME_ELAPSED);
            }
        }
    }

    pub(super) fn finish_frame(&mut self) {
        if !self.frame_active {
            return;
        }
        if self.active_bg.is_some() || self.active_fg.is_some() {
            self.in_flight.push_back(PendingSlot {
                frame: self.current_frame,
                bg: self.active_bg.take(),
                fg: self.active_fg.take(),
            });
        }
        self.frame_active = false;
    }

    fn query_ready(gl: &glow::Context, q: glow::Query) -> bool {
        // SAFETY: GL_EXT_disjoint_timer_query is active; non-blocking availability check.
        unsafe { gl.get_query_parameter_u32(q, glow::QUERY_RESULT_AVAILABLE) != 0 }
    }

    fn read_query_ns(gl: &glow::Context, q: glow::Query) -> u64 {
        let mut ns: u64 = 0;
        // SAFETY: no GL_QUERY_BUFFER is bound, so the pointer receives the 64-bit ns value directly.
        unsafe {
            gl.get_query_parameter_u64_with_offset(
                q,
                glow::QUERY_RESULT,
                (&mut ns as *mut u64) as usize,
            );
        }
        ns
    }

    pub(super) fn drain(&mut self, gl: &glow::Context) -> Vec<GpuFrameTiming> {
        let mut out = Vec::new();
        if !self.supported || self.in_flight.is_empty() {
            return out;
        }
        while let Some(front) = self.in_flight.front() {
            let bg_ok = front.bg.is_none_or(|q| Self::query_ready(gl, q));
            let fg_ok = front.fg.is_none_or(|q| Self::query_ready(gl, q));
            if !(bg_ok && fg_ok) {
                break;
            }
            let slot = self.in_flight.pop_front().unwrap();
            let bg_ns = slot.bg.map(|q| {
                let v = Self::read_query_ns(gl, q);
                self.pool.push(q);
                v
            });
            let fg_ns = slot.fg.map(|q| {
                let v = Self::read_query_ns(gl, q);
                self.pool.push(q);
                v
            });
            let disjoint = unsafe { gl.get_parameter_i32(GPU_DISJOINT_EXT) != 0 };
            out.push(GpuFrameTiming {
                frame: slot.frame,
                bg_ns,
                fg_ns,
                disjoint,
            });
        }
        out
    }

    pub(super) fn destroy(&mut self, gl: &glow::Context) {
        // SAFETY: caller drops renderer while GLES context is still current.
        unsafe {
            for q in self.pool.drain(..) {
                gl.delete_query(q);
            }
            for slot in self.in_flight.drain(..) {
                if let Some(q) = slot.bg {
                    gl.delete_query(q);
                }
                if let Some(q) = slot.fg {
                    gl.delete_query(q);
                }
            }
            if let Some(q) = self.active_bg.take() {
                gl.delete_query(q);
            }
            if let Some(q) = self.active_fg.take() {
                gl.delete_query(q);
            }
        }
    }
}