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.

9.0 KB
Raw Blame
//! Minimal native ThreeRT `--renderer webgpu` sample host:
//! JavaScriptCore realm + shared runtime services + Canvas 2D + native WebGPU (`navigator.gpu`),
//! with zero path-tracer crates linked.
//!
//! Usage:
//!   threert-webgpu-sample --runtime <runtime.js> --script <scene.js>
//!                         [--size 800x600@2] [--timeout 30] [--fps 60]
//!                         [--format bgra8unorm|rgba8unorm] [--shot <out.png>]
use std::cell::{Cell, RefCell};
use std::time::{Duration, Instant};

use jsc::{Ctx, Value};
use threert_webgpu as webgpu;

thread_local! {
    static WAKE_AT: Cell<f64> = const { Cell::new(f64::INFINITY) };
    static WANT_FRAME: Cell<bool> = const { Cell::new(false) };
    static EXIT: Cell<Option<i32>> = const { Cell::new(None) };
    static SHOT: RefCell<Option<String>> = const { RefCell::new(None) };
    static RNG: Cell<u64> = const { Cell::new(0x9e37_79b9_7f4a_7c15) };
}

struct Opts {
    runtime: String,
    script: String,
    width: u32,
    height: u32,
    dpr: f64,
    timeout: f64,
    fps: f64,
    format: wgpu::TextureFormat,
    shot: Option<String>,
}

fn opts() -> Opts {
    let args: Vec<String> = std::env::args().collect();
    let get = |k: &str| args.iter().position(|x| x == k).and_then(|i| args.get(i + 1)).cloned();
    let size = get("--size").unwrap_or_else(|| "800x600@2".into());
    let (wh, dpr) = size.split_once('@').unwrap_or((&size, "1"));
    let (w, h) = wh.split_once('x').unwrap_or(("800", "600"));
    Opts {
        runtime: get("--runtime").unwrap_or_else(|| "out/webgpu/runtime.js".into()),
        script: get("--script").unwrap_or_else(|| "out/webgpu/sample.js".into()),
        width: w.parse().unwrap_or(800),
        height: h.parse().unwrap_or(600),
        dpr: dpr.parse().unwrap_or(1.0),
        timeout: get("--timeout").and_then(|s| s.parse().ok()).unwrap_or(30.0),
        fps: get("--fps").and_then(|s| s.parse().ok()).unwrap_or(60.0),
        format: match get("--format").as_deref() {
            Some("rgba8unorm") => wgpu::TextureFormat::Rgba8Unorm,
            _ => wgpu::TextureFormat::Bgra8Unorm,
        },
        shot: get("--shot"),
    }
}

fn install_sys(c: Ctx, sys: Value) {
    let def = |name: &str, f: Value| sys.set(c, name, f);
    def("now", c.function(|c, _, _| Ok(c.num(rt::page_now()))));
    def("wakeAt", c.function(|c, _, a| {
        let t = a.first().map(|v| v.to_num(c)).unwrap_or(f64::INFINITY);
        WAKE_AT.with(|w| w.set(if t.is_nan() { f64::INFINITY } else { t }));
        Ok(c.undefined())
    }));
    def("requestFrame", c.function(|c, _, _| {
        WANT_FRAME.with(|w| w.set(true));
        Ok(c.undefined())
    }));
    def("log", c.function(|c, _, a| {
        let level = a.first().map(|v| v.to_string(c)).unwrap_or_default();
        let msg = a.get(1).map(|v| v.to_string(c)).unwrap_or_default();
        eprintln!("[{level}] {msg}");
        Ok(c.undefined())
    }));
    def("exit", c.function(|c, _, a| {
        EXIT.with(|e| e.set(Some(a.first().map(|v| v.to_i32(c)).unwrap_or(0))));
        Ok(c.undefined())
    }));
    def("shot", c.function(|c, _, a| {
        let path = a.first().map(|v| v.to_string(c)).unwrap_or_else(|| "out/webgpu/sample.png".into());
        SHOT.with(|s| *s.borrow_mut() = Some(path));
        Ok(c.undefined())
    }));
    def("randomBytes", c.function(|c, _, a| {
        let v = a.first().copied().unwrap_or(c.undefined());
        if let Some(b) = v.bytes(c) {
            RNG.with(|r| {
                let mut x = r.get();
                for byte in b.iter_mut() {
                    x ^= x << 13;
                    x ^= x >> 7;
                    x ^= x << 17;
                    *byte = x as u8;
                }
                r.set(x);
            });
        }
        Ok(v)
    }));
    def("locale", c.function(|c, _, _| Ok(c.str("en-US"))));
    def("storageGet", c.function(|c, _, _| Ok(c.null())));
    def("storageSet", c.function(|c, _, _| Ok(c.undefined())));
    def("resource", c.function(|c, _, _| Ok(c.null())));
    for name in ["navigate", "shell", "closeWindow"] {
        def(name, c.function(|c, _, _| Ok(c.undefined())));
    }
}

fn call_rt(c: Ctx, name: &str, now: f64) {
    let rtv = c.global().get(c, "__rt");
    if !rtv.is_object(c) {
        return;
    }
    let f = rtv.get(c, name);
    if f.is_function(c) {
        if let Err(e) = c.call(f, Some(rtv), &[c.num(now)]) {
            eprintln!("[js] __rt.{name}: {e}");
        }
    }
}

