Skip to content

The native runtime for three.js: three.js, down to the metal. 45× smaller than Electron, on a Sony PS3, and path-traced at 60 fps on ray-tracing GPUs.

8.0 KB
Raw Blame
//! The process-wide wgpu instance/adapter/device/queue, and the error sink that turns wgpu's
//! errors into WebGPU error scopes and `uncapturederror` events.
use std::sync::{Mutex, OnceLock};

use crate::fmt;

/// The shared GPU: one Metal device for the whole process (JS pages and the host's own
/// renderers use the same `Device`/`Queue`).
pub struct Gpu {
    pub instance: wgpu::Instance,
    pub adapter: wgpu::Adapter,
    pub device: wgpu::Device,
    pub queue: wgpu::Queue,
    /// WebGPU names of the features pages see (subset of the device's features)
    pub js_features: Vec<&'static str>,
}

/// Options for [`crate::init`].
#[derive(Clone, Debug)]
pub struct GpuOptions {
    /// Extra wgpu features the host's own renderers need (requested only if the adapter has them).
    pub extra_features: wgpu::Features,
    /// `wgpu::InstanceFlags` debug/validation (default: off; `THREERT_WGPU_DEBUG=1` turns it on).
    pub debug: bool,
    /// Adapter power preference (`HighPerformance` by default; `LowPower` for ambient/wallpaper hosts).
    pub power_preference: wgpu::PowerPreference,
    /// Memory allocation hint (`Performance` by default; `MemoryUsage` for low-footprint hosts).
    pub memory_hints: wgpu::MemoryHints,
}

impl Default for GpuOptions {
    fn default() -> Self {
        Self {
            extra_features: wgpu::Features::empty(),
            debug: false,
            power_preference: wgpu::PowerPreference::HighPerformance,
            memory_hints: wgpu::MemoryHints::Performance,
        }
    }
}

static GPU: OnceLock<Gpu> = OnceLock::new();
static INIT: Mutex<()> = Mutex::new(());

pub fn init(opts: &GpuOptions) -> Result<&'static Gpu, String> {
    let _guard = INIT.lock().unwrap_or_else(|e| e.into_inner());
    if let Some(g) = GPU.get() {
        return Ok(g);
    }
    let debug = opts.debug || std::env::var_os("THREERT_WGPU_DEBUG").is_some() || std::env::var_os("POCKET_WGPU_DEBUG").is_some();
    let instance = wgpu::Instance::new(&wgpu::InstanceDescriptor {
        backends: wgpu::Backends::PRIMARY,
        flags: if debug { wgpu::InstanceFlags::debugging() } else { wgpu::InstanceFlags::empty() },
        ..Default::default()
    });
    let adapter = pollster::block_on(instance.request_adapter(&wgpu::RequestAdapterOptions {
        power_preference: opts.power_preference,
        force_fallback_adapter: false,
        compatible_surface: None,
    }))
    .map_err(|e| format!("no GPU adapter: {e}"))?;
    let have = adapter.features();
    let mut want = opts.extra_features & have;
    let mut js_features = vec!["core-features-and-limits"];
    for (name, f) in fmt::FEATURES {
        if have.contains(*f) {
            want |= *f;
            js_features.push(name);
        }
    }
    let (device, queue) = pollster::block_on(adapter.request_device(&wgpu::DeviceDescriptor {
        label: Some("threert-webgpu"),
        required_features: want,
        required_limits: adapter.limits(),
        memory_hints: opts.memory_hints.clone(),
        trace: wgpu::Trace::Off,
    }))
    .map_err(|e| format!("request_device: {e}"))?;
    device.on_uncaptured_error(Box::new(|e| sink_wgpu(e)));
    device.set_device_lost_callback(|reason, msg| {
        if !matches!(reason, wgpu::DeviceLostReason::Destroyed) {
            eprintln!("[webgpu] device lost: {msg}");
            *LOST.lock().unwrap_or_else(|e| e.into_inner()) = Some(msg);
        }
    });
    let _ = GPU.set(Gpu { instance, adapter, device, queue, js_features });
    Ok(GPU.get().unwrap())
}

pub fn get() -> Option<&'static Gpu> {
    GPU.get()
}

/// Set when the device is lost (reported to pages through `GPUDevice.lost`).
pub static LOST: Mutex<Option<String>> = Mutex::new(None);

// ------------------------------------------------------------------------------------------ errors

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ErrKind {
    Validation = 0,
    OutOfMemory = 1,
    Internal = 2,
}

