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.

4.5 KB
Raw Blame
//! Pure-Rust Canvas 2D, image codec, and text layout backend (`tiny-skia` + `cosmic-text` + `image`).
use std::cell::{Cell, RefCell};
use std::collections::HashMap;
use std::rc::Rc;

use jsc::{Ctx, Value};

pub mod canvas;
pub mod codec;
pub mod fonts;
mod js;
pub mod textblock;

use crate::Bitmap;
use canvas::{Canvas, Gradient, Path, Pattern};

pub(crate) struct Surface {
    pub width: u32,
    pub height: u32,
    pub canvas: Option<Box<Canvas>>,
    pub version: u64,
    /// premultiplied RGBA8, top-down, stride = width * 4
    pub data: Vec<u8>,
}

thread_local! {
    static NEXT_ID: Cell<u32> = const { Cell::new(1) };
    pub(crate) static SURFACES: RefCell<HashMap<u32, Surface>> = RefCell::new(HashMap::new());
    pub(crate) static PATHS: RefCell<HashMap<u32, Path>> = RefCell::new(HashMap::new());
    pub(crate) static GRADIENTS: RefCell<HashMap<u32, Rc<RefCell<Gradient>>>> = RefCell::new(HashMap::new());
    pub(crate) static PATTERNS: RefCell<HashMap<u32, Rc<Pattern>>> = RefCell::new(HashMap::new());
}

const MAX_SIDE: u32 = 32767;
const MAX_AREA: u64 = 268_435_456;

pub(crate) fn next_id() -> u32 {
    NEXT_ID.with(|n| {
        let v = n.get();
        n.set(if v == u32::MAX { 1 } else { v + 1 });
        v
    })
}

fn alloc_pixels(w: u32, h: u32) -> (u32, u32, Vec<u8>) {
    if w == 0 || h == 0 || w > MAX_SIDE || h > MAX_SIDE || w as u64 * h as u64 > MAX_AREA {
        return (w, h, Vec::new());
    }
    let n = w as usize * h as usize * 4;
    let mut v = Vec::new();
    if v.try_reserve_exact(n).is_err() {
        return (w, h, Vec::new());
    }
    v.resize(n, 0);
    (w, h, v)
}

pub(crate) fn create_canvas(w: u32, h: u32) -> u32 {
    let id = next_id();
    let (w, h, data) = alloc_pixels(w, h);
    let canvas = Canvas::new(if data.is_empty() { 0 } else { w }, if data.is_empty() { 0 } else { h });
    SURFACES.with(|s| s.borrow_mut().insert(id, Surface { width: w, height: h, canvas: Some(Box::new(canvas)), version: 1, data }));
    id
}

pub(crate) fn resize_canvas(id: u32, w: u32, h: u32) -> bool {
    SURFACES.with(|s| {
        let mut s = s.borrow_mut();
        let Some(surf) = s.get_mut(&id) else { return false };
        if surf.canvas.is_none() {
            return false;
        }
        let (w, h, data) = alloc_pixels(w, h);
        surf.canvas = Some(Box::new(Canvas::new(if data.is_empty() { 0 } else { w }, if data.is_empty() { 0 } else { h })));
        surf.data = data;
        surf.width = w;
        surf.height = h;
        surf.version += 1;
        true
    })
}

pub(crate) fn insert_image(width: u32, height: u32, data: Vec<u8>) -> u32 {
    let id = next_id();
    SURFACES.with(|s| s.borrow_mut().insert(id, Surface { width, height, canvas: None, version: 1, data }));
    id
}

pub(crate) fn release(id: u32) {
    SURFACES.with(|s| s.borrow_mut().remove(&id));
    PATHS.with(|p| p.borrow_mut().remove(&id));
    GRADIENTS.with(|g| g.borrow_mut().remove(&id));
    PATTERNS.with(|p| p.borrow_mut().remove(&id));
}

pub(crate) fn reset() {
    SURFACES.with(|s| s.borrow_mut().clear());
    PATHS.with(|p| p.borrow_mut().clear());
    GRADIENTS.with(|g| g.borrow_mut().clear());
    PATTERNS.with(|p| p.borrow_mut().clear());
}

pub(crate) fn with_canvas<R>(id: u32, f: impl FnOnce(&mut Canvas, &mut Vec<u8>) -> R) -> Option<R> {
    SURFACES.with(|s| {
        let mut s = s.borrow_mut();
        let surf = s.get_mut(&id)?;
        let canvas = surf.canvas.as_mut()?;
        let r = f(canvas, &mut surf.data);
        if canvas.dirty {
            canvas.dirty = false;
            surf.version += 1;
        }
        Some(r)
    })
}

pub(crate) fn surface_size(id: u32) -> Option<(u32, u32)> {
    SURFACES.with(|s| s.borrow().get(&id).map(|s| (s.width, s.height)))
}

pub(crate) fn snapshot(id: u32) -> Option<(Vec<u8>, u32, u32)> {
    SURFACES.with(|s| {
        let s = s.borrow();
        let surf = s.get(&id)?;
        if surf.data.is_empty() {
            return None;
        }
        Some((surf.data.clone(), surf.width, surf.height))
    })
}

pub fn install(c: Ctx, native: Value) {
    rt::on_reset(reset);
    js::install(c, native);
}

pub fn with_bitmap<R>(id: u32, f: impl FnOnce(&Bitmap) -> R) -> Option<R> {
    SURFACES.with(|s| {
        let s = s.borrow();
        let surf = s.get(&id)?;
        if surf.data.is_empty() {
            return None;
        }
        Some(f(&Bitmap { width: surf.width, height: surf.height, stride: surf.width as usize * 4, data: &surf.data, version: surf.version }))
    })
}

pub fn bitmap_version(id: u32) -> Option<u64> {
    SURFACES.with(|s| s.borrow().get(&id).map(|s| s.version))
}