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.

14.8 KB
Raw Blame
//! ThreeRT PocketJS UI host: one `pocket_runtime::Runtime` whose guest is JavaScriptCore
//! (`pocket-guest-jsc`), whose primary display is the window's drawable (drawn by
//! `pocket-wgpu-render` on the device the game's WebGPU shares), and whose text is the native
//! text path (`text.layout.native`): CoreText measures, wraps and paints the font slots.
//!
//! A frame, driven by the app:
//! 1. [`UiHost::input`] — publish this frame's pointer, scroll and text events;
//! 2. [`UiHost::advance`] — one guest turn: the bundle's `frame` (game update, the game's WebGPU
//!    render into the drawable, UI mutations), then the core's tick;
//! 3. [`UiHost::present`] — the UI's DrawList drawn into the same drawable over the game's
//!    picture; the app then presents the drawable.

mod display;
mod text;

use std::cell::{Cell, RefCell, RefMut};
use std::rc::Rc;

use pocket_drivers::target::RendererCell;
use pocket_drivers::{InputClasses, InputFrameBuilder, InputSource, PixelFormat, Renderer};
use pocket_guest_jsc::jsc::Ctx;
use pocket_guest_jsc::{JscGuest, Realm};
use pocket_package::source::MemorySource;
use pocket_runtime::generated_ops::BINDING_GENERATION;
use pocket_runtime::{Cow, Profile, Runtime, RuntimeConfig};
use pocket_wgpu_render::WgpuRenderer;

pub use pocket_guest_jsc::jsc;
pub use text::{SlotFont, SlotFonts};

use display::{DisplayState, SurfaceDisplay};

struct StderrLog;
impl log::Log for StderrLog {
    fn enabled(&self, m: &log::Metadata<'_>) -> bool {
        m.level() <= log::max_level()
    }
    fn log(&self, r: &log::Record<'_>) {
        if self.enabled(r.metadata()) {
            eprintln!("[{}] {}", r.level().as_str().to_lowercase(), r.args());
        }
    }
    fn flush(&self) {}
}

/// Route the runtime's and guest's `log` records (warnings and errors; all with `THREERT_TRACE`
/// or `POCKET_TRACE`) to stderr.
pub fn init_logging() {
    static LOG: StderrLog = StderrLog;
    if log::set_logger(&LOG).is_ok() {
        // the level decides at each call site whether a record is built at all: wgpu traces its hot paths
        let verbose = std::env::var_os("THREERT_TRACE").is_some() || std::env::var_os("POCKET_TRACE").is_some();
        log::set_max_level(if verbose { log::LevelFilter::Trace } else { log::LevelFilter::Warn });
    }
}

/// The capabilities this host gives a PocketJS UI bundle.
pub const CAPABILITIES: &[&str] = &[
    "display.viewport.live",
    "host.clipboard",
    "input.buttons",
    "input.cursor",
    "input.ime",
    "input.pointer",
    "input.scroll",
    "input.text",
    "text.layout.native",
];

pub struct HostConfig {
    /// the host id the bundle sees as `ui.__host`
    pub host_id: String,
    /// window size in logical px
    pub logical: [u32; 2],
    /// device px per logical px
    pub scale: f32,
    /// the drawable's format
    pub format: wgpu::TextureFormat,
    /// font slot → face; index = slot number
    pub slots: Vec<Option<SlotFont>>,
}

/// The facts the app published for the next guest turn.
struct Input(Rc<RefCell<InputFrameBuilder>>);

impl InputSource for Input {
    fn classes(&self) -> InputClasses {
        InputClasses::BUTTONS | InputClasses::AXIS_ABSOLUTE | InputClasses::POINTER | InputClasses::CONTACT | InputClasses::TEXT
    }
    fn poll(&mut self, output: &mut InputFrameBuilder) {
        let mut input = self.0.borrow_mut();
        output.buttons |= input.buttons;
        if input.pointer.is_some() {
            output.pointer = input.pointer;
        }
        output.text.append(&mut input.text);
        output.scroll[0] += input.scroll[0];
        output.scroll[1] += input.scroll[1];
        input.scroll = [0.0; 2];
    }
}