impl ErrKind {
    pub fn from_filter(s: &str) -> Option<ErrKind> {
        match s {
            "validation" => Some(ErrKind::Validation),
            "out-of-memory" => Some(ErrKind::OutOfMemory),
            "internal" => Some(ErrKind::Internal),
            _ => None,
        }
    }
}

#[derive(Default)]
struct Sink {
    /// WebGPU error scopes of the page (innermost last): filter and first captured error
    scopes: Vec<(ErrKind, Option<(ErrKind, String)>)>,
    uncaptured: Vec<(ErrKind, String)>,
    /// >0 while the binding performs internal operations whose errors must not reach the page
    suppress: u32,
    logged: u32,
}

static SINK: Mutex<Sink> = Mutex::new(Sink { scopes: Vec::new(), uncaptured: Vec::new(), suppress: 0, logged: 0 });

fn sink() -> std::sync::MutexGuard<'static, Sink> {
    SINK.lock().unwrap_or_else(|e| e.into_inner())
}

pub(crate) fn sink_wgpu(e: wgpu::Error) {
    let (kind, msg) = match e {
        wgpu::Error::OutOfMemory { source } => (ErrKind::OutOfMemory, source.to_string()),
        wgpu::Error::Validation { description, .. } => (ErrKind::Validation, description),
        wgpu::Error::Internal { description, .. } => (ErrKind::Internal, description),
    };
    report(kind, msg);
}

/// Report an error the WebGPU way: into the innermost matching error scope, else as an
/// uncaptured error (logged, and dispatched to the page's `onuncapturederror`).
pub fn report(kind: ErrKind, msg: String) {
    let mut s = sink();
    if s.suppress > 0 {
        return;
    }
    if let Some(scope) = s.scopes.iter_mut().rev().find(|(f, _)| *f == kind) {
        if scope.1.is_none() {
            scope.1 = Some((kind, msg));
        }
        return;
    }
    if s.logged < 64 {
        s.logged += 1;
        eprintln!("[webgpu] uncaptured {kind:?} error: {msg}");
    }
    if s.uncaptured.len() < 256 {
        s.uncaptured.push((kind, msg));
    }
}

pub fn validation(msg: impl Into<String>) {
    report(ErrKind::Validation, msg.into());
}

pub fn push_scope(filter: ErrKind) {
    sink().scopes.push((filter, None));
}

/// `Err` when the stack is empty (an OperationError for the page).
pub fn pop_scope() -> Result<Option<(ErrKind, String)>, ()> {
    sink().scopes.pop().map(|(_, e)| e).ok_or(())
}

pub fn take_uncaptured() -> Vec<(ErrKind, String)> {
    std::mem::take(&mut sink().uncaptured)
}

pub fn has_uncaptured() -> bool {
    !sink().uncaptured.is_empty()
}

/// Run `f` with errors swallowed (internal bookkeeping calls that may legitimately fail).
pub fn quietly<R>(f: impl FnOnce() -> R) -> R {
    sink().suppress += 1;
    let r = f();
    sink().suppress -= 1;
    r
}

/// Run `f` inside a private validation scope; returns its result and the first error.
pub fn capture<R>(f: impl FnOnce() -> R) -> (R, Option<String>) {
    push_scope(ErrKind::Validation);
    push_scope(ErrKind::Internal);
    push_scope(ErrKind::OutOfMemory);
    let r = f();
    let mut first = None;
    for _ in 0..3 {
        if let Ok(Some((_, m))) = pop_scope() {
            first.get_or_insert(m);
        }
    }
    (r, first)
}

/// Drop the page's scopes and queued errors (page reset).
pub fn reset_errors() {
    let mut s = sink();
    s.scopes.clear();
    s.uncaptured.clear();
    s.logged = 0;
}

#[cfg(test)]
mod tests {
    use super::*;
    #[test]
    fn scopes_capture_by_filter() {
        reset_errors();
        push_scope(ErrKind::Validation);
        push_scope(ErrKind::OutOfMemory);
        report(ErrKind::Validation, "a".into());
        report(ErrKind::Validation, "b".into());
        assert_eq!(pop_scope(), Ok(None), "the OOM scope saw nothing");
        assert_eq!(pop_scope(), Ok(Some((ErrKind::Validation, "a".into()))), "first error wins");
        assert_eq!(pop_scope(), Err(()), "empty stack");
        report(ErrKind::Internal, "c".into());
        assert!(has_uncaptured());
        assert_eq!(take_uncaptured(), vec![(ErrKind::Internal, "c".into())]);
        quietly(|| report(ErrKind::Validation, "d".into()));
        assert!(!has_uncaptured());
        let ((), e) = capture(|| validation("e"));
        assert_eq!(e.as_deref(), Some("e"));
        assert!(!has_uncaptured());
    }
}