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.

10.8 KB
Raw Blame
//! Pure-Rust text measurement, soft wrapping, and rasterization for PocketJS native UI text
//! (`text.layout.native`), backed by `cosmic-text` + `swash`.
use std::cell::RefCell;

use cosmic_text::{Attrs, Buffer, Color, Metrics, Shaping, SwashCache, SwashContent, Weight, Wrap};

use super::fonts::{self, resolve_family, ParsedFont};

thread_local! {
    static SWASH: RefCell<SwashCache> = RefCell::new(SwashCache::new());
}

/// A face request: CSS families, weight (100–900), italic, size in px.
#[derive(Clone, Debug, PartialEq)]
pub struct TextFont {
    pub families: Vec<String>,
    pub weight: u16,
    pub italic: bool,
    pub size: f64,
}

/// A resolved face for text blocks.
pub struct BlockFont {
    parsed: ParsedFont,
}

impl BlockFont {
    pub fn new(spec: &TextFont) -> BlockFont {
        fonts::register();
        BlockFont {
            parsed: ParsedFont {
                families: spec.families.clone(),
                weight: spec.weight,
                italic: spec.italic,
                size: spec.size.max(1.0),
                line_height: None,
                small_caps: false,
                stretch: None,
                oblique: false,
            },
        }
    }

    /// CSS `line-height: normal` for this face, in px.
    pub fn normal_line_height(&self) -> f64 {
        (self.parsed.size * 1.25).ceil()
    }

    /// Advance width of one line (no `'\n'`), in px.
    pub fn measure(&self, line: &str) -> f64 {
        self.measure_spaced(line, 0.0)
    }

    /// Advance width of one line with `tracking` px after each character.
    pub fn measure_spaced(&self, line: &str, tracking: f64) -> f64 {
        if line.is_empty() {
            return 0.0;
        }
        let size = self.parsed.size as f32;
        let lh = self.normal_line_height() as f32;
        let width = fonts::with_font_system(|fs| {
            let fam = resolve_family(fs, &self.parsed.families);
            let attrs = Attrs::new().family(fam).weight(Weight(self.parsed.weight.clamp(100, 900))).style(self.parsed.cosmic_style());
            let mut buf = Buffer::new(fs, Metrics::new(size, lh));
            buf.set_wrap(fs, Wrap::None);
            buf.set_text(fs, line, attrs, Shaping::Advanced);
            buf.shape_until_scroll(fs, false);
            buf.layout_runs().map(|r| r.line_w as f64).fold(0.0, f64::max)
        });
        let extra = if tracking != 0.0 {
            let chars = line.chars().count();
            if chars > 1 { (chars - 1) as f64 * tracking } else { 0.0 }
        } else {
            0.0
        };
        (width + extra).max(0.0)
    }

    /// Soft-break positions (UTF-16 offsets, ascending) keeping each row within `max_width` px.
    pub fn wrap(&self, line: &str, max_width: f64) -> Vec<u32> {
        let mut breaks = Vec::new();
        if line.is_empty() || !(max_width > 0.0) || self.measure(line) <= max_width {
            return breaks;
        }
        let size = self.parsed.size as f32;
        let lh = self.normal_line_height() as f32;
        let byte_starts: Vec<usize> = fonts::with_font_system(|fs| {
            let fam = resolve_family(fs, &self.parsed.families);
            let attrs = Attrs::new().family(fam).weight(Weight(self.parsed.weight.clamp(100, 900))).style(self.parsed.cosmic_style());
            let mut buf = Buffer::new(fs, Metrics::new(size, lh));
            buf.set_wrap(fs, Wrap::WordOrGlyph);
            buf.set_size(fs, Some(max_width as f32), None);
            buf.set_text(fs, line, attrs, Shaping::Advanced);
            buf.shape_until_scroll(fs, false);
            buf.layout_runs()
                .skip(1)
                .filter_map(|run| run.glyphs.first().map(|g| g.start))
                .collect()
        });
        let mut last = 0u32;
        for byte_idx in byte_starts {
            if byte_idx == 0 || byte_idx >= line.len() || !line.is_char_boundary(byte_idx) {
                continue;
            }
            let u16_off = line[..byte_idx].encode_utf16().count() as u32;
            if u16_off > last {
                breaks.push(u16_off);
                last = u16_off;
            }
        }
        breaks
    }
}

/// Pixels of a painted block.
pub struct PaintedBlock {
    pub width: u32,
    pub height: u32,
    /// straight-alpha RGBA8, sRGB
    pub rgba: Vec<u8>,
    /// logical offset of pixel (0, 0) from the block's origin
    pub offset: [f32; 2],
}