pub struct UiHost {
    runtime: Runtime,
    realm: Realm,
    display: Rc<RefCell<DisplayState>>,
    input: Rc<RefCell<InputFrameBuilder>>,
    guest: Option<JscGuest>,
    config: HostConfig,
    fonts: Rc<SlotFonts>,
    /// a presentation waits for completion until the next frame begins
    presenting: bool,
    /// what the last presented frame drew: DrawList words and resource revision
    shown: Option<(u64, u64)>,
    /// cached picture hash from `changed()` for the current frame, consumed by `present()`
    pending: Cell<Option<(u64, u64)>>,
}

fn err<E: std::fmt::Debug>(what: &'static str) -> impl FnOnce(E) -> String {
    move |e| format!("{what}: {e:?}")
}

fn density(scale: f32) -> u32 {
    (scale.round() as u32).clamp(1, 4)
}

impl UiHost {
    /// A runtime drawing with `device`/`queue`. `setup` runs on every new realm after `ui` is
    /// mounted and before the bundle evaluates: the host's own namespaces (fetch, timers,
    /// `navigator.gpu`, storage, …).
    pub fn new(
        device: &wgpu::Device,
        queue: &wgpu::Queue,
        config: HostConfig,
        setup: impl FnMut(Ctx) -> Result<(), String> + 'static,
    ) -> Result<UiHost, String> {
        let logical = config.logical;
        let density = density(config.scale);
        let profile = Profile {
            id: Cow::Owned(config.host_id.clone()),
            cadences: Cow::Owned(vec![60]),
            viewport: [logical[0] * density, logical[1] * density],
            logical_viewports: Cow::Owned(vec![logical]),
            dynamic_viewport: None,
            presentations: Cow::Borrowed(&[Cow::Borrowed("native")]),
            auxiliary: None,
            auxiliary_logical: Cow::Borrowed(&[]),
            density,
            animation: Cow::Borrowed(""),
            capabilities: Cow::Owned(CAPABILITIES.iter().map(|c| Cow::Borrowed(*c)).collect()),
            required_inputs: InputClasses::NONE,
        };
        let mut runtime = Runtime::new(RuntimeConfig {
            profile_hash: [0; 32],
            host_abi: BINDING_GENERATION,
            // JavaScriptCore has no heap limit to apply; the runtime requires a nonzero figure
            heap_limit: 1 << 30,
            frame_buffer_budget: 256 << 20,
            profile,
        })
        .map_err(err("runtime"))?;
        runtime.allow_embedded_viewport_changes().map_err(err("viewport changes"))?;
        let input = Rc::new(RefCell::new(InputFrameBuilder::new()));
        runtime.add_input_source(Box::new(Input(input.clone()))).map_err(err("input"))?;

        // native text: the core measures and wraps through the slots, the renderer paints them
        let fonts = Rc::new(SlotFonts::new(&config.slots));
        {
            let ops = runtime.op_context();
            let mut core = ops.core_mut().map_err(err("core"))?;
            let measure = fonts.clone();
            core.ui.set_text_measure(Some(Box::new(move |text, slot, tracking, line_height| measure.measure(text, slot, tracking, line_height))));
            let wrap = fonts.clone();
            core.ui.set_text_wrap(Some(Box::new(move |text, slot, max_width| wrap.wrap(text, slot, max_width))));
        }
        let mut renderer = WgpuRenderer::new(device, queue, config.format).map_err(err("renderer"))?;
        renderer.set_text_painter(Some(Box::new(text::Painter(fonts.clone()))));
        let pixel_format = renderer.descriptor().formats()[0];
        let cell = RendererCell::new(renderer);
        let physical = [(logical[0] as f32 * config.scale).round() as u32, (logical[1] as f32 * config.scale).round() as u32];
        let display = Rc::new(RefCell::new(DisplayState::new(&cell, (physical[0], physical[1]), config.scale, pixel_format)));
        let registration = cell.registration().map_err(err("registration"))?;
        let renderer_id = runtime.add_renderer(registration).map_err(err("add renderer"))?;
        runtime.add_display(SurfaceDisplay(display.clone()), renderer_id).map_err(err("add display"))?;
        // the cell lives on in the registration and the display's target slot
        drop(cell);

        let guest = JscGuest::new(&config.host_id).with_setup(setup);
        let realm = guest.realm();
        Ok(UiHost { runtime, realm, display, input, guest: Some(guest), config, fonts, presenting: false, shown: None, pending: Cell::new(None) })
    }

