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.

6.0 KB
Raw Blame
//! Per-page objects: bitmaps (2D canvases and decoded images share one id space), Path2D
//! objects, gradients and patterns. Main thread only; cleared on page reset.
use std::cell::{Cell, RefCell};
use std::collections::HashMap;
use std::rc::Rc;

use objc2_core_foundation::{CFData, CFRetained};
use objc2_core_graphics::{CGBitmapInfo, CGColorRenderingIntent, CGDataProvider, CGImage, CGImageAlphaInfo};

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

pub(crate) struct Surface {
    pub width: u32,
    pub height: u32,
    /// Some for 2D canvases (declared before `data`: the CG context draws into it)
    pub canvas: Option<Box<Canvas>>,
    /// immutable images: CGImage made on first use
    image: Option<CFRetained<CGImage>>,
    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());
}

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
    })
}

/// Largest canvas Chrome allows (area and side).
const MAX_SIDE: u32 = 32767;
const MAX_AREA: u64 = 268_435_456;

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, mut data) = alloc_pixels(w, h);
    let ptr = if data.is_empty() { std::ptr::null_mut() } else { data.as_mut_ptr() };
    let canvas = Canvas::new(ptr, 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)), image: None, version: 1, data }));
    id
}

/// Reallocate a canvas (pixels cleared, state reset — like setting canvas.width).
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;
        }
        surf.canvas = None;
        let (w, h, mut data) = alloc_pixels(w, h);
        let ptr = if data.is_empty() { std::ptr::null_mut() } else { data.as_mut_ptr() };
        surf.canvas = Some(Box::new(Canvas::new(ptr, 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, image: None, version: 1, data }));
    id
}

pub(crate) fn release(id: u32) {
    // Drop outside the borrow (dropping CG objects never re-enters, but keep it tidy).
    let a = SURFACES.with(|s| s.borrow_mut().remove(&id));
    let b = PATHS.with(|s| s.borrow_mut().remove(&id));
    let c = GRADIENTS.with(|s| s.borrow_mut().remove(&id));
    let d = PATTERNS.with(|s| s.borrow_mut().remove(&id));
    drop((a, b, c, d));
}

pub(crate) fn reset() {
    let a = SURFACES.with(|s| std::mem::take(&mut *s.borrow_mut()));
    let b = PATHS.with(|s| std::mem::take(&mut *s.borrow_mut()));
    let c = GRADIENTS.with(|s| std::mem::take(&mut *s.borrow_mut()));
    let d = PATTERNS.with(|s| std::mem::take(&mut *s.borrow_mut()));
    drop((a, b, c, d));
}

/// Run `f` on a canvas; bumps the bitmap version when pixels may have changed.
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)))
}

/// An immutable CGImage of a bitmap's current pixels (canvases are copied: the image must not
/// change when the canvas is drawn to later).
pub(crate) fn snapshot(id: u32) -> Option<(CFRetained<CGImage>, u32, u32)> {
    SURFACES.with(|s| {
        let mut s = s.borrow_mut();
        let surf = s.get_mut(&id)?;
        if surf.data.is_empty() {
            return None;
        }
        if surf.canvas.is_none() {
            if surf.image.is_none() {
                surf.image = image_from_premul(surf.width, surf.height, &surf.data);
            }
            return surf.image.clone().map(|i| (i, surf.width, surf.height));
        }
        image_from_premul(surf.width, surf.height, &surf.data).map(|i| (i, surf.width, surf.height))
    })
}

pub(crate) fn image_from_premul(w: u32, h: u32, data: &[u8]) -> Option<CFRetained<CGImage>> {
    let cf = CFData::from_bytes(data);
    let provider = CGDataProvider::with_cf_data(Some(&cf))?;
    unsafe {
        CGImage::new(
            w as usize,
            h as usize,
            8,
            32,
            w as usize * 4,
            Some(&srgb()),
            CGBitmapInfo(CGImageAlphaInfo::PremultipliedLast.0),
            Some(&provider),
            std::ptr::null(),
            true,
            CGColorRenderingIntent::RenderingIntentDefault,
        )
    }
}