diff --git a/Cargo.lock b/Cargo.lock index 8abf04ca9cd9181a0a018af1f89b95bab958c4d6..be79126df06e532630de9cc62482a041d83ddc1d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -731,6 +731,15 @@ version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7f8f80099a98041a3d1622845c271458a2d73e688351bf3cb999266764b81d48" +[[package]] +name = "core_maths" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77745e017f5edba1a9c1d854f6f3a52dac8a12dd5af5d2f54aecf61e43d80d30" +dependencies = [ + "libm", +] + [[package]] name = "coreaudio-rs" version = "0.11.3" @@ -1003,12 +1012,13 @@ dependencies = [ "cc", "cpal", "exr", + "fontdb 0.23.0", "image", "model", "png", "pollster", + "rustybuzz", "symphonia", - "text", "theme", "wgpu", "zeno", @@ -1217,6 +1227,19 @@ dependencies = [ "roxmltree 0.20.0", ] +[[package]] +name = "fontdb" +version = "0.23.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "457e789b3d1202543297a350643cf459f836cade38934e7a4cf6a39e7cde2905" +dependencies = [ + "log", + "memmap2", + "slotmap", + "tinyvec", + "ttf-parser", +] + [[package]] name = "fontdb" version = "0.24.0" @@ -2956,6 +2979,24 @@ version = "1.0.23" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" +[[package]] +name = "rustybuzz" +version = "0.20.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fd3c7c96f8a08ee34eff8857b11b49b07d71d1c3f4e88f8a88d4c9e9f90b1702" +dependencies = [ + "bitflags 2.13.2", + "bytemuck", + "core_maths", + "log", + "smallvec", + "ttf-parser", + "unicode-bidi-mirroring", + "unicode-ccc", + "unicode-properties", + "unicode-script", +] + [[package]] name = "same-file" version = "1.0.6" @@ -3954,6 +3995,9 @@ name = "ttf-parser" version = "0.25.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d2df906b07856748fa3f6e0ad0cbaa047052d4a7dd609e231c4f72cee8c36f31" +dependencies = [ + "core_maths", +] [[package]] name = "typenum" @@ -3983,7 +4027,7 @@ dependencies = [ "block2 0.6.2", "draw", "edit", - "fontdb", + "fontdb 0.24.0", "knife-window-host", "libc", "nucleo-matcher", @@ -4013,6 +4057,18 @@ version = "0.3.18" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5c1cb5db39152898a79168971543b1cb5020dff7fe43c8dc468b0885f5e29df5" +[[package]] +name = "unicode-bidi-mirroring" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5dfa6e8c60bb66d49db113e0125ee8711b7647b5579dc7f5f19c42357ed039fe" + +[[package]] +name = "unicode-ccc" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce61d488bcdc9bc8b5d1772c404828b17fc481c0a582b5581e95fb233aef503e" + [[package]] name = "unicode-general-category" version = "1.1.0" @@ -4040,6 +4096,12 @@ dependencies = [ "tinyvec", ] +[[package]] +name = "unicode-properties" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "993ad287eb20e8ba755312801cfe1413e0f25d604075863acaddca10b04c1833" + [[package]] name = "unicode-script" version = "0.5.9" @@ -4072,7 +4134,7 @@ checksum = "977d0a4abdef933f424a99fe09f95576e089b90aebc6f016a3bc813762493e91" dependencies = [ "base64", "data-url", - "fontdb", + "fontdb 0.24.0", "harfrust 0.12.0", "imagesize", "kurbo", diff --git a/Cargo.toml b/Cargo.toml index 6911caadd041415309ec2d7977c322a4a99987fc..1ac988270ce8af3ae12df08375cb137b71e87397 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -34,10 +34,12 @@ theme = { path = "../the-knife/knife/theme" } accesskit = "0.25.1" accesskit_winit = { version = "0.34", default-features = false, features = ["rwh_06"] } bytemuck = { version = "1.25", features = ["derive"] } +fontdb = { version = "0.23", default-features = false, features = ["std", "fs", "memmap"] } image = { version = "0.25", default-features = false, features = ["jpeg", "png", "exr", "tiff", "webp"] } mlua = { version = "0.10", features = ["lua54", "vendored"] } png = "0.18" pollster = "0.4" +rustybuzz = "0.20" wgpu = "30.0.1" winit = "0.30.13" zeno = "0.3.3" diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index a630fe46d4e11957a8c11ac1a714f109469f891d..a0f950602f369bcf560e6003b9f904389569b419 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -12,12 +12,13 @@ path = "src/bin/render_check.rs" bytemuck.workspace = true cpal = "0.15" exr = "1.74" +fontdb.workspace = true image.workspace = true model.workspace = true png.workspace = true pollster.workspace = true +rustybuzz.workspace = true symphonia = { version = "0.5", default-features = false, features = ["wav", "mp3", "flac", "ogg", "aac", "isomp4", "pcm"] } -text.workspace = true theme.workspace = true wgpu.workspace = true zeno.workspace = true diff --git a/crates/engine/src/eval/text_3d.rs b/crates/engine/src/eval/text_3d.rs index bc5f6f27ad99bc6f80f63ba42abcda284b819d0a..c5ad9441f499568adcae331cb6c7439d9bc32d0f 100644 --- a/crates/engine/src/eval/text_3d.rs +++ b/crates/engine/src/eval/text_3d.rs @@ -111,7 +111,7 @@ impl Engine { time: f64, frame_i: i64, comp_dims: [u32; 2], - enc: &mut wgpu::CommandEncoder, + _enc: &mut wgpu::CommandEncoder, stats: &mut EvalStats, ) -> CachedTexture { let w = comp.eval_number(node, "Width", time, comp.width as f64, &self.expr) as u32; @@ -190,8 +190,8 @@ impl Engine { stats.nodes_evaluated += 1; let size_px = size_norm * size[0] as f32; - let outline_radius = if is_text_outline && outline_thickness > 1e-4 { - (outline_thickness * size_px * 0.50).clamp(1.0, 28.0) + let outline_width_px = if is_text_outline && outline_thickness > 1e-4 { + (outline_thickness * size_px).clamp(2.0, 56.0) } else { 0.0 }; @@ -203,7 +203,6 @@ impl Engine { } else { 0 }; - let dod_pad = (outline_radius.ceil() as i32 + 2).max(border_pad_px); let (tex_size, origin, mut pixels) = rasterize_text_plus( size, &TextPlusParams { @@ -221,8 +220,10 @@ impl Engine { write_on_end: write_end, shear_x, cls: cls_entries, + outline_rgba: outline_rgba.map(|c| c * elem2_opacity), + outline_width_px, }, - dod_pad, + border_pad_px, ); // Fusion TextPlus ElementShape = 2 (BorderFill): draw filled (optionally rounded) box(es) @@ -433,37 +434,14 @@ impl Engine { } } - let fill_tex = create_texture_dod( - &self.device, - tex_size, - origin, - size, - if outline_radius > 0.0 { 0 } else { key }, - ); + let final_tex = create_texture_dod(&self.device, tex_size, origin, size, key); self.queue.write_texture( - fill_tex.texture.as_image_copy(), + final_tex.texture.as_image_copy(), &pixels, wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(tex_size[0] * 4), rows_per_image: Some(tex_size[1]) }, wgpu::Extent3d { width: tex_size[0], height: tex_size[1], depth_or_array_layers: 1 }, ); - let final_tex = if outline_radius > 0.0 { - // Single-pass circular Euclidean L2 outline + fill-over-outline composite across DoD! - let dst = create_texture_dod(&self.device, tex_size, origin, size, key); - let mut u = UniformParams::default(); - u.p[0] = [ - outline_rgba[0] * elem2_opacity, - outline_rgba[1] * elem2_opacity, - outline_rgba[2] * elem2_opacity, - outline_rgba[3] * elem2_opacity, - ]; - u.p[1] = [outline_radius, 0.0, 0.0, 0.0]; - self.dispatch_op(enc, ShaderOp::TextOutline, &fill_tex.view, &self.dummy.view, &self.dummy.view, &dst, &u); - dst - } else { - fill_tex - }; - self.cache.insert(key, final_tex.clone(), node.id, frame_i); final_tex } @@ -545,7 +523,7 @@ impl Engine { for ms in &mesh_specs { let tex = if let Some(t3d) = &ms.text3d { let tnode = comp.node(t3d.node_id); - Some(self.eval_text_plus(comp, tnode, time, frame_i, [1024, 512], enc, stats)) + Some(self.eval_text_plus(comp, tnode, time, frame_i, [2048, 1024], enc, stats)) } else { ms.material_node.map(|mid| self.eval_node(comp, mid, time, enc, visiting, stats)) }; diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index cbc394ec8f3912cb7479dd7354f2a43cfdedffe9..30afa4dad9c43cccdd0f128bdc7006de3fcf31d1 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -10,6 +10,7 @@ pub mod particles; pub mod profile; pub mod ram_cache; pub mod scene3d; +pub mod text_engine; pub use audio::{AudioPlayer, AudioTrack}; pub use cache::{ diff --git a/crates/engine/src/media.rs b/crates/engine/src/media.rs index 80c5f59e6e52fee1cd9cebe86a7ac6f3d76484d3..c138c5fa73b49422ff8d81cc8ad2d8efb980be30 100644 --- a/crates/engine/src/media.rs +++ b/crates/engine/src/media.rs @@ -1,6 +1,7 @@ //! Media loading (PNG/JPG/EXR/TIFF stills & numbered image sequences) and -//! CPU rasterizers (`TextPlus` via `knife/text` CoreText, `PolylineMask` via `zeno`). +//! CPU rasterizers (`TextPlus` via `text_engine`, `PolylineMask` via `zeno`). +use crate::text_engine; use model::{ClipSpec, ClsEntry, PolyPoint}; use std::collections::HashMap; use std::path::{Path, PathBuf}; @@ -663,7 +664,7 @@ pub fn resolve_clip_path(clip: &ClipSpec, frame: i64) -> Option { } } -/// Parameters for rasterizing a Fusion `TextPlus` node using `knife/text` (CoreText). +/// Parameters for rasterizing a Fusion `TextPlus` node with [`crate::text_engine`]. pub struct TextPlusParams<'a> { pub text: &'a str, pub font_family: &'a str, @@ -679,15 +680,19 @@ pub struct TextPlusParams<'a> { pub write_on_end: f32, pub shear_x: f32, // Fusion CharacterShearX pub cls: &'a [ClsEntry], // Optional StyledTextCLS per-character overrides + pub outline_rgba: [f32; 4], // Fusion Element 2 color, already scaled by Opacity2 + pub outline_width_px: f32, // Fusion Thickness2 as a full stroke width; 0 disables the outline } -/// Rasterizes a `TextPlus` fill layer into premultiplied RGBA8 with automatic Domain-of-Definition -/// (DoD) expansion so off-screen glyphs (e.g. text shifted into frame by a downstream `Transform`) -/// are never clipped. Returns `(tex_size, dod_origin_px, rgba)`. -pub fn rasterize_text_plus(dims: [u32; 2], params: &TextPlusParams<'_>, outline_pad: i32) -> ([u32; 2], [i32; 2], Vec) { +/// Rasterizes a `TextPlus` layer (outline under fill) into premultiplied RGBA8 with automatic +/// Domain-of-Definition (DoD) expansion so off-screen glyphs (e.g. text shifted into frame by a +/// downstream `Transform`) are never clipped; `dod_pad` adds margin for decoration drawn from +/// the result. Returns `(tex_size, dod_origin_px, rgba)`. +pub fn rasterize_text_plus(dims: [u32; 2], params: &TextPlusParams<'_>, dod_pad: i32) -> ([u32; 2], [i32; 2], Vec) { let [w, h] = dims; + let empty = || (dims, [0, 0], vec![0u8; (w as usize) * (h as usize) * 4]); if params.text.is_empty() || params.size_norm <= 1e-4 { - return (dims, [0, 0], vec![0u8; (w as usize) * (h as usize) * 4]); + return empty(); } // Compute WriteOn character range on the FULL string so glyph layout never shifts as letters type on! @@ -695,8 +700,12 @@ pub fn rasterize_text_plus(dims: [u32; 2], params: &TextPlusParams<'_>, outline_ let c_start = ((params.write_on_start.clamp(0.0, 1.0)) * total_chars as f32).floor() as usize; let c_end = ((params.write_on_end.clamp(0.0, 1.0)) * total_chars as f32).ceil() as usize; if c_start >= c_end || c_start >= total_chars { - return (dims, [0, 0], vec![0u8; (w as usize) * (h as usize) * 4]); + return empty(); } + let Some(font) = text_engine::Font::find(params.font_family, params.font_style) else { + return empty(); + }; + let face = font.face(); // Build per-character CLS X/Y offsets (Fusion prop 1350 = X, 1351 = Y in normalized width units). let mut cls_dx = vec![0.0_f32; total_chars]; @@ -717,38 +726,13 @@ pub fn rasterize_text_plus(dims: [u32; 2], params: &TextPlusParams<'_>, outline_ // (calibrated across Open Sans, Liberation Sans, DejaVu Sans, and AT Name Sans Text // on 16:9, square, and vertical frames). let line_box_px = params.size_norm * w as f32 * 0.8; - let weight = style_to_weight(params.font_style); - let italic = params.font_style.to_ascii_lowercase().contains("italic") - || params.font_style.to_ascii_lowercase().contains("oblique"); + let (ascent_em, descent_em) = text_engine::vertical_metrics(&face); + let font_px = (line_box_px / (ascent_em + descent_em).max(0.5)).clamp(6.0, 1024.0); + let descent = descent_em * font_px; - let families: Arc<[text::Family]> = if params.font_family.is_empty() { - Arc::from([text::Family::Sans]) - } else { - Arc::from([ - text::Family::Named(Arc::from(params.font_family)), - text::Family::Sans, - ]) - }; - let probe_font = text::Font { - families: families.clone(), - size: 100.0, - weight, - italic, - }; - let probe_metrics = text::FontHandle::new(&probe_font).metrics(); - let design_span = ((probe_metrics.ascent + probe_metrics.descent) / 100.0).max(0.5); - let font_px = (line_box_px / design_span).clamp(6.0, 1024.0); - let font = text::Font { - families, - size: font_px, - weight, - italic, - }; - let handle = text::FontHandle::new(&font); - let metrics = handle.metrics(); - - // Extra tracking per glyph: Fusion `CharacterSpacing = 1.0` means 0 extra; >1.0 expands cleanly. - let extra_track = (params.tracking - 1.0) * font_px * 1.15; + // Fusion `CharacterSpacing = 1.0` adds nothing; each +1.0 adds `Size * W` between characters, + // independent of the font (probed on Fusion 21.1 with Liberation Sans, 8 gaps, 1.3 and 2.0). + let extra_track = (params.tracking - 1.0) * params.size_norm * w as f32; let lines: Vec<&str> = params.text.split('\n').collect(); let line_height = (line_box_px * params.line_spacing.max(0.05)).max(1.0); @@ -759,66 +743,49 @@ pub fn rasterize_text_plus(dims: [u32; 2], params: &TextPlusParams<'_>, outline_ // VerticalTopCenterBottom: -1=Top (baseline_0 = cy + font_px - descent), 0=Center, +1=Bottom (last baseline = cy). let v_frac = params.v_tcb.clamp(-1.0, 1.0) * 0.5 + 0.5; - let top_anchor = (font_px - metrics.descent).max(0.0); + let top_anchor = (font_px - descent).max(0.0); let block_h = (lines.len().saturating_sub(1) as f32) * line_height + top_anchor; let baseline_0 = cy + top_anchor - v_frac * block_h; let h_frac = params.h_lcr.clamp(-1.0, 1.0) * 0.5 + 0.5; - let fc = params.fill_rgba; - let shear_x = params.shear_x; - // Pass 1: rasterize all visible glyphs & collect exact bounds to expand DoD if anything overflows canvas! - struct PlacedGlyph { - ox: i32, - oy: i32, - baseline_y: f32, - w: i32, - h: i32, - data: Vec, - } + let outlined = params.outline_width_px > 1e-3 && params.outline_rgba[3] > 0.0; + + // Pass 1: vector-rasterize every visible glyph and collect exact bounds to expand the DoD. let mut placed = Vec::new(); - let mut min_x = 0i32; - let mut min_y = 0i32; - let mut max_x = w as i32; - let mut max_y = h as i32; + let (mut min_x, mut min_y, mut max_x, mut max_y) = (0i32, 0i32, w as i32, h as i32); + let mut grow = |c: &text_engine::Coverage, pad: i32| { + min_x = min_x.min(c.left - pad); + min_y = min_y.min(c.top - pad); + max_x = max_x.max(c.left + c.width as i32 + pad); + max_y = max_y.max(c.top + c.height as i32 + pad); + }; let mut char_cursor = 0usize; for (li, line_str) in lines.iter().enumerate() { - let mut glyphs = Vec::new(); - let mut pen_x = 0.0_f32; - for ch in line_str.chars() { - let idx = char_cursor; - char_cursor += 1; - let adv = handle.advance(ch); - if idx >= c_start && idx < c_end { - if let Some(gid) = handle.glyph(ch) { - glyphs.push((gid, pen_x, idx)); - } - } - pen_x += adv + extra_track; - } - char_cursor += 1; // account for '\n' separator - let line_w = (pen_x - extra_track).max(0.0); - let start_x = cx - line_w * h_frac; + let shaped = text_engine::shape_line(&face, line_str, font_px, extra_track); + let start_x = cx - shaped.width * h_frac; let baseline_y = baseline_0 + (li as f32) * line_height; - - for (gid, gx, idx) in glyphs { - let Some(mask) = handle.rasterize(gid, 1.0, [0, 0]) else { continue }; - let cdx = cls_dx[idx] * w as f32; - let cdy = -cls_dy[idx] * w as f32; - let ox = (start_x + gx + cdx).round() as i32 + mask.left; - let g_base_y = baseline_y + cdy; - let oy = g_base_y.round() as i32 - mask.top; - let mw = mask.width as i32; - let mh = mask.height as i32; - let shear_pad = (shear_x.abs() * mh as f32).ceil() as i32; - if mw > 0 && mh > 0 { - min_x = min_x.min(ox - outline_pad - shear_pad); - min_y = min_y.min(oy - outline_pad); - max_x = max_x.max(ox + mw + outline_pad + shear_pad); - max_y = max_y.max(oy + mh + outline_pad); - placed.push(PlacedGlyph { ox, oy, baseline_y: g_base_y, w: mw, h: mh, data: mask.data }); + for g in &shaped.glyphs { + let idx = char_cursor + g.char_index; + if idx < c_start || idx >= c_end { + continue; } + let origin = [ + start_x + g.x + cls_dx[idx] * w as f32, + baseline_y - g.y - cls_dy[idx] * w as f32, + ]; + let path = text_engine::glyph_path(&font, &face, g.id, font_px, origin, -params.shear_x); + let fill = text_engine::fill(&path); + let line = if outlined { text_engine::stroke(&path, params.outline_width_px) } else { None }; + if let Some(c) = &fill { + grow(c, dod_pad); + } + if let Some(c) = &line { + grow(c, dod_pad); + } + placed.push((fill, line)); } + char_cursor += line_str.chars().count() + 1; // + '\n' separator } // Clamp DoD expansion safely to at most +/- 1 canvas width/height so GPU textures stay bounded. @@ -826,51 +793,54 @@ pub fn rasterize_text_plus(dims: [u32; 2], params: &TextPlusParams<'_>, outline_ let origin_y = min_y.max(-(h as i32)); let end_x = max_x.min((w as i32) * 2); let end_y = max_y.min((h as i32) * 2); - let tw = (end_x - origin_x).max(1) as u32; - let th = (end_y - origin_y).max(1) as u32; - let mut out = vec![0u8; (tw as usize) * (th as usize) * 4]; + let tw = (end_x - origin_x).max(1) as usize; + let th = (end_y - origin_y).max(1) as usize; - for g in placed { - for my in 0..g.h { - let py = g.oy + my; - let dy = py - origin_y; - if dy < 0 || dy >= th as i32 { continue; } - let row_shear = if shear_x.abs() > 1e-4 { - (-((g.baseline_y - py as f32) * shear_x)).round() as i32 - } else { - 0 - }; - for mx in 0..g.w { - let dx = g.ox + mx + row_shear - origin_x; - if dx < 0 || dx >= tw as i32 { continue; } - let cov = g.data[(my * g.w + mx) as usize]; - if cov > 0 { - let i = ((dy as usize) * (tw as usize) + (dx as usize)) * 4; - let a = (cov as f32 / 255.0) * fc[3]; - let prev_a = out[i + 3] as f32 / 255.0; - let na = a.max(prev_a); - out[i] = (fc[0] * na * 255.0).clamp(0.0, 255.0) as u8; - out[i + 1] = (fc[1] * na * 255.0).clamp(0.0, 255.0) as u8; - out[i + 2] = (fc[2] * na * 255.0).clamp(0.0, 255.0) as u8; - out[i + 3] = (na * 255.0).clamp(0.0, 255.0) as u8; - } - } + let mut fill_plane = vec![0u8; tw * th]; + let mut line_plane = vec![0.0_f32; if outlined { tw * th } else { 0 }]; + for (fill, line) in &placed { + if let Some(c) = fill { + blit_max(c, [origin_x, origin_y], [tw, th], |i, a| fill_plane[i] = fill_plane[i].max(a)); } + if let Some(c) = line { + blit_max(c, [origin_x, origin_y], [tw, th], |i, a| line_plane[i] = line_plane[i].max(a as f32 / 255.0)); + } + } + + let (fc, oc) = (params.fill_rgba, params.outline_rgba); + let mut out = vec![0u8; tw * th * 4]; + for (i, px) in out.chunks_exact_mut(4).enumerate() { + let fa = fill_plane[i] as f32 / 255.0 * fc[3]; + let oa = if outlined { line_plane[i] * oc[3] } else { 0.0 }; + if fa <= 0.0 && oa <= 0.0 { + continue; + } + let under = 1.0 - fa; + for k in 0..3 { + let v = fc[k] * fa + oc[k] * oa * under; + px[k] = (v * 255.0 + 0.5).clamp(0.0, 255.0) as u8; + } + px[3] = ((fa + oa * under) * 255.0 + 0.5).clamp(0.0, 255.0) as u8; } - ([tw, th], [origin_x, origin_y], out) + ([tw as u32, th as u32], [origin_x, origin_y], out) } -fn style_to_weight(style: &str) -> u16 { - let s = style.to_ascii_lowercase(); - if s.contains("black") || s.contains("heavy") { 900 } - else if s.contains("extrabold") || s.contains("ultrabold") { 800 } - else if s.contains("bold") { 700 } - else if s.contains("semibold") || s.contains("demi") { 600 } - else if s.contains("medium") { 500 } - else if s.contains("light") { 300 } - else if s.contains("thin") || s.contains("hairline") { 100 } - else { 400 } +/// Calls `f(plane_index, coverage)` for every non-zero coverage pixel that lands inside the plane. +fn blit_max(c: &text_engine::Coverage, origin: [i32; 2], plane: [usize; 2], mut f: impl FnMut(usize, u8)) { + for y in 0..c.height as i32 { + let py = c.top + y - origin[1]; + if py < 0 || py >= plane[1] as i32 { + continue; + } + for x in 0..c.width as i32 { + let px = c.left + x - origin[0]; + let a = c.data[(y as u32 * c.width + x as u32) as usize]; + if a > 0 && px >= 0 && px < plane[0] as i32 { + f(py as usize * plane[0] + px as usize, a); + } + } + } } /// Rasterizes a closed Fusion `PolylineMask` into RGBA8 `[w, h]` via `zeno`. @@ -1093,6 +1063,8 @@ mod tests { write_on_end: 1.0, shear_x: 0.0, cls: &[], + outline_rgba: [0.0; 4], + outline_width_px: 0.0, }, 0, ) diff --git a/crates/engine/src/text_engine.rs b/crates/engine/src/text_engine.rs new file mode 100644 index 0000000000000000000000000000000000000000..2d2da3d000d560458024ba7c98187fa994ce7493 --- /dev/null +++ b/crates/engine/src/text_engine.rs @@ -0,0 +1,448 @@ +//! Deterministic vector text for `TextPlus` / `Text3D`: system font discovery (`fontdb`), +//! HarfBuzz-compatible shaping (`rustybuzz`), OpenType outlines and analytic `zeno` fill and +//! stroke. No platform text stack is involved, so glyph coverage depends only on the font file. + +use rustybuzz::ttf_parser::{self, GlyphId, OutlineBuilder, Tag}; +use rustybuzz::{Face, Feature, UnicodeBuffer, Variation}; +use std::collections::HashMap; +use std::sync::{Arc, Mutex, OnceLock}; +use zeno::{Cap, Command, Fill, Join, Mask, Stroke, Vector}; + +/// Tried in order when the requested family is not installed. +const FALLBACK_FAMILIES: [&str; 6] = + ["Helvetica Neue", "Helvetica", "Arial", "Liberation Sans", "Open Sans", "DejaVu Sans"]; + +/// Horizontal lean (`tan 12°`) applied to italic requests that resolve to an upright face. +const SYNTHETIC_ITALIC: f32 = 0.2126; + +/// A resolved font file; `face()` parses it on demand. +pub struct Font { + data: Vec, + index: u32, + weight: u16, + lean: f32, +} + +impl Font { + /// Resolves `family` + `style` (`"Bold"`, `"Extra Bold"`, `"Light Italic"`, ...) against the + /// system fonts, falling back through [`FALLBACK_FAMILIES`] and finally any installed face. + pub fn find(family: &str, style: &str) -> Option> { + static CACHE: OnceLock>>>> = OnceLock::new(); + let mut cache = CACHE.get_or_init(Default::default).lock().unwrap(); + cache + .entry((family.to_owned(), style.to_owned())) + .or_insert_with(|| resolve(database(), family, style).map(Arc::new)) + .clone() + } + + pub fn face(&self) -> Face<'_> { + let mut face = Face::from_slice(&self.data, self.index).expect("font validated on load"); + if face.is_variable() { + face.set_variations(&[Variation { tag: Tag::from_bytes(b"wght"), value: self.weight as f32 }]); + } + face + } +} + +fn database() -> &'static fontdb::Database { + static DB: OnceLock = OnceLock::new(); + DB.get_or_init(|| { + let mut db = fontdb::Database::new(); + db.load_system_fonts(); + db + }) +} + +/// CSS-style weight and italic flag for a Fusion style name. +pub fn parse_style(style: &str) -> (u16, bool) { + let s: String = style.chars().filter(|c| !c.is_whitespace()).collect::().to_ascii_lowercase(); + let weight = if s.contains("black") || s.contains("heavy") { + 900 + } else if s.contains("extrabold") || s.contains("ultrabold") { + 800 + } else if s.contains("semibold") || s.contains("demibold") || s.contains("demi") { + 600 + } else if s.contains("bold") { + 700 + } else if s.contains("medium") { + 500 + } else if s.contains("extralight") || s.contains("ultralight") || s.contains("thin") || s.contains("hairline") { + 200 + } else if s.contains("light") { + 300 + } else { + 400 + }; + (weight, s.contains("italic") || s.contains("oblique")) +} + +fn resolve(db: &fontdb::Database, family: &str, style: &str) -> Option { + let (weight, italic) = parse_style(style); + let wanted: String = style.chars().filter(|c| !c.is_whitespace()).collect::().to_ascii_lowercase(); + let id = std::iter::once(family) + .chain(FALLBACK_FAMILIES) + .find_map(|name| pick(db, name, &wanted, weight, italic)) + .or_else(|| db.query(&fontdb::Query { families: &[fontdb::Family::SansSerif], ..Default::default() })) + .or_else(|| db.faces().map(|f| f.id).next())?; + let info = db.face(id)?; + let data = db.with_face_data(id, |data, _| data.to_vec())?; + let lean = if italic && info.style == fontdb::Style::Normal { SYNTHETIC_ITALIC } else { 0.0 }; + Face::from_slice(&data, info.index)?; + Some(Font { data, index: info.index, weight, lean }) +} + +/// Best face of `family`: an exact subfamily-name match (`"Extra Bold"`), else the CSS-nearest +/// weight/style. Candidates are ordered by PostScript name so ties resolve identically everywhere. +fn pick(db: &fontdb::Database, family: &str, wanted_style: &str, weight: u16, italic: bool) -> Option { + if family.is_empty() { + return None; + } + let mut candidates: Vec<&fontdb::FaceInfo> = db + .faces() + .filter(|f| f.families.iter().any(|(name, _)| name.eq_ignore_ascii_case(family))) + .collect(); + candidates.sort_by(|a, b| (&a.post_script_name, a.index).cmp(&(&b.post_script_name, b.index))); + let first = candidates.first()?; + let exact = candidates.iter().find(|f| { + db.with_face_data(f.id, |data, index| { + let face = ttf_parser::Face::parse(data, index).ok()?; + let names = face.names(); + let name = [17, 2].into_iter().find_map(|id| { + names.into_iter().find(|n| n.name_id == id && n.is_unicode()).and_then(|n| n.to_string()) + })?; + Some(name.chars().filter(|c| !c.is_whitespace()).collect::().eq_ignore_ascii_case(wanted_style)) + }) + .flatten() + .unwrap_or(false) + }); + if let Some(face) = exact { + return Some(face.id); + } + let name = first.families.iter().find(|(n, _)| n.eq_ignore_ascii_case(family))?.0.as_str(); + db.query(&fontdb::Query { + families: &[fontdb::Family::Name(name)], + weight: fontdb::Weight(weight), + style: if italic { fontdb::Style::Italic } else { fontdb::Style::Normal }, + ..Default::default() + }) +} + +/// Ascent and descent (both positive) in em units, from `hhea`. +pub fn vertical_metrics(face: &Face<'_>) -> (f32, f32) { + let upem = face.units_per_em() as f32; + (face.ascender() as f32 / upem, -(face.descender() as f32) / upem) +} + +pub struct ShapedGlyph { + pub id: GlyphId, + /// Pen offset from the line origin in pixels. + pub x: f32, + pub y: f32, + /// Index (in `char`s) of the first source character of the glyph's cluster. + pub char_index: usize, +} + +pub struct ShapedLine { + pub glyphs: Vec, + /// Advance width in pixels, excluding trailing tracking. + pub width: f32, +} + +/// Shapes one line at `px` pixels per em. `tracking_px` is added after every cluster and turns +/// ligatures off, as ligated glyphs cannot be spaced per character. +pub fn shape_line(face: &Face<'_>, text: &str, px: f32, tracking_px: f32) -> ShapedLine { + let scale = px / face.units_per_em() as f32; + let mut buffer = UnicodeBuffer::new(); + buffer.push_str(text); + buffer.guess_segment_properties(); + let features: &[Feature] = if tracking_px != 0.0 { + &[Feature::new(Tag::from_bytes(b"liga"), 0, ..), Feature::new(Tag::from_bytes(b"clig"), 0, ..)] + } else { + &[] + }; + let shaped = rustybuzz::shape(face, features, buffer); + + let char_starts: Vec = text.char_indices().map(|(i, _)| i).collect(); + let mut glyphs = Vec::with_capacity(shaped.len()); + let (mut pen, mut last_cluster) = (0.0_f32, None); + for (info, pos) in shaped.glyph_infos().iter().zip(shaped.glyph_positions()) { + if last_cluster.is_some_and(|c| c != info.cluster) { + pen += tracking_px; + } + last_cluster = Some(info.cluster); + glyphs.push(ShapedGlyph { + id: GlyphId(info.glyph_id as u16), + x: pen + pos.x_offset as f32 * scale, + y: pos.y_offset as f32 * scale, + char_index: char_starts.partition_point(|&s| s < info.cluster as usize), + }); + pen += pos.x_advance as f32 * scale; + } + ShapedLine { glyphs, width: pen } +} + +struct PathBuilder { + commands: Vec, + scale: f32, + origin: [f32; 2], + /// Horizontal shift per pixel above the baseline. + lean: f32, +} + +impl PathBuilder { + fn point(&self, x: f32, y: f32) -> Vector { + let (px, py) = (x * self.scale, y * self.scale); + Vector::new(self.origin[0] + px + py * self.lean, self.origin[1] - py) + } +} + +impl OutlineBuilder for PathBuilder { + fn move_to(&mut self, x: f32, y: f32) { + let p = self.point(x, y); + self.commands.push(Command::MoveTo(p)); + } + fn line_to(&mut self, x: f32, y: f32) { + let p = self.point(x, y); + self.commands.push(Command::LineTo(p)); + } + fn quad_to(&mut self, x1: f32, y1: f32, x: f32, y: f32) { + let (c, p) = (self.point(x1, y1), self.point(x, y)); + self.commands.push(Command::QuadTo(c, p)); + } + fn curve_to(&mut self, x1: f32, y1: f32, x2: f32, y2: f32, x: f32, y: f32) { + let (c1, c2, p) = (self.point(x1, y1), self.point(x2, y2), self.point(x, y)); + self.commands.push(Command::CurveTo(c1, c2, p)); + } + fn close(&mut self) { + self.commands.push(Command::Close); + } +} + +/// The glyph's Bézier contours in pixel space (y down) with the baseline pen at `origin`. +/// `shear` leans the glyph right per pixel of height; the font's own synthetic italic is added. +pub fn glyph_path(font: &Font, face: &Face<'_>, glyph: GlyphId, px: f32, origin: [f32; 2], shear: f32) -> Vec { + let mut builder = PathBuilder { + commands: Vec::new(), + scale: px / face.units_per_em() as f32, + origin, + lean: font.lean + shear, + }; + face.outline_glyph(glyph, &mut builder); + builder.commands +} + +/// 8-bit coverage over a tight pixel rectangle. +pub struct Coverage { + pub left: i32, + pub top: i32, + pub width: u32, + pub height: u32, + pub data: Vec, +} + +fn render(mask: &mut Mask<'_, '_, &[Command]>) -> Option { + let (data, placement) = mask.render(); + (placement.width > 0 && placement.height > 0).then_some(Coverage { + left: placement.left, + top: placement.top, + width: placement.width, + height: placement.height, + data, + }) +} + +/// Analytic non-zero fill of `path`. +pub fn fill(path: &[Command]) -> Option { + render(Mask::new(path).style(Fill::NonZero)) +} + +/// Analytic stroke of `path`, centered on the contour, with round joins and caps. +pub fn stroke(path: &[Command], width: f32) -> Option { + render(Mask::new(path).style(Stroke::new(width).join(Join::Round).cap(Cap::Round))) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::media::{TextPlusParams, rasterize_text_plus}; + use model::ClsEntry; + + fn params<'a>(text: &'a str) -> TextPlusParams<'a> { + TextPlusParams { + text, + font_family: "Helvetica", + font_style: "Regular", + size_norm: 0.08, + tracking: 1.0, + line_spacing: 1.0, + center: [0.5, 0.5], + h_lcr: 0.0, + v_tcb: 0.0, + fill_rgba: [1.0, 1.0, 1.0, 1.0], + write_on_start: 0.0, + write_on_end: 1.0, + shear_x: 0.0, + cls: &[], + outline_rgba: [0.0; 4], + outline_width_px: 0.0, + } + } + + const DIMS: [u32; 2] = [960, 540]; + + fn alpha_bounds(size: [u32; 2], origin: [i32; 2], rgba: &[u8]) -> Option<[i32; 4]> { + let mut b: Option<[i32; 4]> = None; + for (i, px) in rgba.chunks_exact(4).enumerate() { + if px[3] == 0 { + continue; + } + let (x, y) = ((i as u32 % size[0]) as i32 + origin[0], (i as u32 / size[0]) as i32 + origin[1]); + let b = b.get_or_insert([x, y, x, y]); + *b = [b[0].min(x), b[1].min(y), b[2].max(x), b[3].max(y)]; + } + b + } + + fn render_bounds(p: &TextPlusParams<'_>) -> Option<[i32; 4]> { + let (size, origin, rgba) = rasterize_text_plus(DIMS, p, 0); + alpha_bounds(size, origin, &rgba) + } + + #[test] + fn system_fonts_resolve_with_fallback() { + let font = Font::find("Definitely Not Installed 123", "Regular").expect("fallback font"); + let face = font.face(); + assert!(face.glyph_index('A').is_some()); + let (asc, desc) = vertical_metrics(&face); + assert!(asc > 0.5 && desc > 0.0 && asc + desc < 2.0, "{asc} {desc}"); + } + + #[test] + fn style_names_map_to_weight_and_slant() { + assert_eq!(parse_style("Regular"), (400, false)); + assert_eq!(parse_style("Extra Bold"), (800, false)); + assert_eq!(parse_style("Semi Bold Italic"), (600, true)); + assert_eq!(parse_style("Light Oblique"), (300, true)); + assert_eq!(parse_style("Extra Light"), (200, false)); + } + + #[test] + fn bold_face_is_heavier_than_regular() { + let ink = |style: &str| { + let mut p = params("HHHH"); + p.font_style = style; + let (_, _, rgba) = rasterize_text_plus(DIMS, &p, 0); + rgba.chunks_exact(4).map(|px| px[3] as u64).sum::() + }; + assert!(ink("Bold") > ink("Regular")); + } + + #[test] + fn rendering_is_deterministic() { + let mut p = params("Fission 2 \u{2014} fi AV"); + p.outline_rgba = [1.0, 0.0, 0.0, 1.0]; + p.outline_width_px = 6.0; + assert_eq!(rasterize_text_plus(DIMS, &p, 0), rasterize_text_plus(DIMS, &p, 0)); + } + + #[test] + fn kerning_tightens_av_pair() { + let font = Font::find("Helvetica", "Regular").unwrap(); + let face = font.face(); + let solo = |s: &str| shape_line(&face, s, 100.0, 0.0).width; + assert!(solo("AV") < solo("A") + solo("V") - 1.0, "{} vs {}", solo("AV"), solo("A") + solo("V")); + } + + #[test] + fn tracking_adds_space_between_clusters_only() { + let font = Font::find("Helvetica", "Regular").unwrap(); + let face = font.face(); + let plain = shape_line(&face, "HHH", 100.0, 0.0); + let spaced = shape_line(&face, "HHH", 100.0, 10.0); + assert!((spaced.width - plain.width - 20.0).abs() < 1e-3); + assert_eq!(spaced.glyphs.iter().map(|g| g.char_index).collect::>(), [0, 1, 2]); + } + + #[test] + fn outlines_are_true_curves() { + let font = Font::find("Helvetica", "Regular").unwrap(); + let face = font.face(); + let gid = face.glyph_index('O').unwrap(); + let path = glyph_path(&font, &face, gid, 100.0, [0.0, 0.0], 0.0); + assert!(path.iter().any(|c| matches!(c, Command::QuadTo(..) | Command::CurveTo(..)))); + let cov = fill(&path).unwrap(); + assert!((60..=90).contains(&cov.height), "O cap height {}", cov.height); + let ring = stroke(&path, 10.0).unwrap(); + assert!(ring.width >= cov.width + 8, "stroke must extend past the fill"); + assert!(cov.data.iter().any(|&a| a > 0 && a < 255), "edges are antialiased"); + } + + #[test] + fn outline_stroke_grows_the_domain_and_sits_under_the_fill() { + let plain = render_bounds(¶ms("HI")).unwrap(); + let mut p = params("HI"); + p.outline_rgba = [1.0, 0.0, 0.0, 1.0]; + p.outline_width_px = 12.0; + let outlined = render_bounds(&p).unwrap(); + assert!(outlined[0] <= plain[0] - 5 && outlined[2] >= plain[2] + 5, "{outlined:?} vs {plain:?}"); + let (size, origin, rgba) = rasterize_text_plus(DIMS, &p, 0); + let at = |x: i32, y: i32| { + let i = (((y - origin[1]) as u32 * size[0] + (x - origin[0]) as u32) * 4) as usize; + [rgba[i], rgba[i + 1], rgba[i + 2], rgba[i + 3]] + }; + let ring = at(plain[0] - 3, (plain[1] + plain[3]) / 2); + assert!(ring[0] > 200 && ring[1] < 10 && ring[3] > 200, "outline pixel {ring:?}"); + } + + #[test] + fn write_on_reveals_by_character_without_moving_layout() { + let full = render_bounds(¶ms("HHHH")).unwrap(); + let mut p = params("HHHH"); + p.write_on_end = 0.5; + let half = render_bounds(&p).unwrap(); + assert_eq!(half[0], full[0], "the first glyph stays put"); + assert!(half[2] < (full[0] + full[2]) / 2 + 3, "{half:?} vs {full:?}"); + p.write_on_start = 0.5; + p.write_on_end = 1.0; + let tail = render_bounds(&p).unwrap(); + assert_eq!(tail[2], full[2], "the last glyph stays put"); + p.write_on_start = 1.0; + assert!(render_bounds(&p).is_none()); + } + + #[test] + fn cls_offsets_move_only_the_styled_characters() { + let base = render_bounds(¶ms("HH")).unwrap(); + let cls = [ClsEntry { prop_id: 1351, start: 1, end: 1, value: 0.05 }]; + let mut p = params("HH"); + p.cls = &cls; + let raised = render_bounds(&p).unwrap(); + assert_eq!(raised[0], base[0]); + assert_eq!(raised[2], base[2]); + assert!(raised[1] < base[1] - 30, "{raised:?} vs {base:?}"); + } + + #[test] + fn character_spacing_widens_lines() { + let width = |t: f32| { + let mut p = params("HHHH"); + p.tracking = t; + let b = render_bounds(&p).unwrap(); + b[2] - b[0] + }; + assert!(width(1.5) > width(1.0) + 20); + } + + #[test] + fn justification_anchors_lines() { + let at = |h: f32| { + let mut p = params("HHHH"); + p.h_lcr = h; + render_bounds(&p).unwrap() + }; + let (left, centre, right) = (at(-1.0), at(0.0), at(1.0)); + assert!((left[0] - 480).abs() <= 6, "{left:?}"); + assert!((right[2] - 480).abs() <= 6, "{right:?}"); + assert!(((centre[0] + centre[2]) / 2 - 480).abs() <= 3, "{centre:?}"); + } +}