    /// Admit `js` (a PocketJS bundle) with its `pak` and evaluate it.
    pub fn boot(&mut self, label: &str, js: &str, pak: &[u8]) -> Result<(), String> {
        let features: serde_json::Map<String, serde_json::Value> = CAPABILITIES.iter().map(|c| (c.to_string(), serde_json::Value::Bool(true))).collect();
        let plan = serde_json::json!({
            "target": { "id": self.config.host_id, "hostAbi": BINDING_GENERATION },
            "profile": { "id": self.config.host_id, "tickHz": 60 },
            "viewport": { "logical": self.config.logical, "presentation": "native", "rasterDensity": density(self.config.scale) },
            "features": features,
        });
        let plan = serde_json::to_vec(&plan).map_err(err("plan"))?;
        let identity = pocket_package::embedded::identity(label, label, label).map_err(err("identity"))?;
        let bytes = pocket_package::embedded::encode(pocket_package::embedded::EmbeddedPackage {
            host_abi: BINDING_GENERATION,
            profile_hash: [0; 32],
            identity: &identity,
            plan: &plan,
            code: js.as_bytes(),
            pak,
        })
        .map_err(err("package"))?;
        self.runtime.set_package_source(Box::new(MemorySource(bytes))).map_err(err("package source"))?;
        let guest = self.guest.take().ok_or("already booted")?;
        self.runtime.set_guest(Box::new(guest)).map_err(err("guest"))?;
        self.runtime.boot_deferred().map_err(err("boot"))?;
        self.runtime.skip_presentation().map_err(err("skip presentation"))?;
        Ok(())
    }

    /// The JavaScript realm (for the host's callbacks into it).
    pub fn realm(&self) -> &Realm {
        &self.realm
    }

