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.

16.7 KB
Raw Blame
//! WebGPU (`navigator.gpu`) for the JavaScriptCore runtime, over wgpu 25 on Metal.
//!
//! `runtime/webgpu.ts` defines the JS objects (`GPUDevice`, `GPUBuffer`, …); every native-backed
//! object is an integer id into a per-page slab ([`res::Slab`]). The binding is shaped for
//! three.js's `WebGPURenderer` at native speed:
//!
//! * **Command encoders are recorded in JS.** Pass commands (setPipeline / setBindGroup /
//!   setVertexBuffer / draw* / …) and copies append words to a typed-array stream; `finish()`
//!   hands the stream over in one call and [`cmd::encode`] replays it into wgpu. A frame costs
//!   one native call per command encoder plus one per `queue.submit`, not one per command.
//! * **`queue.writeBuffer` is batched.** Data is copied (read in place from the typed array)
//!   into a staging blob; at `submit` the blob goes to the GPU with one `write_buffer` and the
//!   writes become `copy_buffer_to_buffer` commands ahead of the submitted command buffers (wgpu
//!   allocates a staging buffer per `write_buffer`, which dominates with hundreds of uniform
//!   updates per frame).
//! * Creation calls with big dictionaries (pipelines, layouts, bind groups, textures) pass JSON.
//!
//! Errors follow WebGPU: wgpu validation errors land in the page's error scopes or become
//! `uncapturederror` events ([`gpu::report`]); bad input never panics (ranges that wgpu would
//! panic on are validated here first).
//!
//! # Host API
//!
//! ```ignore
//! // once per process, before the first page (Metal, high-performance adapter):
//! let gpu = webgpu::init(&webgpu::GpuOptions::default())?;
//! // the PocketJS UI renderer shares the device:
//! let (device, queue) = (webgpu::device(), webgpu::queue());
//!
//! // per page, next to the other modules:
//! webgpu::install(ctx, native);            // defines __native.gpu; runtime.js mounts navigator.gpu
//!
//! // per frame:
//! let frame = surface.get_current_texture()?;
//! webgpu::set_window_target(&frame.texture, logical_w, logical_h);
//! /* __rt.frame(now): the page renders into __pocketGpuCanvas */
//! let out = webgpu::end_window_frame();     // flushes, blits if needed, releases the texture
//! if out.drew { /* composite the UI over frame.texture (out.opaque: ignore its alpha) */ }
//! frame.present();
//! ```
//!
//! The window canvas (`globalThis.__pocketGpuCanvas`) renders **directly** into the host texture
//! when the page configured the host texture's format (see `getPreferredCanvasFormat()`, which
//! returns it), its size matches `canvas.width/height`, and the host texture's usage covers the
//! configured usage (three.js asks for `RENDER_ATTACHMENT | COPY_SRC`). Otherwise the page renders
//! into an intermediate texture that [`end_window_frame`] scales/converts into the target.
//!
//! Headless: [`Offscreen`] owns a target texture and reads it back as RGBA8.
//!
//! The device's uncaptured-error handler belongs to this crate; host renderers that want their
//! own errors should use wgpu error scopes (they take precedence over the handler).
use std::cell::RefCell;
use std::mem::ManuallyDrop;
use std::sync::Mutex;
use std::sync::atomic::{AtomicU64, Ordering};
use std::time::Duration;

use jsc::{Ctx, Value};

mod args;
mod canvas;
pub mod cmd;
pub mod desc;
pub mod fmt;
pub mod gpu;
pub mod image;
mod js;
pub mod res;

pub use gpu::{Gpu, GpuOptions};

use canvas::{Blitter, Canvas, Target};
use res::Slab;

/// Create the process-wide instance/adapter/device/queue (idempotent).
pub fn init(opts: &GpuOptions) -> Result<&'static Gpu, String> {
    gpu::init(opts)
}

fn g() -> &'static Gpu {
    gpu::get().expect("webgpu::init() must be called first")
}
pub fn gpu() -> Option<&'static Gpu> {
    gpu::get()
}
pub fn instance() -> &'static wgpu::Instance {
    &g().instance
}
pub fn adapter() -> &'static wgpu::Adapter {
    &g().adapter
}
pub fn device() -> &'static wgpu::Device {
    &g().device
}
pub fn queue() -> &'static wgpu::Queue {
    &g().queue
}

/// Define `__native.gpu` for a page (call after [`init`]; without a device, pages see
/// `navigator.gpu.requestAdapter()` resolve to null).
pub fn install(c: Ctx, native: Value) {
    args::calibrate(c);
    js::install(c, native);
    rt::on_reset(reset);
}

