siftgl 0.1.0

Memory-safe, ergonomic, zero-dependency, security-hardened OpenGL 3.3-4.6 Core frontend for Rust
Documentation
//! GPU fence synchronization (`GLsync`) and hardware performance/occlusion queries.

use std::fmt;
use std::rc::Rc;

use crate::context::{GlContext, GlInner};
use crate::error::{GlError, Result};
use crate::sys;

/// Outcome of waiting on a [`SyncFence`] from the CPU (`glClientWaitSync`).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum SyncWaitResult {
    /// Fence was already signaled before the wait began (`GL_ALREADY_SIGNALED`).
    AlreadySignaled,
    /// Fence became signaled before the timeout elapsed (`GL_CONDITION_SATISFIED`).
    ConditionSatisfied,
    /// Timeout elapsed before the fence was signaled (`GL_TIMEOUT_EXPIRED`).
    TimeoutExpired,
}

impl SyncWaitResult {
    /// Returns `true` if the GPU work preceding the fence has completed.
    #[inline]
    pub const fn is_signaled(self) -> bool {
        matches!(self, Self::AlreadySignaled | Self::ConditionSatisfied)
    }
}

/// RAII wrapper around an OpenGL 3.2+ GPU fence sync object (`GLsync`).
pub struct SyncFence {
    ctx: Rc<GlInner>,
    raw: sys::GLsync,
}

impl fmt::Debug for SyncFence {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("SyncFence")
            .field("raw", &(self.raw as usize))
            .finish()
    }
}

impl Drop for SyncFence {
    fn drop(&mut self) {
        if !self.raw.is_null() {
            // SAFETY: `self.raw` was created by `glFenceSync` and is exclusively owned.
            unsafe { (self.ctx.fns.delete_sync)(self.raw) };
        }
    }
}

impl SyncFence {
    /// Inserts a GPU fence sync object into the OpenGL command stream (`glFenceSync`).
    pub fn insert(ctx: &GlContext) -> Result<Self> {
        // SAFETY: `GL_SYNC_GPU_COMMANDS_COMPLETE` and `0` are the standard GL 3.2+ arguments.
        let raw = unsafe { (ctx.inner.fns.fence_sync)(sys::GL_SYNC_GPU_COMMANDS_COMPLETE, 0) };
        if raw.is_null() {
            return Err(GlError::ObjectCreationFailed {
                object: "SyncFence",
            });
        }
        Ok(Self {
            ctx: Rc::clone(&ctx.inner),
            raw,
        })
    }

    /// Blocks the CPU until the fence is signaled or `timeout_ns` nanoseconds elapse.
    ///
    /// When `flush` is `true`, passes `GL_SYNC_FLUSH_COMMANDS_BIT` to ensure queued
    /// GPU commands are flushed before waiting.
    pub fn client_wait(&self, timeout_ns: u64, flush: bool) -> Result<SyncWaitResult> {
        let flags = if flush {
            sys::GL_SYNC_FLUSH_COMMANDS_BIT
        } else {
            0
        };
        // SAFETY: `self.raw` is a live `GLsync` handle.
        let status = unsafe { (self.ctx.fns.client_wait_sync)(self.raw, flags, timeout_ns) };
        match status {
            sys::GL_ALREADY_SIGNALED => Ok(SyncWaitResult::AlreadySignaled),
            sys::GL_CONDITION_SATISFIED => Ok(SyncWaitResult::ConditionSatisfied),
            sys::GL_TIMEOUT_EXPIRED => Ok(SyncWaitResult::TimeoutExpired),
            _ => Err(GlError::SyncWaitFailed),
        }
    }

    /// Instructs the GPU command processor to wait on this fence without blocking the CPU (`glWaitSync`).
    pub fn gpu_wait(&self) {
        // SAFETY: `GL_TIMEOUT_IGNORED` and `flags = 0` are required by the OpenGL specification.
        unsafe { (self.ctx.fns.wait_sync)(self.raw, 0, sys::GL_TIMEOUT_IGNORED) };
    }
}

/// Hardware query target type.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[repr(u32)]
pub enum QueryTarget {
    /// Counts fragments passing depth/stencil tests (`GL_SAMPLES_PASSED`).
    SamplesPassed = sys::GL_SAMPLES_PASSED,
    /// Boolean occlusion query (`GL_ANY_SAMPLES_PASSED`).
    AnySamplesPassed = sys::GL_ANY_SAMPLES_PASSED,
    /// Counts primitives emitted by geometry stage (`GL_PRIMITIVES_GENERATED`).
    PrimitivesGenerated = sys::GL_PRIMITIVES_GENERATED,
    /// GPU elapsed time in nanoseconds (`GL_TIME_ELAPSED`).
    TimeElapsed = sys::GL_TIME_ELAPSED,
}