    /// The facts the next guest turn sees: pointer (logical px), scroll, text events.
    pub fn input(&self) -> RefMut<'_, InputFrameBuilder> {
        self.input.borrow_mut()
    }

    /// Finish the previous frame's presentation (normally long done on the GPU).
    fn complete(&mut self) -> Result<(), String> {
        if self.presenting {
            self.presenting = false;
            self.runtime.complete_presentation().map_err(err("complete presentation"))?;
        }
        Ok(())
    }

    /// One guest turn.
    pub fn advance(&mut self) -> Result<(), String> {
        self.complete()?;
        self.pending.set(None);
        self.runtime.skip_presentation().map_err(err("skip"))?;
        self.runtime.advance().map_err(err("advance"))
    }

    /// Draw the UI into `view` (`size` device px) over what it holds, or over `clear`.
    pub fn present(&mut self, view: &wgpu::TextureView, size: (u32, u32), clear: Option<wgpu::Color>) -> Result<(), String> {
        if self.display.borrow().size != size && size.0 > 0 && size.1 > 0 {
            self.resize_physical([size.0, size.1], self.config.scale)?;
        }
        self.display.borrow_mut().set_frame(view, size, self.config.scale, clear)?;
        self.runtime.present().map_err(err("present"))?;
        self.presenting = true;
        self.shown = self.pending.take().or_else(|| self.picture());
        Ok(())
    }

    /// The interface's picture after the last turn: a hash of its DrawList and the resource
    /// revision (textures, fonts, styles).
    fn picture(&self) -> Option<(u64, u64)> {
        let ops = self.runtime.op_context();
        let mut core = ops.core_mut().ok()?;
        let words = &core.ui.draw().words;
        // FNV-1a over the words
        let mut hash = 0xcbf2_9ce4_8422_2325u64;
        for w in words {
            hash = (hash ^ *w as u64).wrapping_mul(0x0000_0100_0000_01b3);
        }
        Some((hash, core.ui.raster_revision()))
    }

    /// Whether the interface would draw something other than what the window shows.
    pub fn changed(&self) -> bool {
        let current = self.pending.get().or_else(|| {
            let pic = self.picture();
            self.pending.set(pic);
            pic
        });
        self.shown.is_none() || current != self.shown
    }

    /// The window lost its pictures (resize, new drawable): the next frame presents.
    pub fn invalidate(&mut self) {
        self.shown = None;
        self.pending.set(None);
    }

    /// The window changed size or scale (logical px). Supports both integer and fractional HiDPI scales.
    pub fn resize(&mut self, logical: [u32; 2], scale: f32) -> Result<(), String> {
        let scale = if scale.is_finite() && scale > 0.0 { scale } else { 1.0 };
        let logical = [logical[0].max(1), logical[1].max(1)];
        let physical = [
            (logical[0] as f32 * scale).round().max(1.0) as u32,
            (logical[1] as f32 * scale).round().max(1.0) as u32,
        ];
        self.resize_gpu([logical[0] as f32, logical[1] as f32], physical, scale)
    }

    /// The window changed physical surface size or scale (exact swapchain device px).
    /// Preferred on Wayland / fractional HiDPI where physical dimensions may not equal `round(logical) * scale`.
    pub fn resize_physical(&mut self, physical: [u32; 2], scale: f32) -> Result<(), String> {
        let scale = if scale.is_finite() && scale > 0.0 { scale } else { 1.0 };
        let physical = [physical[0].max(1), physical[1].max(1)];
        let logical = [
            (physical[0] as f32 / scale).max(1.0),
            (physical[1] as f32 / scale).max(1.0),
        ];
        self.resize_gpu(logical, physical, scale)
    }

    fn resize_gpu(&mut self, logical: [f32; 2], physical: [u32; 2], scale: f32) -> Result<(), String> {
        self.complete()?;
        let prev = {
            let mut d = self.display.borrow_mut();
            let prev = (d.size, d.scale);
            d.size = (physical[0], physical[1]);
            d.scale = scale;
            prev
        };
        if let Err(e) = self.runtime.resize_embedded_gpu(logical, physical) {
            let mut d = self.display.borrow_mut();
            d.size = prev.0;
            d.scale = prev.1;
            return Err(format!("resize: {e:?}"));
        }
        self.config.logical = [logical[0].round().max(1.0) as u32, logical[1].round().max(1.0) as u32];
        self.config.scale = scale;
        self.shown = None;
        self.pending.set(None);
        Ok(())
    }

    /// The CSS cursor the interface's hovered node asks for (`cursor-*` classes).
    pub fn cursor(&self) -> &'static str {
        let ops = self.runtime.op_context();
        let Ok(core) = ops.core() else { return "default" };
        match core.ui.hover_cursor() {
            2 => "pointer",
            3 => "text",
            4 => "not-allowed",
            _ => "default",
        }
    }

    pub fn logical(&self) -> [u32; 2] {
        self.config.logical
    }
    pub fn scale(&self) -> f32 {
        self.config.scale
    }
    pub fn fonts(&self) -> &Rc<SlotFonts> {
        &self.fonts
    }
    pub fn pixel_format(&self) -> PixelFormat {
        self.display.borrow().pixel_format
    }
}

impl Drop for UiHost {
    fn drop(&mut self) {
        let _ = self.complete();
        let _ = self.runtime.shutdown();
    }
}