use core::cell::Cell;
use core::ffi::{CStr, c_void};
use core::fmt;
use core::marker::PhantomData;
use core::num::NonZeroU64;
use core::sync::atomic::{AtomicU64, Ordering};
use nadir_core::UVec2;
use crate::PlatformError;
#[cfg(target_os = "linux")]
use crate::linux::Headless;
#[cfg(not(target_os = "linux"))]
use crate::no_gl::NoHeadless as Headless;
#[non_exhaustive]
#[derive(Clone, Copy)]
pub enum GpuSurface<'a> {
Gl(&'a dyn GlContext),
}
impl fmt::Debug for GpuSurface<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Gl(_) => f.write_str("GpuSurface::Gl(..)"),
}
}
}
pub unsafe trait GlContext {
fn get_proc_address(&self, name: &CStr) -> *const c_void;
fn swap_buffers(&self) -> Result<(), PlatformError>;
fn set_swap_interval(&self, interval: i32) -> bool;
fn drawable_size(&self) -> UVec2;
fn context_id(&self) -> Option<GlContextId> {
None
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct GlContextId(NonZeroU64);
impl GlContextId {
pub fn is_current(self) -> bool {
CURRENT
.try_with(|current| current.get() == Some(self))
.unwrap_or(false)
}
}
thread_local! {
static CURRENT: Cell<Option<GlContextId>> = const { Cell::new(None) };
}
static NEXT_ID: AtomicU64 = AtomicU64::new(1);
#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
pub(crate) struct Claim {
id: GlContextId,
_thread: PhantomData<*const ()>,
}
#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
impl Claim {
pub(crate) fn take() -> Result<Self, PlatformError> {
if CURRENT.with(Cell::get).is_some() {
return Err(PlatformError::GlContextExists);
}
let next = NEXT_ID.fetch_add(1, Ordering::Relaxed);
let id = GlContextId(NonZeroU64::new(next).unwrap_or(NonZeroU64::MAX));
CURRENT.with(|current| current.set(Some(id)));
Ok(Self {
id,
_thread: PhantomData,
})
}
pub(crate) fn id(&self) -> GlContextId {
self.id
}
}
impl Drop for Claim {
fn drop(&mut self) {
let _ = CURRENT.try_with(|current| current.set(None));
}
}
pub struct HeadlessGl {
inner: Headless,
_thread: PhantomData<*const ()>,
}
impl fmt::Debug for HeadlessGl {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("HeadlessGl { .. }")
}
}
unsafe impl GlContext for HeadlessGl {
fn get_proc_address(&self, name: &CStr) -> *const c_void {
self.inner.get_proc_address(name)
}
fn swap_buffers(&self) -> Result<(), PlatformError> {
Ok(())
}
fn set_swap_interval(&self, _interval: i32) -> bool {
false
}
fn drawable_size(&self) -> UVec2 {
UVec2::ZERO
}
fn context_id(&self) -> Option<GlContextId> {
Some(self.inner.id())
}
}
pub fn create_headless_gl() -> Result<HeadlessGl, PlatformError> {
Ok(HeadlessGl {
inner: Headless::new()?,
_thread: PhantomData,
})
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_thread_claims_one_context_at_a_time() {
let claim = Claim::take().unwrap();
assert_eq!(Claim::take().err(), Some(PlatformError::GlContextExists));
std::thread::spawn(|| assert!(Claim::take().is_ok()))
.join()
.unwrap();
drop(claim);
assert!(Claim::take().is_ok());
}
#[test]
fn an_id_is_current_only_while_its_claim_exists_on_its_thread() {
let claim = Claim::take().unwrap();
let id = claim.id();
assert!(id.is_current());
std::thread::spawn(move || assert!(!id.is_current()))
.join()
.unwrap();
drop(claim);
assert!(!id.is_current());
let next = Claim::take().unwrap();
assert_ne!(next.id(), id);
assert!(next.id().is_current());
assert!(!id.is_current());
}
}