/// Paint `text` (lines separated by `'\n'`) in `color` (straight RGBA), aligned within `box_width`
/// (0 left, 1 center, 2 right), `tracking` px after each character, at `scale` device px per px.
#[allow(clippy::too_many_arguments)]
pub fn paint(font: &BlockFont, text: &str, color: [u8; 4], align: u8, box_width: f32, line_height: f32, tracking: f32, scale: f32) -> Option<PaintedBlock> {
    let lines: Vec<&str> = text.split('\n').collect();
    let widths: Vec<f64> = lines.iter().map(|line| font.measure_spaced(line, tracking as f64)).collect();
    if widths.iter().all(|w| *w <= 0.0) {
        return None;
    }
    let scale = scale.max(1.0) as f64;
    let line_h = (line_height as f64).max(1.0);
    let pad_x = (font.parsed.size * 0.25).ceil() + 2.0;
    let pad_y = (font.parsed.size * 0.25).ceil() + 2.0;
    let content_w = widths.iter().cloned().fold(box_width as f64, f64::max);
    let logical_w = content_w + 2.0 * pad_x;
    let logical_h = line_h * lines.len() as f64 + 2.0 * pad_y;
    let width = (logical_w * scale).ceil() as u32;
    let height = (logical_h * scale).ceil() as u32;
    if width == 0 || height == 0 || width > 16384 || height > 16384 {
        return None;
    }

    // Premultiplied scratch buffer, converted to straight alpha at the end.
    let mut pixels = vec![0u8; width as usize * height as usize * 4];
    let px_size = (font.parsed.size * scale) as f32;
    let px_lh = (line_h * scale) as f32;

    fonts::with_font_system(|fs| {
        let fam = resolve_family(fs, &font.parsed.families);
        let attrs = Attrs::new()
            .family(fam)
            .weight(Weight(font.parsed.weight.clamp(100, 900)))
            .style(font.parsed.cosmic_style())
            .color(Color::rgba(color[0], color[1], color[2], color[3]));
        SWASH.with(|sc| {
            let mut swash = sc.borrow_mut();
            for (row, (line, line_w)) in lines.iter().zip(&widths).enumerate() {
                if line.is_empty() {
                    continue;
                }
                let dx = match align {
                    1 => (box_width as f64 - line_w) / 2.0,
                    2 => box_width as f64 - line_w,
                    _ => 0.0,
                };
                let origin_x = ((pad_x + dx) * scale) as f32;
                let origin_y = ((pad_y + row as f64 * line_h) * scale) as f32;

                let mut buf = Buffer::new(fs, Metrics::new(px_size, px_lh));
                buf.set_wrap(fs, Wrap::None);
                buf.set_text(fs, line, attrs, Shaping::Advanced);
                buf.shape_until_scroll(fs, false);

                for run in buf.layout_runs() {
                    let mut char_idx = 0usize;
                    let mut last_start = usize::MAX;
                    for glyph in run.glyphs.iter() {
                        if glyph.start != last_start {
                            if last_start != usize::MAX {
                                char_idx += 1;
                            }
                            last_start = glyph.start;
                        }
                        let extra_x = char_idx as f32 * tracking * scale as f32;
                        let physical = glyph.physical((origin_x + extra_x, origin_y + run.line_y), 1.0);
                        let Some(img) = swash.get_image_uncached(fs, physical.cache_key) else { continue };
                        let gx = physical.x + img.placement.left;
                        let gy = physical.y - img.placement.top;
                        blit_glyph(&mut pixels, width, height, gx, gy, &img, color);
                    }
                }
            }
        });
    });

    // premultiplied → straight alpha
    for px in pixels.chunks_exact_mut(4) {
        let a = px[3] as u32;
        if a != 0 && a != 255 {
            for c in &mut px[..3] {
                *c = ((*c as u32 * 255 + a / 2) / a).min(255) as u8;
            }
        }
    }

    Some(PaintedBlock { width, height, rgba: pixels, offset: [-pad_x as f32, -pad_y as f32] })
}

pub(crate) fn blit_glyph(dst: &mut [u8], w: u32, h: u32, gx: i32, gy: i32, img: &cosmic_text::SwashImage, color: [u8; 4]) {
    let gw = img.placement.width as i32;
    let gh = img.placement.height as i32;
    if gw <= 0 || gh <= 0 {
        return;
    }
    let cr = color[0] as u32;
    let cg = color[1] as u32;
    let cb = color[2] as u32;
    let ca = color[3] as u32;

    for row in 0..gh {
        let dy = gy + row;
        if dy < 0 || dy >= h as i32 {
            continue;
        }
        for col in 0..gw {
            let dx = gx + col;
            if dx < 0 || dx >= w as i32 {
                continue;
            }
            let src_idx = (row as usize) * (gw as usize) + (col as usize);
            let (sr, sg, sb, sa) = match img.content {
                SwashContent::Mask => {
                    let cov = img.data[src_idx] as u32;
                    if cov == 0 {
                        continue;
                    }
                    let a = (cov * ca + 127) / 255;
                    ((cr * a + 127) / 255, (cg * a + 127) / 255, (cb * a + 127) / 255, a)
                }
                SwashContent::Color => {
                    let o = src_idx * 4;
                    let a = (img.data[o + 3] as u32 * ca + 127) / 255;
                    if a == 0 {
                        continue;
                    }
                    (
                        (img.data[o] as u32 * a + 127) / 255,
                        (img.data[o + 1] as u32 * a + 127) / 255,
                        (img.data[o + 2] as u32 * a + 127) / 255,
                        a,
                    )
                }
                SwashContent::SubpixelMask => {
                    let o = src_idx * 4;
                    let cov = ((img.data[o] as u32 + img.data[o + 1] as u32 + img.data[o + 2] as u32) / 3).min(255);
                    if cov == 0 {
                        continue;
                    }
                    let a = (cov * ca + 127) / 255;
                    ((cr * a + 127) / 255, (cg * a + 127) / 255, (cb * a + 127) / 255, a)
                }
            };
            let di = ((dy as usize) * (w as usize) + (dx as usize)) * 4;
            let inv = 255 - sa;
            dst[di] = (sr + (dst[di] as u32 * inv + 127) / 255).min(255) as u8;
            dst[di + 1] = (sg + (dst[di + 1] as u32 * inv + 127) / 255).min(255) as u8;
            dst[di + 2] = (sb + (dst[di + 2] as u32 * inv + 127) / 255).min(255) as u8;
            dst[di + 3] = (sa + (dst[di + 3] as u32 * inv + 127) / 255).min(255) as u8;
        }
    }
}