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.
Rust electron-alternativegame-engineglobal-illuminationgraphicsjavascript-runtimemetalpath-tracingray-tracingreal-time-renderingrenderingrustthreejstypescriptvoxelvulkanwebgpuwgpu
//! Canvas text: layout with CoreText (fonts and fallback from [`crate::fonts`]), glyph placement
//! that reproduces Skia's (subpixel x positions quantized to ¼ px, baselines snapped to whole
//! pixels for axis-aligned transforms), Chrome's baselines and `measureText` metrics.
use std::ptr::NonNull;
use std::rc::Rc;
use objc2_core_foundation::{CFArray, CFAttributedString, CFData, CFDictionary, CFMutableAttributedString, CFNumber, CFRange, CFRetained, CFString, CFType, CGAffineTransform, CGPoint, CGRect, CGSize};
use objc2_core_graphics::{
CGBitmapContextCreate, CGBitmapInfo, CGColorRenderingIntent, CGColorSpace, CGContext, CGDataProvider, CGImage, CGImageAlphaInfo, CGImageByteOrderInfo, CGLineJoin, CGMutablePath, CGPath,
CGTextDrawingMode,
};
use objc2_core_text::{kCTFontAttributeName, kCTKernAttributeName, CTFont, CTFontOrientation, CTLine, CTRun};
use crate::canvas::{apply, apply_line_state, concat, fill_clip_with, invert, Paint, State, IDENTITY};
use crate::fonts::{self, Font};
pub(crate) struct GlyphRun {
pub ct: CFRetained<CTFont>,
pub font: Rc<Font>,
pub glyphs: Vec<u16>,
/// glyph origins in text space (y down, origin = pen start on the baseline)
pub pos: Vec<(f64, f64)>,
}
pub(crate) struct Layout {
pub runs: Vec<GlyphRun>,
pub width: f64,
}
/// Lay out `text` on one line (canvas text never wraps; ASCII whitespace becomes spaces).
pub(crate) fn layout(font: &Rc<Font>, text: &[u16], letter_spacing: f64, word_spacing: f64, kerning: bool) -> Layout {
let text: Vec<u16> = text.iter().map(|&c| if matches!(c, 0x09 | 0x0A | 0x0C | 0x0D) { 0x20 } else { c }).collect();
if text.is_empty() {
return Layout { runs: Vec::new(), width: 0.0 };
}
let font_runs = font.runs(&text);
let s = fonts::cfstring_utf16(&text);
let Some(attr) = CFMutableAttributedString::new(None, 0) else { return Layout { runs: Vec::new(), width: 0.0 } };
unsafe { CFMutableAttributedString::replace_string(Some(&attr), CFRange { location: 0, length: 0 }, Some(&s)) };
for r in &font_runs {
let range = CFRange { location: r.start as isize, length: (r.end - r.start) as isize };
unsafe { CFMutableAttributedString::set_attribute(Some(&attr), range, Some(kCTFontAttributeName), Some(&r.font.plain as &CFType)) };
}
if !kerning {
let zero = CFNumber::new_f64(0.0);
unsafe { CFMutableAttributedString::set_attribute(Some(&attr), CFRange { location: 0, length: text.len() as isize }, Some(kCTKernAttributeName), Some(&*zero as &CFType)) };
}
let attr_ref: &CFAttributedString = &attr;
let line = unsafe { CTLine::with_attributed_string(attr_ref) };
let mut width = unsafe { line.typographic_bounds(std::ptr::null_mut(), std::ptr::null_mut(), std::ptr::null_mut()) };
// Letter/word spacing: extra advance after each grapheme / space, accumulated per UTF-16 index.
let spacing = letter_spacing != 0.0 || word_spacing != 0.0;
let mut extra_at = Vec::new();
if spacing {
extra_at = vec![0.0; text.len() + 1];
let mut acc = 0.0;
let mut i = 0;
while i < text.len() {
let end = fonts::grapheme_end(&text, i);
for e in extra_at.iter_mut().take(end).skip(i) {
*e = acc;
}
acc += letter_spacing;
if text[i] == 0x20 || text[i] == 0xA0 {
acc += word_spacing;
}
i = end;
}
extra_at[text.len()] = acc;
width += acc;
}
let runs_arr = unsafe { line.glyph_runs() };
let runs_arr: CFRetained<CFArray<CTRun>> = unsafe { CFRetained::cast_unchecked(runs_arr) };
let mut runs = Vec::new();
for run in runs_arr.iter() {
let n = unsafe { run.glyph_count() } as usize;
if n == 0 {
continue;
}
let mut glyphs = vec![0u16; n];
let mut pts = vec![CGPoint { x: 0.0, y: 0.0 }; n];
let mut idx = vec![0isize; n];
let all = CFRange { location: 0, length: 0 };
unsafe {
run.glyphs(all, NonNull::new_unchecked(glyphs.as_mut_ptr()));
run.positions(all, NonNull::new_unchecked(pts.as_mut_ptr()));
run.string_indices(all, NonNull::new_unchecked(idx.as_mut_ptr()));
}
let attrs = unsafe { run.attributes() };
let attrs: CFRetained<CFDictionary<CFString, CFType>> = unsafe { CFRetained::cast_unchecked(attrs) };
let ct = attrs.get(unsafe { kCTFontAttributeName }).and_then(|v| v.downcast::<CTFont>().ok());
let first = idx[0].max(0) as usize;
let ours = font_runs.iter().find(|r| first >= r.start && first < r.end).map(|r| r.font.clone()).unwrap_or_else(|| font.clone());
let ct = ct.unwrap_or_else(|| ours.plain.clone());
// If CoreText substituted a face we did not pick, draw with it but without our synthesis.
let same = unsafe { ct.post_script_name() }.to_string() == unsafe { ours.plain.post_script_name() }.to_string();
let pos = pts
.iter()
.zip(&idx)
.map(|(p, &i)| {
let e = if spacing { extra_at[(i.max(0) as usize).min(text.len())] } else { 0.0 };
(p.x + e, -p.y)
})
.collect();
let font_for_run = if same { ours } else { fonts::resolve(&fonts::FontQuery { families: &[unsafe { ct.family_name() }.to_string()], weight: 400, italic: false, size: font.size }) };
runs.push(GlyphRun { ct, font: font_for_run, glyphs, pos });
}
Layout { runs, width }
}
/// Offset from the `y` passed to fillText to the alphabetic baseline (Blink's GetFontBaseline).
pub(crate) fn baseline_offset(font: &Font, baseline: u8) -> f64 {
let (em_a, em_d) = font.em_ascent_descent();
let m = font.line_metrics();
match baseline {
1 => em_a,
2 => m.ascent * 0.8,
3 => (em_a - em_d) / 2.0,
4 => -m.descent,
5 => -em_d,
_ => 0.0,
}
}
/// Union of glyph ink rects in text space (y down): (left, top, right, bottom).
pub(crate) fn ink_bounds(layout: &Layout) -> Option<(f64, f64, f64, f64)> {
let mut b: Option<(f64, f64, f64, f64)> = None;
for run in &layout.runs {
let mut rects = vec![CGRect::default(); run.glyphs.len()];
unsafe { run.ct.bounding_rects_for_glyphs(CTFontOrientation::Horizontal, NonNull::new_unchecked(run.glyphs.as_ptr() as *mut u16), rects.as_mut_ptr(), run.glyphs.len() as isize) };
for (r, &(x, y)) in rects.iter().zip(&run.pos) {
if r.size.width <= 0.0 || r.size.height <= 0.0 {
continue;
}
let mut l = x + r.origin.x;
let t = y - (r.origin.y + r.size.height);
let mut rr = x + r.origin.x + r.size.width;
let bt = y - r.origin.y;
if run.font.synthetic_italic {
// skew moves the top right / bottom left
l += -(r.origin.y.min(0.0)) * -0.25;
rr += (r.origin.y + r.size.height).max(0.0) * 0.25;
}
let grow = if run.font.synthetic_bold { fonts::fake_bold_stroke(run.font.size) / 2.0 } else { 0.0 };
let g = (l - grow, t - grow, rr + grow, bt + grow);
b = Some(match b {
None => g,
Some(o) => (o.0.min(g.0), o.1.min(g.1), o.2.max(g.2), o.3.max(g.3)),
});
}
}
b
}
fn skewed(ct: &CTFont) -> CFRetained<CTFont> {
let m = CGAffineTransform { a: 1.0, b: 0.0, c: 0.25, d: 1.0, tx: 0.0, ty: 0.0 };
let desc = unsafe { ct.font_descriptor() };
unsafe { CTFont::with_font_descriptor(&desc, ct.size(), &m) }
}
/// Device position Skia would put a glyph at: x on a ¼-pixel grid; y on whole pixels when the
/// transform is axis-aligned (¼ grid otherwise). Text drawn as paths (> 256 device px) is exact.
fn quantize(x: f64, y: f64, axis_aligned: bool, as_paths: bool) -> (f64, f64) {
if as_paths {
return (x, y);
}
let qx = ((x + 0.125) * 4.0).floor() / 4.0;
let qy = if axis_aligned { (y + 0.5).floor() } else { ((y + 0.125) * 4.0).floor() / 4.0 };
(qx, qy)
}
/// Draw a laid-out line. `m` maps text space to device pixels; the context CTM on entry is the
/// device (canvas pixel) space.
pub(crate) fn draw(cg: &CGContext, s: &State, layout: &Layout, m: &CGAffineTransform, paint: &Paint, stroke: bool) {
// Chrome (Skia on macOS) renders ordinary glyphs as CoreGraphics coverage masks; fake-bold,
// stroked and very large text go through outlines, color glyphs through bitmaps.
let scale = (m.a * m.d - m.b * m.c).abs().sqrt();
let (masked, direct): (Vec<&GlyphRun>, Vec<&GlyphRun>) =
layout.runs.iter().partition(|r| !stroke && !r.font.color && !r.font.synthetic_bold && r.font.size * scale <= 256.0);
if !masked.is_empty() {
draw_masked(cg, s, &masked, m, paint);
}
if !direct.is_empty() {
let rest = Layout { runs: direct.into_iter().map(|r| GlyphRun { ct: r.ct.clone(), font: r.font.clone(), glyphs: r.glyphs.clone(), pos: r.pos.clone() }).collect(), width: layout.width };
draw_direct(cg, s, &rest, m, paint, stroke);
}
}
/// Device position of each glyph origin (quantized like Skia).
fn device_positions(run: &GlyphRun, m: &CGAffineTransform) -> Vec<(f64, f64)> {
let axis_aligned = m.b == 0.0 && m.c == 0.0;
let as_paths = run.font.size * (m.a * m.d - m.b * m.c).abs().sqrt() > 256.0;
run.pos
.iter()
.map(|&(x, y)| {
let (dx, dy) = apply(m, x, y);
quantize(dx, dy, axis_aligned, as_paths)
})
.collect()
}
/// Skia's glyph masks: each glyph drawn black on white by CoreGraphics into an opaque RGB bitmap
/// with font smoothing, luminance → coverage; the coverage then masks the paint.
fn draw_masked(cg: &CGContext, s: &State, runs: &[&GlyphRun], m: &CGAffineTransform, paint: &Paint) {
let lin = CGAffineTransform { tx: 0.0, ty: 0.0, ..*m };
let Some(lin_inv) = invert(&lin) else { return };
let flip = CGAffineTransform { a: 1.0, b: 0.0, c: 0.0, d: -1.0, tx: 0.0, ty: 0.0 };
let user = concat(&flip, &lin);
// Device bounds of all glyphs (+ a margin for smoothing dilation).
let mut bx0 = f64::INFINITY;
let mut by0 = f64::INFINITY;
let mut bx1 = f64::NEG_INFINITY;
let mut by1 = f64::NEG_INFINITY;
let mut placed = Vec::with_capacity(runs.len());
for run in runs {
let dev = device_positions(run, m);
let ct = if run.font.synthetic_italic { skewed(&run.ct) } else { run.ct.clone() };
let mut rects = vec![CGRect::default(); run.glyphs.len()];
unsafe { ct.bounding_rects_for_glyphs(CTFontOrientation::Horizontal, NonNull::new_unchecked(run.glyphs.as_ptr() as *mut u16), rects.as_mut_ptr(), run.glyphs.len() as isize) };
for (r, &(qx, qy)) in rects.iter().zip(&dev) {
if r.size.width <= 0.0 || r.size.height <= 0.0 {
continue;
}
for (cx, cy) in [(r.origin.x, r.origin.y), (r.origin.x + r.size.width, r.origin.y), (r.origin.x, r.origin.y + r.size.height), (r.origin.x + r.size.width, r.origin.y + r.size.height)] {
// glyph space is y-up: S flips it into text space, `lin` maps to device
let (ex, ey) = apply(&lin, cx, -cy);
bx0 = bx0.min(qx + ex);
by0 = by0.min(qy + ey);
bx1 = bx1.max(qx + ex);
by1 = by1.max(qy + ey);
}
}
placed.push((ct, dev));
}
if !bx0.is_finite() {
return;
}
let clip = CGContext::clip_bounding_box(Some(cg));
let x0 = (bx0 - 2.0).floor().max(clip.origin.x.floor());
let y0 = (by0 - 2.0).floor().max(clip.origin.y.floor());
let x1 = (bx1 + 2.0).ceil().min((clip.origin.x + clip.size.width).ceil());
let y1 = (by1 + 2.0).ceil().min((clip.origin.y + clip.size.height).ceil());
if x1 <= x0 || y1 <= y0 {
return;
}
let (w, h) = ((x1 - x0) as usize, (y1 - y0) as usize);
if w * h > 64 << 20 {
return;
}
let mut buf = vec![0xFFu8; w * h * 4];
let Some(rgb) = CGColorSpace::new_device_rgb() else { return };
let info = CGImageAlphaInfo::NoneSkipFirst.0 | CGImageByteOrderInfo::Order32Little.0;
let Some(off) = (unsafe { CGBitmapContextCreate(buf.as_mut_ptr().cast(), w, h, 8, w * 4, Some(&rgb), info) }) else { return };
let o = Some(&*off);
CGContext::translate_ctm(o, -x0, y1);
CGContext::scale_ctm(o, 1.0, -1.0);
CGContext::concat_ctm(o, user);
CGContext::set_text_matrix(o, IDENTITY);
CGContext::set_should_antialias(o, true);
CGContext::set_allows_font_smoothing(o, true);
CGContext::set_should_smooth_fonts(o, true);
CGContext::set_allows_font_subpixel_positioning(o, true);
CGContext::set_should_subpixel_position_fonts(o, true);
CGContext::set_allows_font_subpixel_quantization(o, false);
CGContext::set_should_subpixel_quantize_fonts(o, false);
CGContext::set_text_drawing_mode(o, CGTextDrawingMode::Fill);
CGContext::set_gray_fill_color(o, 0.0, 1.0);
let to_user = |dx: f64, dy: f64| {
let (u, v) = apply(&lin_inv, dx, dy);
CGPoint { x: u, y: -v }
};
for (run, (ct, dev)) in runs.iter().zip(&placed) {
let pts: Vec<CGPoint> = dev.iter().map(|&(qx, qy)| to_user(qx, qy)).collect();
unsafe { ct.draw_glyphs(NonNull::new_unchecked(run.glyphs.as_ptr() as *mut u16), NonNull::new_unchecked(pts.as_ptr() as *mut CGPoint), run.glyphs.len(), &off) };
}
drop(off);
// BGRX (little-endian XRGB) → coverage, Skia's luminance weights
let mut mask = vec![0u8; w * h];
for (i, p) in buf.chunks_exact(4).enumerate() {
let (b, g, r) = (255 - p[0] as u32, 255 - p[1] as u32, 255 - p[2] as u32);
mask[i] = ((r * 54 + g * 183 + b * 19) >> 8) as u8;
}
let data = CFData::from_bytes(&mask);
let Some(provider) = CGDataProvider::with_cf_data(Some(&data)) else { return };
let Some(gray) = CGColorSpace::new_device_gray() else { return };
let Some(img) = (unsafe { CGImage::new(w, h, 8, 8, w, Some(&gray), CGBitmapInfo(0), Some(&provider), std::ptr::null(), false, CGColorRenderingIntent::RenderingIntentDefault) }) else { return };
CGContext::save_g_state(Some(cg));
// the mask image is y-up: flip around its rect, clip, flip back
CGContext::translate_ctm(Some(cg), 0.0, y1);
CGContext::scale_ctm(Some(cg), 1.0, -1.0);
CGContext::clip_to_mask(Some(cg), CGRect { origin: CGPoint { x: x0, y: 0.0 }, size: CGSize { width: w as f64, height: h as f64 } }, Some(&img));
CGContext::scale_ctm(Some(cg), 1.0, -1.0);
CGContext::translate_ctm(Some(cg), 0.0, -y1);
match paint {
Paint::Color(c, _) => {
CGContext::set_fill_color_with_color(Some(cg), Some(c));
CGContext::fill_rect(Some(cg), CGRect { origin: CGPoint { x: x0, y: y0 }, size: CGSize { width: w as f64, height: h as f64 } });
}
_ => fill_clip_with(cg, paint, &s.ctm),
}
CGContext::restore_g_state(Some(cg));
}
fn draw_direct(cg: &CGContext, s: &State, layout: &Layout, m: &CGAffineTransform, paint: &Paint, stroke: bool) {
let lin = CGAffineTransform { tx: 0.0, ty: 0.0, ..*m };
let Some(lin_inv) = invert(&lin) else { return };
let axis_aligned = m.b == 0.0 && m.c == 0.0;
let device_size = |size: f64| size * (m.a * m.d - m.b * m.c).abs().sqrt();
let flip = CGAffineTransform { a: 1.0, b: 0.0, c: 0.0, d: -1.0, tx: 0.0, ty: 0.0 };
// CG user space for glyphs: y-up text space mapped by the linear part of `m`.
let user = concat(&flip, &lin);
let to_user = |dx: f64, dy: f64| {
let (u, v) = apply(&lin_inv, dx, dy);
CGPoint { x: u, y: -v }
};
if let Paint::Color(color, _) = paint {
CGContext::save_g_state(Some(cg));
CGContext::concat_ctm(Some(cg), user);
CGContext::set_text_matrix(Some(cg), IDENTITY);
CGContext::set_should_antialias(Some(cg), true);
CGContext::set_allows_font_smoothing(Some(cg), true);
CGContext::set_should_smooth_fonts(Some(cg), false); // outlines and bitmaps: Skia draws these unsmoothed
CGContext::set_allows_font_subpixel_positioning(Some(cg), true);
CGContext::set_should_subpixel_position_fonts(Some(cg), true);
CGContext::set_allows_font_subpixel_quantization(Some(cg), false);
CGContext::set_should_subpixel_quantize_fonts(Some(cg), false);
CGContext::set_fill_color_with_color(Some(cg), Some(color));
CGContext::set_stroke_color_with_color(Some(cg), Some(color));
for run in &layout.runs {
let as_paths = device_size(run.font.size) > 256.0;
let positions: Vec<CGPoint> = run
.pos
.iter()
.map(|&(x, y)| {
let (dx, dy) = apply(m, x, y);
let (qx, qy) = quantize(dx, dy, axis_aligned, as_paths);
to_user(qx, qy)
})
.collect();
let ct = if run.font.synthetic_italic { skewed(&run.ct) } else { run.ct.clone() };
if stroke {
apply_line_state(cg, s);
CGContext::set_text_drawing_mode(Some(cg), CGTextDrawingMode::Stroke);
} else if run.font.synthetic_bold {
CGContext::set_line_width(Some(cg), fonts::fake_bold_stroke(run.font.size));
CGContext::set_line_join(Some(cg), CGLineJoin::Miter);
CGContext::set_miter_limit(Some(cg), 4.0);
CGContext::set_text_drawing_mode(Some(cg), CGTextDrawingMode::FillStroke);
} else {
CGContext::set_text_drawing_mode(Some(cg), CGTextDrawingMode::Fill);
}
unsafe { ct.draw_glyphs(NonNull::new_unchecked(run.glyphs.as_ptr() as *mut u16), NonNull::new_unchecked(positions.as_ptr() as *mut CGPoint), run.glyphs.len(), cg) };
}
CGContext::restore_g_state(Some(cg));
return;
}
// Gradient / pattern: build the glyph outlines (device space) and paint through them.
let outline = CGMutablePath::new();
let mut color_runs = Vec::new();
for run in &layout.runs {
if run.font.color {
color_runs.push(run);
continue;
}
let ct = if run.font.synthetic_italic { skewed(&run.ct) } else { run.ct.clone() };
for (g, &(x, y)) in run.glyphs.iter().zip(&run.pos) {
let Some(gp) = (unsafe { ct.path_for_glyph(*g, std::ptr::null()) }) else { continue };
// glyph (y-up) → text space at (x, y) → device
let place = concat(&CGAffineTransform { a: 1.0, b: 0.0, c: 0.0, d: -1.0, tx: x, ty: y }, m);
unsafe { CGMutablePath::add_path(Some(&outline), &place, Some(&gp)) };
if run.font.synthetic_bold && !stroke {
let w = fonts::fake_bold_stroke(run.font.size);
if let Some(sp) = unsafe { CGPath::new_copy_by_stroking_path(Some(&gp), std::ptr::null(), w, objc2_core_graphics::CGLineCap::Butt, CGLineJoin::Miter, 4.0) } {
unsafe { CGMutablePath::add_path(Some(&outline), &place, Some(&sp)) };
}
}
}
}
CGContext::save_g_state(Some(cg));
if stroke {
if let Some(inv) = invert(&s.ctm) {
let user_path = unsafe { CGPath::new_copy_by_transforming_path(Some(&outline), &inv) };
CGContext::concat_ctm(Some(cg), s.ctm);
CGContext::add_path(Some(cg), user_path.as_deref());
apply_line_state(cg, s);
CGContext::replace_path_with_stroked_path(Some(cg));
CGContext::clip(Some(cg));
CGContext::concat_ctm(Some(cg), inv);
fill_clip_with(cg, paint, &s.ctm);
}
} else if !CGPath::is_empty(Some(&outline)) {
CGContext::add_path(Some(cg), Some(&outline));
CGContext::clip(Some(cg));
fill_clip_with(cg, paint, &s.ctm);
}
CGContext::restore_g_state(Some(cg));
if !color_runs.is_empty() {
let opaque = Paint::color(0.0, 0.0, 0.0, 1.0);
for run in color_runs {
let one = Layout { runs: vec![GlyphRun { ct: run.ct.clone(), font: run.font.clone(), glyphs: run.glyphs.clone(), pos: run.pos.clone() }], width: 0.0 };
draw_direct(cg, s, &one, m, &opaque, false);
}
}
}
/// `measureText` results, in Chrome's order: width, actualBoundingBoxLeft, actualBoundingBoxRight,
/// fontBoundingBoxAscent, fontBoundingBoxDescent, actualBoundingBoxAscent,
/// actualBoundingBoxDescent, emHeightAscent, emHeightDescent, hangingBaseline,
/// alphabeticBaseline, ideographicBaseline.
pub(crate) fn measure(font: &Rc<Font>, s: &State, text: &[u16]) -> [f64; 12] {
let layout = layout(font, text, s.letter_spacing, s.word_spacing, s.kerning);
let width = layout.width;
let m = font.line_metrics();
let (em_a, em_d) = font.em_ascent_descent();
let base = baseline_offset(font, s.baseline);
let dx = match (s.align, s.rtl) {
(4, _) => -width / 2.0,
(3, _) | (1, false) | (0, true) => -width,
_ => 0.0,
};
let (l, t, r, b) = ink_bounds(&layout).unwrap_or((0.0, 0.0, 0.0, 0.0));
[
width,
-(l + dx),
r + dx,
m.ascent - base,
m.descent + base,
-t - base,
b + base,
em_a - base,
em_d + base,
m.ascent * 0.8 - base,
-base,
-m.descent - base,
]
}