// ------------------------------------------------------------------------------------- state

#[derive(Default)]
pub(crate) struct Writes {
    pub staging: Vec<u8>,
    /// (buffer id, destination offset, staging offset, size)
    pub ops: Vec<(u32, u64, u32, u32)>,
    /// staging buffers for the batches encoded since the last submit: each batch takes its own,
    /// since every `queue.write_buffer` lands before that submit's commands
    pub pool: Vec<wgpu::Buffer>,
    pub used: usize,
}

/// CPU time spent in the binding (for measurements; see [`stats`]).
#[derive(Default, Clone, Copy, Debug)]
pub struct Stats {
    pub calls: u64,
    pub finish_ns: u64,
    pub submit_ns: u64,
    pub write_ns: u64,
    pub writes: u64,
    pub write_bytes: u64,
    pub passes: u64,
    pub draws: u64,
    pub submits: u64,
}

pub(crate) struct State {
    pub slab: Slab,
    /// canvas contexts by id (index 0 unused)
    pub canvases: Vec<Option<Canvas>>,
    pub window_canvas: u32,
    pub writes: Writes,
    pub stats: Stats,
    /// the encoder a submit replays into (writes queued before it, then its command buffers)
    pub frame: Option<wgpu::CommandEncoder>,
    /// command buffers finished since the last flush, each replayed into its own encoder (an
    /// invalid one fails alone, as in WebGPU), submitted together at the flush
    pub finished: Vec<wgpu::CommandBuffer>,
}

/// Host-side window state (survives page navigations).
pub(crate) struct Window {
    pub target: Option<Target>,
    pub drew: bool,
    pub blitter: Option<Blitter>,
}

// `ManuallyDrop`: wgpu-core touches its own thread-locals when objects drop, which fails inside
// thread-local destructors at process exit. Pages drop their objects on reset; at exit the OS
// reclaims the rest.
thread_local! {
    pub(crate) static STATE: ManuallyDrop<RefCell<State>> = ManuallyDrop::new(RefCell::new(State { slab: Slab::default(), canvases: vec![None], window_canvas: 0, writes: Writes::default(), stats: Stats::default(), frame: None, finished: Vec::new() }));
    pub(crate) static WINDOW: ManuallyDrop<RefCell<Window>> = const { ManuallyDrop::new(RefCell::new(Window { target: None, drew: false, blitter: None })) };
}

/// Completed async operations (token, status 0 ok / 1 failed, buffer id or 0), filled by wgpu
/// callbacks on any thread.
pub(crate) static EVENTS: Mutex<Vec<(f64, u32, u32)>> = Mutex::new(Vec::new());
static NEXT_TOKEN: AtomicU64 = AtomicU64::new(1);

pub(crate) fn token() -> f64 {
    NEXT_TOKEN.fetch_add(1, Ordering::Relaxed) as f64
}

pub(crate) fn push_event(token: f64, status: u32, buffer: u32) {
    EVENTS.lock().unwrap_or_else(|e| e.into_inner()).push((token, status, buffer));
}

fn reset() {
    let dropped = STATE.with(|s| {
        let mut st = s.borrow_mut();
        let canvases = std::mem::replace(&mut st.canvases, vec![None]);
        st.window_canvas = 0;
        st.writes.ops.clear();
        st.writes.staging.clear();
        st.writes.used = 0;
        st.frame = None;
        st.finished.clear();
        let slab = std::mem::take(&mut st.slab);
        (canvases, slab)
    });
    drop(dropped);
    gpu::reset_errors();
    EVENTS.lock().unwrap_or_else(|e| e.into_inner()).clear();
    if let Some(g) = gpu::get() {
        let _ = g.device.poll(wgpu::PollType::Poll);
    }
}

/// Submit queued `writeBuffer`s: returns a command buffer to submit ahead of the page's (or
/// `None` when there was nothing or the writes went straight to the queue).
/// Encode the queued `writeBuffer`s into `enc` as copies from a staging buffer of this submit's
/// pool, so they land between the commands submitted before and after them.
pub(crate) fn encode_writes(st: &mut State, g: &Gpu, enc: &mut wgpu::CommandEncoder) {
    let w = &mut st.writes;
    if w.ops.is_empty() {
        return;
    }
    let t0 = std::time::Instant::now();
    let need = w.staging.len() as u64;
    if w.pool.len() <= w.used {
        w.pool.push(staging_buffer(g, need));
    } else if w.pool[w.used].size() < need {
        w.pool[w.used] = staging_buffer(g, need);
    }
    let staging = &w.pool[w.used];
    w.used += 1;
    g.queue.write_buffer(staging, 0, &w.staging);
    for &(id, dst, src, size) in &w.ops {
        if let Ok(b) = st.slab.buffer(id) {
            enc.copy_buffer_to_buffer(staging, src as u64, &b.buf, dst, size as u64);
        }
    }
    w.ops.clear();
    w.staging.clear();
    st.stats.write_ns += t0.elapsed().as_nanos() as u64;
}