fn write_shot(off: &webgpu::Offscreen, path: &str, opaque: bool, w: u32, h: u32) -> bool {
    match off.read_rgba(opaque) {
        Ok(px) => {
            let png = canvas2d::encode_png(w, h, &px);
            if let Some(dir) = std::path::Path::new(path).parent() {
                if !dir.as_os_str().is_empty() {
                    let _ = std::fs::create_dir_all(dir);
                }
            }
            match std::fs::write(path, png) {
                Ok(()) => {
                    eprintln!("[threert-webgpu-sample] wrote {path} ({w}x{h})");
                    true
                }
                Err(e) => {
                    eprintln!("[threert-webgpu-sample] write {path}: {e}");
                    false
                }
            }
        }
        Err(e) => {
            eprintln!("[threert-webgpu-sample] readback failed: {e}");
            false
        }
    }
}

fn main() {
    let o = opts();
    let (pw, ph) = ((o.width as f64 * o.dpr).round() as u32, (o.height as f64 * o.dpr).round() as u32);
    if let Err(e) = webgpu::init(&webgpu::GpuOptions::default()) {
        eprintln!("[threert-webgpu-sample] GPU unavailable: {e}");
        std::process::exit(2);
    }
    let runtime = std::fs::read_to_string(&o.runtime).unwrap_or_else(|e| panic!("read {}: {e}", o.runtime));
    let script = std::fs::read_to_string(&o.script).unwrap_or_else(|e| panic!("read {}: {e}", o.script));

    let cx = jsc::Context::new("threert-webgpu-sample");
    let c = cx.ctx();
    rt::begin_page(c);
    let native = c.object();
    c.global().set(c, "__native", native);
    let sys = c.object();
    native.set(c, "sys", sys);
    install_sys(c, sys);
    canvas2d::install(c, native);
    webgpu::install(c, native);
    c.global().set(
        c,
        "__boot",
        c.json(&format!(
            r#"{{"url":"http://localhost/","width":{},"height":{},"dpr":{},"lang":"en-US","title":"ThreeRT WebGPU Sample"}}"#,
            o.width, o.height, o.dpr
        )),
    );

    let off = webgpu::Offscreen::new(pw, ph, o.format);
    let (lw, lh) = (o.width as f64, o.height as f64);
    let mut last_opaque = true;
    let mut shot_written = false;

    let mut turn = |f: &mut dyn FnMut()| -> webgpu::WindowFrame {
        webgpu::set_window_target(off.texture(), lw, lh);
        f();
        let fr = webgpu::end_window_frame();
        if fr.drew {
            last_opaque = fr.opaque;
        }
        if let Some(path) = SHOT.with(|s| s.borrow_mut().take()) {
            shot_written = write_shot(&off, &path, last_opaque, pw, ph);
        }
        fr
    };

    let mut eval_failed = false;
    turn(&mut || {
        if let Err(e) = c.eval(&runtime, &o.runtime) {
            eprintln!("[js] runtime: {e}");
            eval_failed = true;
        }
        if !eval_failed {
            if let Err(e) = c.eval(&script, &o.script) {
                eprintln!("[js] script: {e}");
                eval_failed = true;
            }
        }
    });
    if eval_failed {
        rt::reset_page();
        drop(cx);
        std::process::exit(1);
    }

    let start = Instant::now();
    let frame_ms = 1000.0 / o.fps.max(1.0);
    let mut next_frame = rt::page_now();
    let mut frames = 0u32;

    let code = loop {
        if let Some(code) = EXIT.with(|e| e.get()) {
            break code;
        }
        if start.elapsed().as_secs_f64() > o.timeout {
            eprintln!("[threert-webgpu-sample] timeout after {}s", o.timeout);
            break 3;
        }
        rt::drain();
        let now = rt::page_now();
        if WAKE_AT.with(|w| w.get()) <= now + 0.5 {
            WAKE_AT.with(|w| w.set(f64::INFINITY));
            turn(&mut || call_rt(c, "timers", now));
        }
        if WANT_FRAME.with(|w| w.get()) && now >= next_frame {
            WANT_FRAME.with(|w| w.set(false));
            next_frame = (next_frame + frame_ms).max(now);
            turn(&mut || call_rt(c, "frame", now));
            frames += 1;
            webgpu::wait_idle();
            continue;
        }
        webgpu::poll();
        let wake = WAKE_AT.with(|w| w.get()).min(if WANT_FRAME.with(|w| w.get()) { next_frame } else { f64::INFINITY });
        let sleep = (wake - rt::page_now()).clamp(0.0, 2.0);
        if sleep > 0.05 {
            std::thread::sleep(Duration::from_secs_f64(sleep / 1000.0));
        }
    };

    if let Some(out) = &o.shot {
        if !shot_written {
            write_shot(&off, out, last_opaque, pw, ph);
        }
    }
    eprintln!(
        "[threert-webgpu-sample] frames={} elapsed={:.1}ms",
        frames,
        start.elapsed().as_secs_f64() * 1000.0
    );
    rt::reset_page();
    drop(cx);
    std::process::exit(code);
}