/// RAII wrapper around an OpenGL hardware query object.
pub struct Query {
    ctx: Rc<GlInner>,
    id: sys::GLuint,
    target: QueryTarget,
}

impl fmt::Debug for Query {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Query")
            .field("id", &self.id)
            .field("target", &self.target)
            .finish()
    }
}

impl Drop for Query {
    fn drop(&mut self) {
        if self.id != 0 {
            // SAFETY: `self.id` is exclusively owned by this `Query`.
            unsafe { (self.ctx.fns.delete_queries)(1, &self.id) };
        }
    }
}

impl Query {
    /// Allocates a new hardware query object for `target`.
    pub fn new(ctx: &GlContext, target: QueryTarget) -> Result<Self> {
        let mut id: sys::GLuint = 0;
        // SAFETY: Generates one query name in valid stack storage.
        unsafe { (ctx.inner.fns.gen_queries)(1, &mut id) };
        if id == 0 {
            return Err(GlError::ObjectCreationFailed { object: "Query" });
        }
        Ok(Self {
            ctx: Rc::clone(&ctx.inner),
            id,
            target,
        })
    }

    /// Returns the raw OpenGL query ID.
    #[inline]
    pub const fn raw_id(&self) -> u32 {
        self.id
    }

    /// Begins recording hardware metrics for this query (`glBeginQuery`).
    pub fn begin(&self) -> Result<()> {
        // SAFETY: `self.target` and `self.id` are valid.
        unsafe { (self.ctx.fns.begin_query)(self.target as sys::GLenum, self.id) };
        self.ctx.check_gl_error("glBeginQuery")
    }

    /// Ends recording hardware metrics for this query (`glEndQuery`).
    pub fn end(&self) -> Result<()> {
        // SAFETY: `self.target` is valid.
        unsafe { (self.ctx.fns.end_query)(self.target as sys::GLenum) };
        self.ctx.check_gl_error("glEndQuery")
    }

    /// Returns `true` if the query result is ready without blocking (`GL_QUERY_RESULT_AVAILABLE`).
    pub fn is_available(&self) -> bool {
        let mut available: sys::GLuint = 0;
        // SAFETY: Valid stack pointer for `glGetQueryObjectuiv`.
        unsafe {
            (self.ctx.fns.get_query_objectuiv)(
                self.id,
                sys::GL_QUERY_RESULT_AVAILABLE,
                &mut available,
            );
        }
        available != 0
    }

    /// Retrieves the 32-bit unsigned query result, blocking if not yet available.
    pub fn result_u32(&self) -> u32 {
        let mut val: sys::GLuint = 0;
        // SAFETY: Valid stack pointer for `glGetQueryObjectuiv`.
        unsafe {
            (self.ctx.fns.get_query_objectuiv)(self.id, sys::GL_QUERY_RESULT, &mut val);
        }
        val
    }

    /// Retrieves the 64-bit unsigned query result (OpenGL 3.3+ `glGetQueryObjectui64v`).
    pub fn result_u64(&self) -> Result<u64> {
        let Some(get_ui64) = self.ctx.fns.get_query_objectui64v else {
            return Err(GlError::MissingFunction {
                name: "glGetQueryObjectui64v",
            });
        };
        let mut val: sys::GLuint64 = 0;
        // SAFETY: Valid stack pointer for `glGetQueryObjectui64v`.
        unsafe { get_ui64(self.id, sys::GL_QUERY_RESULT, &mut val) };
        Ok(val)
    }

    /// Records the current GPU timestamp into this query object (`glQueryCounter`, OpenGL 3.3+).
    pub fn record_timestamp(&self) -> Result<()> {
        let Some(query_counter) = self.ctx.fns.query_counter else {
            return Err(GlError::MissingFunction {
                name: "glQueryCounter",
            });
        };
        // SAFETY: `self.id` is a valid query handle and `GL_TIMESTAMP` is the only valid target.
        unsafe { query_counter(self.id, sys::GL_TIMESTAMP) };
        self.ctx.check_gl_error("glQueryCounter")
    }
}