fn staging_buffer(g: &Gpu, need: u64) -> wgpu::Buffer {
    let size = need.next_power_of_two().max(64 * 1024);
    g.device.create_buffer(&wgpu::BufferDescriptor { label: Some("writeBuffer staging"), size, usage: wgpu::BufferUsages::COPY_SRC | wgpu::BufferUsages::COPY_DST, mapped_at_creation: false })
}

/// The frame's encoder, created on first use.
pub(crate) fn frame_encoder<'a>(frame: &'a mut Option<wgpu::CommandEncoder>, g: &Gpu) -> &'a mut wgpu::CommandEncoder {
    frame.get_or_insert_with(|| g.device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("frame") }))
}

/// Put everything the page submitted and wrote so far on the queue with one `submit`. Called at
/// the end of a frame and before anything that must observe or follow that work in queue order
/// (mapping, work-done, destroy, readback, `writeTexture`, image uploads).
pub(crate) fn flush_writes_now(st: &mut State, g: &Gpu) {
    if st.frame.is_none() && st.finished.is_empty() && st.writes.ops.len() <= 2 {
        // nothing deferred: a couple of writes go straight to the queue
        for &(id, dst, src, size) in &st.writes.ops {
            if let Ok(b) = st.slab.buffer(id) {
                g.queue.write_buffer(&b.buf, dst, &st.writes.staging[src as usize..(src + size) as usize]);
            }
        }
        st.writes.ops.clear();
        st.writes.staging.clear();
        st.writes.used = 0;
        return;
    }
    if !st.writes.ops.is_empty() {
        let mut enc = st.frame.take().unwrap_or_else(|| g.device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("frame") }));
        encode_writes(st, g, &mut enc);
        st.frame = Some(enc);
    }
    if let Some(enc) = st.frame.take() {
        st.finished.push(enc.finish());
    }
    if !st.finished.is_empty() {
        let t0 = std::time::Instant::now();
        g.queue.submit(std::mem::take(&mut st.finished));
        st.stats.submits += 1;
        st.stats.submit_ns += t0.elapsed().as_nanos() as u64;
    }
    st.writes.used = 0;
}

/// How submits reach the queue: `batch` (default) replays each submit into its own encoder
/// (an invalid command buffer fails alone, as in WebGPU) and queues the frame's command buffers
/// with one `submit` at the flush; `THREERT_WEBGPU_SUBMIT=each` submits at once, as a browser does.
#[derive(Clone, Copy, PartialEq, Eq)]
pub(crate) enum SubmitMode {
    Batch,
    Each,
}

pub(crate) fn submit_mode() -> SubmitMode {
    static MODE: std::sync::OnceLock<SubmitMode> = std::sync::OnceLock::new();
    *MODE.get_or_init(|| {
        match std::env::var("THREERT_WEBGPU_SUBMIT").or_else(|_| std::env::var("POCKET_WEBGPU_SUBMIT")).as_deref() {
            Ok("each") => SubmitMode::Each,
            _ => SubmitMode::Batch,
        }
    })
}

// ------------------------------------------------------------------------------------- host API

/// The texture the window canvas renders into this frame (call before running the page's frame).
/// `logical_*` is the canvas's CSS size (`clientWidth/Height`, `getBoundingClientRect()`).
pub fn set_window_target(texture: &wgpu::Texture, logical_width: f64, logical_height: f64) {
    WINDOW.with(|w| {
        let mut w = w.borrow_mut();
        w.target = Some(Target { texture: texture.clone(), logical: (logical_width, logical_height) });
        w.drew = false;
    });
}

/// Forget the window target (e.g. the window closed); the window canvas keeps rendering
/// into its own texture.
pub fn clear_window_target() {
    WINDOW.with(|w| w.borrow_mut().target = None);
}

/// The result of a window frame.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct WindowFrame {
    /// the page acquired the window canvas's texture this frame (`getCurrentTexture()`): the
    /// target holds a new frame; otherwise its contents are whatever the host left there
    pub drew: bool,
    /// the page configured `alphaMode: "opaque"`: composite the target ignoring its alpha
    pub opaque: bool,
    /// the frame went through the intermediate texture (format/size mismatch)
    pub blitted: bool,
}

/// End of the page's frame: flush pending writes, copy the window canvas into the target if it
/// rendered into an intermediate, and release this frame's textures. Then composite and present.
pub fn end_window_frame() -> WindowFrame {
    let Some(g) = gpu::get() else { return WindowFrame::default() };
    let mut out = WindowFrame::default();
    STATE.with(|s| {
        let mut st = s.borrow_mut();
        flush_writes_now(&mut st, g);
        let wid = st.window_canvas;
        let State { canvases, slab, .. } = &mut *st;
        for (i, c) in canvases.iter_mut().enumerate() {
            let Some(c) = c else { continue };
            if i as u32 == wid {
                out.drew = c.current != 0;
                out.opaque = c.config.as_ref().is_some_and(|c| !c.premultiplied);
                if out.drew && c.owned.as_ref().is_some_and(|o| o.0 == c.current) {
                    WINDOW.with(|w| {
                        let mut w = w.borrow_mut();
                        let Window { target, blitter, .. } = &mut *w;
                        if let (Some(t), Some((_, src))) = (target.as_ref(), c.owned.as_ref()) {
                            blitter.get_or_insert_with(|| Blitter::new(&g.device)).blit(&g.device, &g.queue, src, &t.texture, out.opaque);
                            out.blitted = true;
                        }
                    });
                }
            }
            c.release_current(slab);
        }
    });
    WINDOW.with(|w| {
        let mut w = w.borrow_mut();
        w.drew = out.drew;
        w.target = None;
    });
    out
}

/// Physical size the page set on the window canvas (`canvas.width/height`), if it has one.
pub fn window_canvas_size() -> Option<(u32, u32)> {
    STATE.with(|s| {
        let st = s.borrow();
        st.canvases.get(st.window_canvas as usize)?.as_ref().map(|c| (c.width, c.height))
    })
}

/// Process completed GPU work (map callbacks, work-done); pages also poll on their own while
/// they wait for something.
pub fn poll() {
    if let Some(g) = gpu::get() {
        let _ = g.device.poll(wgpu::PollType::Poll);
    }
}

/// Block until the GPU finished all submitted work (headless pacing, measurements).
pub fn wait_idle() {
    if let Some(g) = gpu::get() {
        let _ = g.device.poll(wgpu::PollType::Wait);
    }
}

/// Counters since the page started (or since the last [`take_stats`]).
pub fn stats() -> Stats {
    STATE.with(|s| s.borrow().stats)
}
pub fn take_stats() -> Stats {
    STATE.with(|s| std::mem::take(&mut s.borrow_mut().stats))
}

/// An owned render target for headless runs: pass `texture()` to [`set_window_target`] each
/// frame and read the result back with [`Offscreen::read_rgba`].
pub struct Offscreen {
    texture: wgpu::Texture,
}

impl Offscreen {
    /// `format`: normally `Bgra8Unorm` (what a Metal surface uses).
    pub fn new(width: u32, height: u32, format: wgpu::TextureFormat) -> Self {
        let texture = device().create_texture(&wgpu::TextureDescriptor {
            label: Some("offscreen window"),
            size: wgpu::Extent3d { width, height, depth_or_array_layers: 1 },
            mip_level_count: 1,
            sample_count: 1,
            dimension: wgpu::TextureDimension::D2,
            format,
            usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC | wgpu::TextureUsages::COPY_DST | wgpu::TextureUsages::TEXTURE_BINDING,
            view_formats: &[],
        });
        Offscreen { texture }
    }
    pub fn texture(&self) -> &wgpu::Texture {
        &self.texture
    }
    /// RGBA8, rows top-down; alpha forced to 255 when `opaque`.
    pub fn read_rgba(&self, opaque: bool) -> Result<Vec<u8>, String> {
        if let Some(g) = gpu::get() {
            STATE.with(|s| flush_writes_now(&mut s.borrow_mut(), g));
        }
        image::read_rgba(device(), queue(), &self.texture, opaque, !opaque).map(|(_, _, px)| px)
    }
}

/// Sleep-free wait for pending callbacks (tests).
pub fn poll_for(d: Duration) {
    let t0 = std::time::Instant::now();
    while t0.elapsed() < d {
        poll();
        if !EVENTS.lock().unwrap_or_else(|e| e.into_inner()).is_empty() {
            return;
        }
        std::thread::yield_now();
    }
}