authoravatarclover caruso<git@paperclover.net>2026-11-30 18:22:51-08:00
committeravatarclover caruso<git@paperclover.net>2026-11-30 19:14:04-08:00
log138aa6b97bbbf1feaf785a127ca34a5e1a487476
tree9815f1cafe8b91ed8a46f56c7a4407045fecb714
parent5c885076bb1b170ed84529096c0fa94fce3c4cef
signature Signed by SSH key SHA256:52mNGHRsVFBDED9IAX5pe+LRWUefqTbxEReunq21QvU

Replace CoreText in TextPlus/Text3D with deterministic pure-Rust vector font engine (#35)

TextPlus (and Text3D plates, which render through it) now use fontdb discovery, rustybuzz shaping, ttf-parser outlines and analytic zeno fill and stroke. The outline is a round-join zeno stroke composed under the fill on the CPU; CharacterSpacing adds (t-1)*Size*W per gap, calibrated against Fusion 21.1. Text3D plates render at 2048x1024. Assisted-by: claude-sonnet-5.5

7 files changed, 628 insertions(+), 164 deletions(-)

Cargo.lock+65-3
......@@ -731,6 +731,15 @@ version = "1.0.0"
731731source = "registry+https://github.com/rust-lang/crates.io-index"
732732checksum = "7f8f80099a98041a3d1622845c271458a2d73e688351bf3cb999266764b81d48"
733733
734[[package]]
735name = "core_maths"
736version = "0.1.1"
737source = "registry+https://github.com/rust-lang/crates.io-index"
738checksum = "77745e017f5edba1a9c1d854f6f3a52dac8a12dd5af5d2f54aecf61e43d80d30"
739dependencies = [
740 "libm",
741]
742
734743[[package]]
735744name = "coreaudio-rs"
736745version = "0.11.3"
......@@ -1003,12 +1012,13 @@ dependencies = [
10031012 "cc",
10041013 "cpal",
10051014 "exr",
1015 "fontdb 0.23.0",
10061016 "image",
10071017 "model",
10081018 "png",
10091019 "pollster",
1020 "rustybuzz",
10101021 "symphonia",
1011 "text",
10121022 "theme",
10131023 "wgpu",
10141024 "zeno",
......@@ -1217,6 +1227,19 @@ dependencies = [
12171227 "roxmltree 0.20.0",
12181228]
12191229
1230[[package]]
1231name = "fontdb"
1232version = "0.23.0"
1233source = "registry+https://github.com/rust-lang/crates.io-index"
1234checksum = "457e789b3d1202543297a350643cf459f836cade38934e7a4cf6a39e7cde2905"
1235dependencies = [
1236 "log",
1237 "memmap2",
1238 "slotmap",
1239 "tinyvec",
1240 "ttf-parser",
1241]
1242
12201243[[package]]
12211244name = "fontdb"
12221245version = "0.24.0"
......@@ -2956,6 +2979,24 @@ version = "1.0.23"
29562979source = "registry+https://github.com/rust-lang/crates.io-index"
29572980checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f"
29582981
2982[[package]]
2983name = "rustybuzz"
2984version = "0.20.1"
2985source = "registry+https://github.com/rust-lang/crates.io-index"
2986checksum = "fd3c7c96f8a08ee34eff8857b11b49b07d71d1c3f4e88f8a88d4c9e9f90b1702"
2987dependencies = [
2988 "bitflags 2.13.2",
2989 "bytemuck",
2990 "core_maths",
2991 "log",
2992 "smallvec",
2993 "ttf-parser",
2994 "unicode-bidi-mirroring",
2995 "unicode-ccc",
2996 "unicode-properties",
2997 "unicode-script",
2998]
2999
29593000[[package]]
29603001name = "same-file"
29613002version = "1.0.6"
......@@ -3954,6 +3995,9 @@ name = "ttf-parser"
39543995version = "0.25.1"
39553996source = "registry+https://github.com/rust-lang/crates.io-index"
39563997checksum = "d2df906b07856748fa3f6e0ad0cbaa047052d4a7dd609e231c4f72cee8c36f31"
3998dependencies = [
3999 "core_maths",
4000]
39574001
39584002[[package]]
39594003name = "typenum"
......@@ -3983,7 +4027,7 @@ dependencies = [
39834027 "block2 0.6.2",
39844028 "draw",
39854029 "edit",
3986 "fontdb",
4030 "fontdb 0.24.0",
39874031 "knife-window-host",
39884032 "libc",
39894033 "nucleo-matcher",
......@@ -4013,6 +4057,18 @@ version = "0.3.18"
40134057source = "registry+https://github.com/rust-lang/crates.io-index"
40144058checksum = "5c1cb5db39152898a79168971543b1cb5020dff7fe43c8dc468b0885f5e29df5"
40154059
4060[[package]]
4061name = "unicode-bidi-mirroring"
4062version = "0.4.0"
4063source = "registry+https://github.com/rust-lang/crates.io-index"
4064checksum = "5dfa6e8c60bb66d49db113e0125ee8711b7647b5579dc7f5f19c42357ed039fe"
4065
4066[[package]]
4067name = "unicode-ccc"
4068version = "0.4.0"
4069source = "registry+https://github.com/rust-lang/crates.io-index"
4070checksum = "ce61d488bcdc9bc8b5d1772c404828b17fc481c0a582b5581e95fb233aef503e"
4071
40164072[[package]]
40174073name = "unicode-general-category"
40184074version = "1.1.0"
......@@ -4040,6 +4096,12 @@ dependencies = [
40404096 "tinyvec",
40414097]
40424098
4099[[package]]
4100name = "unicode-properties"
4101version = "0.1.5"
4102source = "registry+https://github.com/rust-lang/crates.io-index"
4103checksum = "993ad287eb20e8ba755312801cfe1413e0f25d604075863acaddca10b04c1833"
4104
40434105[[package]]
40444106name = "unicode-script"
40454107version = "0.5.9"
......@@ -4072,7 +4134,7 @@ checksum = "977d0a4abdef933f424a99fe09f95576e089b90aebc6f016a3bc813762493e91"
40724134dependencies = [
40734135 "base64",
40744136 "data-url",
4075 "fontdb",
4137 "fontdb 0.24.0",
40764138 "harfrust 0.12.0",
40774139 "imagesize",
40784140 "kurbo",
Cargo.toml+2
......@@ -34,10 +34,12 @@ theme = { path = "../the-knife/knife/theme" }
3434accesskit = "0.25.1"
3535accesskit_winit = { version = "0.34", default-features = false, features = ["rwh_06"] }
3636bytemuck = { version = "1.25", features = ["derive"] }
37fontdb = { version = "0.23", default-features = false, features = ["std", "fs", "memmap"] }
3738image = { version = "0.25", default-features = false, features = ["jpeg", "png", "exr", "tiff", "webp"] }
3839mlua = { version = "0.10", features = ["lua54", "vendored"] }
3940png = "0.18"
4041pollster = "0.4"
42rustybuzz = "0.20"
4143wgpu = "30.0.1"
4244winit = "0.30.13"
4345zeno = "0.3.3"
crates/engine/Cargo.toml+2-1
......@@ -12,12 +12,13 @@ path = "src/bin/render_check.rs"
1212bytemuck.workspace = true
1313cpal = "0.15"
1414exr = "1.74"
15fontdb.workspace = true
1516image.workspace = true
1617model.workspace = true
1718png.workspace = true
1819pollster.workspace = true
20rustybuzz.workspace = true
1921symphonia = { version = "0.5", default-features = false, features = ["wav", "mp3", "flac", "ogg", "aac", "isomp4", "pcm"] }
20text.workspace = true
2122theme.workspace = true
2223wgpu.workspace = true
2324zeno.workspace = true
crates/engine/src/eval/text_3d.rs+9-31
......@@ -111,7 +111,7 @@ impl Engine {
111111 time: f64,
112112 frame_i: i64,
113113 comp_dims: [u32; 2],
114 enc: &mut wgpu::CommandEncoder,
114 _enc: &mut wgpu::CommandEncoder,
115115 stats: &mut EvalStats,
116116 ) -> CachedTexture {
117117 let w = comp.eval_number(node, "Width", time, comp.width as f64, &self.expr) as u32;
......@@ -190,8 +190,8 @@ impl Engine {
190190 stats.nodes_evaluated += 1;
191191
192192 let size_px = size_norm * size[0] as f32;
193 let outline_radius = if is_text_outline && outline_thickness > 1e-4 {
194 (outline_thickness * size_px * 0.50).clamp(1.0, 28.0)
193 let outline_width_px = if is_text_outline && outline_thickness > 1e-4 {
194 (outline_thickness * size_px).clamp(2.0, 56.0)
195195 } else {
196196 0.0
197197 };
......@@ -203,7 +203,6 @@ impl Engine {
203203 } else {
204204 0
205205 };
206 let dod_pad = (outline_radius.ceil() as i32 + 2).max(border_pad_px);
207206 let (tex_size, origin, mut pixels) = rasterize_text_plus(
208207 size,
209208 &TextPlusParams {
......@@ -221,8 +220,10 @@ impl Engine {
221220 write_on_end: write_end,
222221 shear_x,
223222 cls: cls_entries,
223 outline_rgba: outline_rgba.map(|c| c * elem2_opacity),
224 outline_width_px,
224225 },
225 dod_pad,
226 border_pad_px,
226227 );
227228
228229 // Fusion TextPlus ElementShape = 2 (BorderFill): draw filled (optionally rounded) box(es)
......@@ -433,37 +434,14 @@ impl Engine {
433434 }
434435 }
435436
436 let fill_tex = create_texture_dod(
437 &self.device,
438 tex_size,
439 origin,
440 size,
441 if outline_radius > 0.0 { 0 } else { key },
442 );
437 let final_tex = create_texture_dod(&self.device, tex_size, origin, size, key);
443438 self.queue.write_texture(
444 fill_tex.texture.as_image_copy(),
439 final_tex.texture.as_image_copy(),
445440 &pixels,
446441 wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(tex_size[0] * 4), rows_per_image: Some(tex_size[1]) },
447442 wgpu::Extent3d { width: tex_size[0], height: tex_size[1], depth_or_array_layers: 1 },
448443 );
449444
450 let final_tex = if outline_radius > 0.0 {
451 // Single-pass circular Euclidean L2 outline + fill-over-outline composite across DoD!
452 let dst = create_texture_dod(&self.device, tex_size, origin, size, key);
453 let mut u = UniformParams::default();
454 u.p[0] = [
455 outline_rgba[0] * elem2_opacity,
456 outline_rgba[1] * elem2_opacity,
457 outline_rgba[2] * elem2_opacity,
458 outline_rgba[3] * elem2_opacity,
459 ];
460 u.p[1] = [outline_radius, 0.0, 0.0, 0.0];
461 self.dispatch_op(enc, ShaderOp::TextOutline, &fill_tex.view, &self.dummy.view, &self.dummy.view, &dst, &u);
462 dst
463 } else {
464 fill_tex
465 };
466
467445 self.cache.insert(key, final_tex.clone(), node.id, frame_i);
468446 final_tex
469447 }
......@@ -545,7 +523,7 @@ impl Engine {
545523 for ms in &mesh_specs {
546524 let tex = if let Some(t3d) = &ms.text3d {
547525 let tnode = comp.node(t3d.node_id);
548 Some(self.eval_text_plus(comp, tnode, time, frame_i, [1024, 512], enc, stats))
526 Some(self.eval_text_plus(comp, tnode, time, frame_i, [2048, 1024], enc, stats))
549527 } else {
550528 ms.material_node.map(|mid| self.eval_node(comp, mid, time, enc, visiting, stats))
551529 };
crates/engine/src/lib.rs+1
......@@ -10,6 +10,7 @@ pub mod particles;
1010pub mod profile;
1111pub mod ram_cache;
1212pub mod scene3d;
13pub mod text_engine;
1314
1415pub use audio::{AudioPlayer, AudioTrack};
1516pub use cache::{
crates/engine/src/media.rs+101-129
......@@ -1,6 +1,7 @@
11//! Media loading (PNG/JPG/EXR/TIFF stills & numbered image sequences) and
2//! CPU rasterizers (`TextPlus` via `knife/text` CoreText, `PolylineMask` via `zeno`).
2//! CPU rasterizers (`TextPlus` via `text_engine`, `PolylineMask` via `zeno`).
33
4use crate::text_engine;
45use model::{ClipSpec, ClsEntry, PolyPoint};
56use std::collections::HashMap;
67use std::path::{Path, PathBuf};
......@@ -663,7 +664,7 @@ pub fn resolve_clip_path(clip: &ClipSpec, frame: i64) -> Option<PathBuf> {
663664 }
664665}
665666
666/// Parameters for rasterizing a Fusion `TextPlus` node using `knife/text` (CoreText).
667/// Parameters for rasterizing a Fusion `TextPlus` node with [`crate::text_engine`].
667668pub struct TextPlusParams<'a> {
668669 pub text: &'a str,
669670 pub font_family: &'a str,
......@@ -679,15 +680,19 @@ pub struct TextPlusParams<'a> {
679680 pub write_on_end: f32,
680681 pub shear_x: f32, // Fusion CharacterShearX
681682 pub cls: &'a [ClsEntry], // Optional StyledTextCLS per-character overrides
683 pub outline_rgba: [f32; 4], // Fusion Element 2 color, already scaled by Opacity2
684 pub outline_width_px: f32, // Fusion Thickness2 as a full stroke width; 0 disables the outline
682685}
683686
684/// Rasterizes a `TextPlus` fill layer into premultiplied RGBA8 with automatic Domain-of-Definition
685/// (DoD) expansion so off-screen glyphs (e.g. text shifted into frame by a downstream `Transform`)
686/// are never clipped. Returns `(tex_size, dod_origin_px, rgba)`.
687pub fn rasterize_text_plus(dims: [u32; 2], params: &TextPlusParams<'_>, outline_pad: i32) -> ([u32; 2], [i32; 2], Vec<u8>) {
687/// Rasterizes a `TextPlus` layer (outline under fill) into premultiplied RGBA8 with automatic
688/// Domain-of-Definition (DoD) expansion so off-screen glyphs (e.g. text shifted into frame by a
689/// downstream `Transform`) are never clipped; `dod_pad` adds margin for decoration drawn from
690/// the result. Returns `(tex_size, dod_origin_px, rgba)`.
691pub fn rasterize_text_plus(dims: [u32; 2], params: &TextPlusParams<'_>, dod_pad: i32) -> ([u32; 2], [i32; 2], Vec<u8>) {
688692 let [w, h] = dims;
693 let empty = || (dims, [0, 0], vec![0u8; (w as usize) * (h as usize) * 4]);
689694 if params.text.is_empty() || params.size_norm <= 1e-4 {
690 return (dims, [0, 0], vec![0u8; (w as usize) * (h as usize) * 4]);
695 return empty();
691696 }
692697
693698 // 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_
695700 let c_start = ((params.write_on_start.clamp(0.0, 1.0)) * total_chars as f32).floor() as usize;
696701 let c_end = ((params.write_on_end.clamp(0.0, 1.0)) * total_chars as f32).ceil() as usize;
697702 if c_start >= c_end || c_start >= total_chars {
698 return (dims, [0, 0], vec![0u8; (w as usize) * (h as usize) * 4]);
703 return empty();
699704 }
705 let Some(font) = text_engine::Font::find(params.font_family, params.font_style) else {
706 return empty();
707 };
708 let face = font.face();
700709
701710 // Build per-character CLS X/Y offsets (Fusion prop 1350 = X, 1351 = Y in normalized width units).
702711 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_
717726 // (calibrated across Open Sans, Liberation Sans, DejaVu Sans, and AT Name Sans Text
718727 // on 16:9, square, and vertical frames).
719728 let line_box_px = params.size_norm * w as f32 * 0.8;
720 let weight = style_to_weight(params.font_style);
721 let italic = params.font_style.to_ascii_lowercase().contains("italic")
722 || params.font_style.to_ascii_lowercase().contains("oblique");
723
724 let families: Arc<[text::Family]> = if params.font_family.is_empty() {
725 Arc::from([text::Family::Sans])
726 } else {
727 Arc::from([
728 text::Family::Named(Arc::from(params.font_family)),
729 text::Family::Sans,
730 ])
731 };
732 let probe_font = text::Font {
733 families: families.clone(),
734 size: 100.0,
735 weight,
736 italic,
737 };
738 let probe_metrics = text::FontHandle::new(&probe_font).metrics();
739 let design_span = ((probe_metrics.ascent + probe_metrics.descent) / 100.0).max(0.5);
740 let font_px = (line_box_px / design_span).clamp(6.0, 1024.0);
741 let font = text::Font {
742 families,
743 size: font_px,
744 weight,
745 italic,
746 };
747 let handle = text::FontHandle::new(&font);
748 let metrics = handle.metrics();
729 let (ascent_em, descent_em) = text_engine::vertical_metrics(&face);
730 let font_px = (line_box_px / (ascent_em + descent_em).max(0.5)).clamp(6.0, 1024.0);
731 let descent = descent_em * font_px;
749732
750 // Extra tracking per glyph: Fusion `CharacterSpacing = 1.0` means 0 extra; >1.0 expands cleanly.
751 let extra_track = (params.tracking - 1.0) * font_px * 1.15;
733 // Fusion `CharacterSpacing = 1.0` adds nothing; each +1.0 adds `Size * W` between characters,
734 // independent of the font (probed on Fusion 21.1 with Liberation Sans, 8 gaps, 1.3 and 2.0).
735 let extra_track = (params.tracking - 1.0) * params.size_norm * w as f32;
752736
753737 let lines: Vec<&str> = params.text.split('\n').collect();
754738 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_
759743
760744 // VerticalTopCenterBottom: -1=Top (baseline_0 = cy + font_px - descent), 0=Center, +1=Bottom (last baseline = cy).
761745 let v_frac = params.v_tcb.clamp(-1.0, 1.0) * 0.5 + 0.5;
762 let top_anchor = (font_px - metrics.descent).max(0.0);
746 let top_anchor = (font_px - descent).max(0.0);
763747 let block_h = (lines.len().saturating_sub(1) as f32) * line_height + top_anchor;
764748 let baseline_0 = cy + top_anchor - v_frac * block_h;
765749 let h_frac = params.h_lcr.clamp(-1.0, 1.0) * 0.5 + 0.5;
766 let fc = params.fill_rgba;
767 let shear_x = params.shear_x;
768
769 // Pass 1: rasterize all visible glyphs & collect exact bounds to expand DoD if anything overflows canvas!
770 struct PlacedGlyph {
771 ox: i32,
772 oy: i32,
773 baseline_y: f32,
774 w: i32,
775 h: i32,
776 data: Vec<u8>,
777 }
750
751 let outlined = params.outline_width_px > 1e-3 && params.outline_rgba[3] > 0.0;
752
753 // Pass 1: vector-rasterize every visible glyph and collect exact bounds to expand the DoD.
778754 let mut placed = Vec::new();
779 let mut min_x = 0i32;
780 let mut min_y = 0i32;
781 let mut max_x = w as i32;
782 let mut max_y = h as i32;
755 let (mut min_x, mut min_y, mut max_x, mut max_y) = (0i32, 0i32, w as i32, h as i32);
756 let mut grow = |c: &text_engine::Coverage, pad: i32| {
757 min_x = min_x.min(c.left - pad);
758 min_y = min_y.min(c.top - pad);
759 max_x = max_x.max(c.left + c.width as i32 + pad);
760 max_y = max_y.max(c.top + c.height as i32 + pad);
761 };
783762
784763 let mut char_cursor = 0usize;
785764 for (li, line_str) in lines.iter().enumerate() {
786 let mut glyphs = Vec::new();
787 let mut pen_x = 0.0_f32;
788 for ch in line_str.chars() {
789 let idx = char_cursor;
790 char_cursor += 1;
791 let adv = handle.advance(ch);
792 if idx >= c_start && idx < c_end {
793 if let Some(gid) = handle.glyph(ch) {
794 glyphs.push((gid, pen_x, idx));
795 }
796 }
797 pen_x += adv + extra_track;
798 }
799 char_cursor += 1; // account for '\n' separator
800 let line_w = (pen_x - extra_track).max(0.0);
801 let start_x = cx - line_w * h_frac;
765 let shaped = text_engine::shape_line(&face, line_str, font_px, extra_track);
766 let start_x = cx - shaped.width * h_frac;
802767 let baseline_y = baseline_0 + (li as f32) * line_height;
803
804 for (gid, gx, idx) in glyphs {
805 let Some(mask) = handle.rasterize(gid, 1.0, [0, 0]) else { continue };
806 let cdx = cls_dx[idx] * w as f32;
807 let cdy = -cls_dy[idx] * w as f32;
808 let ox = (start_x + gx + cdx).round() as i32 + mask.left;
809 let g_base_y = baseline_y + cdy;
810 let oy = g_base_y.round() as i32 - mask.top;
811 let mw = mask.width as i32;
812 let mh = mask.height as i32;
813 let shear_pad = (shear_x.abs() * mh as f32).ceil() as i32;
814 if mw > 0 && mh > 0 {
815 min_x = min_x.min(ox - outline_pad - shear_pad);
816 min_y = min_y.min(oy - outline_pad);
817 max_x = max_x.max(ox + mw + outline_pad + shear_pad);
818 max_y = max_y.max(oy + mh + outline_pad);
819 placed.push(PlacedGlyph { ox, oy, baseline_y: g_base_y, w: mw, h: mh, data: mask.data });
768 for g in &shaped.glyphs {
769 let idx = char_cursor + g.char_index;
770 if idx < c_start || idx >= c_end {
771 continue;
820772 }
773 let origin = [
774 start_x + g.x + cls_dx[idx] * w as f32,
775 baseline_y - g.y - cls_dy[idx] * w as f32,
776 ];
777 let path = text_engine::glyph_path(&font, &face, g.id, font_px, origin, -params.shear_x);
778 let fill = text_engine::fill(&path);
779 let line = if outlined { text_engine::stroke(&path, params.outline_width_px) } else { None };
780 if let Some(c) = &fill {
781 grow(c, dod_pad);
782 }
783 if let Some(c) = &line {
784 grow(c, dod_pad);
785 }
786 placed.push((fill, line));
821787 }
788 char_cursor += line_str.chars().count() + 1; // + '\n' separator
822789 }
823790
824791 // 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_
826793 let origin_y = min_y.max(-(h as i32));
827794 let end_x = max_x.min((w as i32) * 2);
828795 let end_y = max_y.min((h as i32) * 2);
829 let tw = (end_x - origin_x).max(1) as u32;
830 let th = (end_y - origin_y).max(1) as u32;
831 let mut out = vec![0u8; (tw as usize) * (th as usize) * 4];
832
833 for g in placed {
834 for my in 0..g.h {
835 let py = g.oy + my;
836 let dy = py - origin_y;
837 if dy < 0 || dy >= th as i32 { continue; }
838 let row_shear = if shear_x.abs() > 1e-4 {
839 (-((g.baseline_y - py as f32) * shear_x)).round() as i32
840 } else {
841 0
842 };
843 for mx in 0..g.w {
844 let dx = g.ox + mx + row_shear - origin_x;
845 if dx < 0 || dx >= tw as i32 { continue; }
846 let cov = g.data[(my * g.w + mx) as usize];
847 if cov > 0 {
848 let i = ((dy as usize) * (tw as usize) + (dx as usize)) * 4;
849 let a = (cov as f32 / 255.0) * fc[3];
850 let prev_a = out[i + 3] as f32 / 255.0;
851 let na = a.max(prev_a);
852 out[i] = (fc[0] * na * 255.0).clamp(0.0, 255.0) as u8;
853 out[i + 1] = (fc[1] * na * 255.0).clamp(0.0, 255.0) as u8;
854 out[i + 2] = (fc[2] * na * 255.0).clamp(0.0, 255.0) as u8;
855 out[i + 3] = (na * 255.0).clamp(0.0, 255.0) as u8;
856 }
857 }
796 let tw = (end_x - origin_x).max(1) as usize;
797 let th = (end_y - origin_y).max(1) as usize;
798
799 let mut fill_plane = vec![0u8; tw * th];
800 let mut line_plane = vec![0.0_f32; if outlined { tw * th } else { 0 }];
801 for (fill, line) in &placed {
802 if let Some(c) = fill {
803 blit_max(c, [origin_x, origin_y], [tw, th], |i, a| fill_plane[i] = fill_plane[i].max(a));
804 }
805 if let Some(c) = line {
806 blit_max(c, [origin_x, origin_y], [tw, th], |i, a| line_plane[i] = line_plane[i].max(a as f32 / 255.0));
858807 }
859808 }
860809
861 ([tw, th], [origin_x, origin_y], out)
810 let (fc, oc) = (params.fill_rgba, params.outline_rgba);
811 let mut out = vec![0u8; tw * th * 4];
812 for (i, px) in out.chunks_exact_mut(4).enumerate() {
813 let fa = fill_plane[i] as f32 / 255.0 * fc[3];
814 let oa = if outlined { line_plane[i] * oc[3] } else { 0.0 };
815 if fa <= 0.0 && oa <= 0.0 {
816 continue;
817 }
818 let under = 1.0 - fa;
819 for k in 0..3 {
820 let v = fc[k] * fa + oc[k] * oa * under;
821 px[k] = (v * 255.0 + 0.5).clamp(0.0, 255.0) as u8;
822 }
823 px[3] = ((fa + oa * under) * 255.0 + 0.5).clamp(0.0, 255.0) as u8;
824 }
825
826 ([tw as u32, th as u32], [origin_x, origin_y], out)
862827}
863828
864fn style_to_weight(style: &str) -> u16 {
865 let s = style.to_ascii_lowercase();
866 if s.contains("black") || s.contains("heavy") { 900 }
867 else if s.contains("extrabold") || s.contains("ultrabold") { 800 }
868 else if s.contains("bold") { 700 }
869 else if s.contains("semibold") || s.contains("demi") { 600 }
870 else if s.contains("medium") { 500 }
871 else if s.contains("light") { 300 }
872 else if s.contains("thin") || s.contains("hairline") { 100 }
873 else { 400 }
829/// Calls `f(plane_index, coverage)` for every non-zero coverage pixel that lands inside the plane.
830fn blit_max(c: &text_engine::Coverage, origin: [i32; 2], plane: [usize; 2], mut f: impl FnMut(usize, u8)) {
831 for y in 0..c.height as i32 {
832 let py = c.top + y - origin[1];
833 if py < 0 || py >= plane[1] as i32 {
834 continue;
835 }
836 for x in 0..c.width as i32 {
837 let px = c.left + x - origin[0];
838 let a = c.data[(y as u32 * c.width + x as u32) as usize];
839 if a > 0 && px >= 0 && px < plane[0] as i32 {
840 f(py as usize * plane[0] + px as usize, a);
841 }
842 }
843 }
874844}
875845
876846/// Rasterizes a closed Fusion `PolylineMask` into RGBA8 `[w, h]` via `zeno`.
......@@ -1093,6 +1063,8 @@ mod tests {
10931063 write_on_end: 1.0,
10941064 shear_x: 0.0,
10951065 cls: &[],
1066 outline_rgba: [0.0; 4],
1067 outline_width_px: 0.0,
10961068 },
10971069 0,
10981070 )
crates/engine/src/text_engine.rs created+448
......@@ -0,0 +1,448 @@
1//! Deterministic vector text for `TextPlus` / `Text3D`: system font discovery (`fontdb`),
2//! HarfBuzz-compatible shaping (`rustybuzz`), OpenType outlines and analytic `zeno` fill and
3//! stroke. No platform text stack is involved, so glyph coverage depends only on the font file.
4
5use rustybuzz::ttf_parser::{self, GlyphId, OutlineBuilder, Tag};
6use rustybuzz::{Face, Feature, UnicodeBuffer, Variation};
7use std::collections::HashMap;
8use std::sync::{Arc, Mutex, OnceLock};
9use zeno::{Cap, Command, Fill, Join, Mask, Stroke, Vector};
10
11/// Tried in order when the requested family is not installed.
12const FALLBACK_FAMILIES: [&str; 6] =
13 ["Helvetica Neue", "Helvetica", "Arial", "Liberation Sans", "Open Sans", "DejaVu Sans"];
14
15/// Horizontal lean (`tan 12°`) applied to italic requests that resolve to an upright face.
16const SYNTHETIC_ITALIC: f32 = 0.2126;
17
18/// A resolved font file; `face()` parses it on demand.
19pub struct Font {
20 data: Vec<u8>,
21 index: u32,
22 weight: u16,
23 lean: f32,
24}
25
26impl Font {
27 /// Resolves `family` + `style` (`"Bold"`, `"Extra Bold"`, `"Light Italic"`, ...) against the
28 /// system fonts, falling back through [`FALLBACK_FAMILIES`] and finally any installed face.
29 pub fn find(family: &str, style: &str) -> Option<Arc<Font>> {
30 static CACHE: OnceLock<Mutex<HashMap<(String, String), Option<Arc<Font>>>>> = OnceLock::new();
31 let mut cache = CACHE.get_or_init(Default::default).lock().unwrap();
32 cache
33 .entry((family.to_owned(), style.to_owned()))
34 .or_insert_with(|| resolve(database(), family, style).map(Arc::new))
35 .clone()
36 }
37
38 pub fn face(&self) -> Face<'_> {
39 let mut face = Face::from_slice(&self.data, self.index).expect("font validated on load");
40 if face.is_variable() {
41 face.set_variations(&[Variation { tag: Tag::from_bytes(b"wght"), value: self.weight as f32 }]);
42 }
43 face
44 }
45}
46
47fn database() -> &'static fontdb::Database {
48 static DB: OnceLock<fontdb::Database> = OnceLock::new();
49 DB.get_or_init(|| {
50 let mut db = fontdb::Database::new();
51 db.load_system_fonts();
52 db
53 })
54}
55
56/// CSS-style weight and italic flag for a Fusion style name.
57pub fn parse_style(style: &str) -> (u16, bool) {
58 let s: String = style.chars().filter(|c| !c.is_whitespace()).collect::<String>().to_ascii_lowercase();
59 let weight = if s.contains("black") || s.contains("heavy") {
60 900
61 } else if s.contains("extrabold") || s.contains("ultrabold") {
62 800
63 } else if s.contains("semibold") || s.contains("demibold") || s.contains("demi") {
64 600
65 } else if s.contains("bold") {
66 700
67 } else if s.contains("medium") {
68 500
69 } else if s.contains("extralight") || s.contains("ultralight") || s.contains("thin") || s.contains("hairline") {
70 200
71 } else if s.contains("light") {
72 300
73 } else {
74 400
75 };
76 (weight, s.contains("italic") || s.contains("oblique"))
77}
78
79fn resolve(db: &fontdb::Database, family: &str, style: &str) -> Option<Font> {
80 let (weight, italic) = parse_style(style);
81 let wanted: String = style.chars().filter(|c| !c.is_whitespace()).collect::<String>().to_ascii_lowercase();
82 let id = std::iter::once(family)
83 .chain(FALLBACK_FAMILIES)
84 .find_map(|name| pick(db, name, &wanted, weight, italic))
85 .or_else(|| db.query(&fontdb::Query { families: &[fontdb::Family::SansSerif], ..Default::default() }))
86 .or_else(|| db.faces().map(|f| f.id).next())?;
87 let info = db.face(id)?;
88 let data = db.with_face_data(id, |data, _| data.to_vec())?;
89 let lean = if italic && info.style == fontdb::Style::Normal { SYNTHETIC_ITALIC } else { 0.0 };
90 Face::from_slice(&data, info.index)?;
91 Some(Font { data, index: info.index, weight, lean })
92}
93
94/// Best face of `family`: an exact subfamily-name match (`"Extra Bold"`), else the CSS-nearest
95/// weight/style. Candidates are ordered by PostScript name so ties resolve identically everywhere.
96fn pick(db: &fontdb::Database, family: &str, wanted_style: &str, weight: u16, italic: bool) -> Option<fontdb::ID> {
97 if family.is_empty() {
98 return None;
99 }
100 let mut candidates: Vec<&fontdb::FaceInfo> = db
101 .faces()
102 .filter(|f| f.families.iter().any(|(name, _)| name.eq_ignore_ascii_case(family)))
103 .collect();
104 candidates.sort_by(|a, b| (&a.post_script_name, a.index).cmp(&(&b.post_script_name, b.index)));
105 let first = candidates.first()?;
106 let exact = candidates.iter().find(|f| {
107 db.with_face_data(f.id, |data, index| {
108 let face = ttf_parser::Face::parse(data, index).ok()?;
109 let names = face.names();
110 let name = [17, 2].into_iter().find_map(|id| {
111 names.into_iter().find(|n| n.name_id == id && n.is_unicode()).and_then(|n| n.to_string())
112 })?;
113 Some(name.chars().filter(|c| !c.is_whitespace()).collect::<String>().eq_ignore_ascii_case(wanted_style))
114 })
115 .flatten()
116 .unwrap_or(false)
117 });
118 if let Some(face) = exact {
119 return Some(face.id);
120 }
121 let name = first.families.iter().find(|(n, _)| n.eq_ignore_ascii_case(family))?.0.as_str();
122 db.query(&fontdb::Query {
123 families: &[fontdb::Family::Name(name)],
124 weight: fontdb::Weight(weight),
125 style: if italic { fontdb::Style::Italic } else { fontdb::Style::Normal },
126 ..Default::default()
127 })
128}
129
130/// Ascent and descent (both positive) in em units, from `hhea`.
131pub fn vertical_metrics(face: &Face<'_>) -> (f32, f32) {
132 let upem = face.units_per_em() as f32;
133 (face.ascender() as f32 / upem, -(face.descender() as f32) / upem)
134}
135
136pub struct ShapedGlyph {
137 pub id: GlyphId,
138 /// Pen offset from the line origin in pixels.
139 pub x: f32,
140 pub y: f32,
141 /// Index (in `char`s) of the first source character of the glyph's cluster.
142 pub char_index: usize,
143}
144
145pub struct ShapedLine {
146 pub glyphs: Vec<ShapedGlyph>,
147 /// Advance width in pixels, excluding trailing tracking.
148 pub width: f32,
149}
150
151/// Shapes one line at `px` pixels per em. `tracking_px` is added after every cluster and turns
152/// ligatures off, as ligated glyphs cannot be spaced per character.
153pub fn shape_line(face: &Face<'_>, text: &str, px: f32, tracking_px: f32) -> ShapedLine {
154 let scale = px / face.units_per_em() as f32;
155 let mut buffer = UnicodeBuffer::new();
156 buffer.push_str(text);
157 buffer.guess_segment_properties();
158 let features: &[Feature] = if tracking_px != 0.0 {
159 &[Feature::new(Tag::from_bytes(b"liga"), 0, ..), Feature::new(Tag::from_bytes(b"clig"), 0, ..)]
160 } else {
161 &[]
162 };
163 let shaped = rustybuzz::shape(face, features, buffer);
164
165 let char_starts: Vec<usize> = text.char_indices().map(|(i, _)| i).collect();
166 let mut glyphs = Vec::with_capacity(shaped.len());
167 let (mut pen, mut last_cluster) = (0.0_f32, None);
168 for (info, pos) in shaped.glyph_infos().iter().zip(shaped.glyph_positions()) {
169 if last_cluster.is_some_and(|c| c != info.cluster) {
170 pen += tracking_px;
171 }
172 last_cluster = Some(info.cluster);
173 glyphs.push(ShapedGlyph {
174 id: GlyphId(info.glyph_id as u16),
175 x: pen + pos.x_offset as f32 * scale,
176 y: pos.y_offset as f32 * scale,
177 char_index: char_starts.partition_point(|&s| s < info.cluster as usize),
178 });
179 pen += pos.x_advance as f32 * scale;
180 }
181 ShapedLine { glyphs, width: pen }
182}
183
184struct PathBuilder {
185 commands: Vec<Command>,
186 scale: f32,
187 origin: [f32; 2],
188 /// Horizontal shift per pixel above the baseline.
189 lean: f32,
190}
191
192impl PathBuilder {
193 fn point(&self, x: f32, y: f32) -> Vector {
194 let (px, py) = (x * self.scale, y * self.scale);
195 Vector::new(self.origin[0] + px + py * self.lean, self.origin[1] - py)
196 }
197}
198
199impl OutlineBuilder for PathBuilder {
200 fn move_to(&mut self, x: f32, y: f32) {
201 let p = self.point(x, y);
202 self.commands.push(Command::MoveTo(p));
203 }
204 fn line_to(&mut self, x: f32, y: f32) {
205 let p = self.point(x, y);
206 self.commands.push(Command::LineTo(p));
207 }
208 fn quad_to(&mut self, x1: f32, y1: f32, x: f32, y: f32) {
209 let (c, p) = (self.point(x1, y1), self.point(x, y));
210 self.commands.push(Command::QuadTo(c, p));
211 }
212 fn curve_to(&mut self, x1: f32, y1: f32, x2: f32, y2: f32, x: f32, y: f32) {
213 let (c1, c2, p) = (self.point(x1, y1), self.point(x2, y2), self.point(x, y));
214 self.commands.push(Command::CurveTo(c1, c2, p));
215 }
216 fn close(&mut self) {
217 self.commands.push(Command::Close);
218 }
219}
220
221/// The glyph's Bézier contours in pixel space (y down) with the baseline pen at `origin`.
222/// `shear` leans the glyph right per pixel of height; the font's own synthetic italic is added.
223pub fn glyph_path(font: &Font, face: &Face<'_>, glyph: GlyphId, px: f32, origin: [f32; 2], shear: f32) -> Vec<Command> {
224 let mut builder = PathBuilder {
225 commands: Vec::new(),
226 scale: px / face.units_per_em() as f32,
227 origin,
228 lean: font.lean + shear,
229 };
230 face.outline_glyph(glyph, &mut builder);
231 builder.commands
232}
233
234/// 8-bit coverage over a tight pixel rectangle.
235pub struct Coverage {
236 pub left: i32,
237 pub top: i32,
238 pub width: u32,
239 pub height: u32,
240 pub data: Vec<u8>,
241}
242
243fn render(mask: &mut Mask<'_, '_, &[Command]>) -> Option<Coverage> {
244 let (data, placement) = mask.render();
245 (placement.width > 0 && placement.height > 0).then_some(Coverage {
246 left: placement.left,
247 top: placement.top,
248 width: placement.width,
249 height: placement.height,
250 data,
251 })
252}
253
254/// Analytic non-zero fill of `path`.
255pub fn fill(path: &[Command]) -> Option<Coverage> {
256 render(Mask::new(path).style(Fill::NonZero))
257}
258
259/// Analytic stroke of `path`, centered on the contour, with round joins and caps.
260pub fn stroke(path: &[Command], width: f32) -> Option<Coverage> {
261 render(Mask::new(path).style(Stroke::new(width).join(Join::Round).cap(Cap::Round)))
262}
263
264#[cfg(test)]
265mod tests {
266 use super::*;
267 use crate::media::{TextPlusParams, rasterize_text_plus};
268 use model::ClsEntry;
269
270 fn params<'a>(text: &'a str) -> TextPlusParams<'a> {
271 TextPlusParams {
272 text,
273 font_family: "Helvetica",
274 font_style: "Regular",
275 size_norm: 0.08,
276 tracking: 1.0,
277 line_spacing: 1.0,
278 center: [0.5, 0.5],
279 h_lcr: 0.0,
280 v_tcb: 0.0,
281 fill_rgba: [1.0, 1.0, 1.0, 1.0],
282 write_on_start: 0.0,
283 write_on_end: 1.0,
284 shear_x: 0.0,
285 cls: &[],
286 outline_rgba: [0.0; 4],
287 outline_width_px: 0.0,
288 }
289 }
290
291 const DIMS: [u32; 2] = [960, 540];
292
293 fn alpha_bounds(size: [u32; 2], origin: [i32; 2], rgba: &[u8]) -> Option<[i32; 4]> {
294 let mut b: Option<[i32; 4]> = None;
295 for (i, px) in rgba.chunks_exact(4).enumerate() {
296 if px[3] == 0 {
297 continue;
298 }
299 let (x, y) = ((i as u32 % size[0]) as i32 + origin[0], (i as u32 / size[0]) as i32 + origin[1]);
300 let b = b.get_or_insert([x, y, x, y]);
301 *b = [b[0].min(x), b[1].min(y), b[2].max(x), b[3].max(y)];
302 }
303 b
304 }
305
306 fn render_bounds(p: &TextPlusParams<'_>) -> Option<[i32; 4]> {
307 let (size, origin, rgba) = rasterize_text_plus(DIMS, p, 0);
308 alpha_bounds(size, origin, &rgba)
309 }
310
311 #[test]
312 fn system_fonts_resolve_with_fallback() {
313 let font = Font::find("Definitely Not Installed 123", "Regular").expect("fallback font");
314 let face = font.face();
315 assert!(face.glyph_index('A').is_some());
316 let (asc, desc) = vertical_metrics(&face);
317 assert!(asc > 0.5 && desc > 0.0 && asc + desc < 2.0, "{asc} {desc}");
318 }
319
320 #[test]
321 fn style_names_map_to_weight_and_slant() {
322 assert_eq!(parse_style("Regular"), (400, false));
323 assert_eq!(parse_style("Extra Bold"), (800, false));
324 assert_eq!(parse_style("Semi Bold Italic"), (600, true));
325 assert_eq!(parse_style("Light Oblique"), (300, true));
326 assert_eq!(parse_style("Extra Light"), (200, false));
327 }
328
329 #[test]
330 fn bold_face_is_heavier_than_regular() {
331 let ink = |style: &str| {
332 let mut p = params("HHHH");
333 p.font_style = style;
334 let (_, _, rgba) = rasterize_text_plus(DIMS, &p, 0);
335 rgba.chunks_exact(4).map(|px| px[3] as u64).sum::<u64>()
336 };
337 assert!(ink("Bold") > ink("Regular"));
338 }
339
340 #[test]
341 fn rendering_is_deterministic() {
342 let mut p = params("Fission 2 \u{2014} fi AV");
343 p.outline_rgba = [1.0, 0.0, 0.0, 1.0];
344 p.outline_width_px = 6.0;
345 assert_eq!(rasterize_text_plus(DIMS, &p, 0), rasterize_text_plus(DIMS, &p, 0));
346 }
347
348 #[test]
349 fn kerning_tightens_av_pair() {
350 let font = Font::find("Helvetica", "Regular").unwrap();
351 let face = font.face();
352 let solo = |s: &str| shape_line(&face, s, 100.0, 0.0).width;
353 assert!(solo("AV") < solo("A") + solo("V") - 1.0, "{} vs {}", solo("AV"), solo("A") + solo("V"));
354 }
355
356 #[test]
357 fn tracking_adds_space_between_clusters_only() {
358 let font = Font::find("Helvetica", "Regular").unwrap();
359 let face = font.face();
360 let plain = shape_line(&face, "HHH", 100.0, 0.0);
361 let spaced = shape_line(&face, "HHH", 100.0, 10.0);
362 assert!((spaced.width - plain.width - 20.0).abs() < 1e-3);
363 assert_eq!(spaced.glyphs.iter().map(|g| g.char_index).collect::<Vec<_>>(), [0, 1, 2]);
364 }
365
366 #[test]
367 fn outlines_are_true_curves() {
368 let font = Font::find("Helvetica", "Regular").unwrap();
369 let face = font.face();
370 let gid = face.glyph_index('O').unwrap();
371 let path = glyph_path(&font, &face, gid, 100.0, [0.0, 0.0], 0.0);
372 assert!(path.iter().any(|c| matches!(c, Command::QuadTo(..) | Command::CurveTo(..))));
373 let cov = fill(&path).unwrap();
374 assert!((60..=90).contains(&cov.height), "O cap height {}", cov.height);
375 let ring = stroke(&path, 10.0).unwrap();
376 assert!(ring.width >= cov.width + 8, "stroke must extend past the fill");
377 assert!(cov.data.iter().any(|&a| a > 0 && a < 255), "edges are antialiased");
378 }
379
380 #[test]
381 fn outline_stroke_grows_the_domain_and_sits_under_the_fill() {
382 let plain = render_bounds(&params("HI")).unwrap();
383 let mut p = params("HI");
384 p.outline_rgba = [1.0, 0.0, 0.0, 1.0];
385 p.outline_width_px = 12.0;
386 let outlined = render_bounds(&p).unwrap();
387 assert!(outlined[0] <= plain[0] - 5 && outlined[2] >= plain[2] + 5, "{outlined:?} vs {plain:?}");
388 let (size, origin, rgba) = rasterize_text_plus(DIMS, &p, 0);
389 let at = |x: i32, y: i32| {
390 let i = (((y - origin[1]) as u32 * size[0] + (x - origin[0]) as u32) * 4) as usize;
391 [rgba[i], rgba[i + 1], rgba[i + 2], rgba[i + 3]]
392 };
393 let ring = at(plain[0] - 3, (plain[1] + plain[3]) / 2);
394 assert!(ring[0] > 200 && ring[1] < 10 && ring[3] > 200, "outline pixel {ring:?}");
395 }
396
397 #[test]
398 fn write_on_reveals_by_character_without_moving_layout() {
399 let full = render_bounds(&params("HHHH")).unwrap();
400 let mut p = params("HHHH");
401 p.write_on_end = 0.5;
402 let half = render_bounds(&p).unwrap();
403 assert_eq!(half[0], full[0], "the first glyph stays put");
404 assert!(half[2] < (full[0] + full[2]) / 2 + 3, "{half:?} vs {full:?}");
405 p.write_on_start = 0.5;
406 p.write_on_end = 1.0;
407 let tail = render_bounds(&p).unwrap();
408 assert_eq!(tail[2], full[2], "the last glyph stays put");
409 p.write_on_start = 1.0;
410 assert!(render_bounds(&p).is_none());
411 }
412
413 #[test]
414 fn cls_offsets_move_only_the_styled_characters() {
415 let base = render_bounds(&params("HH")).unwrap();
416 let cls = [ClsEntry { prop_id: 1351, start: 1, end: 1, value: 0.05 }];
417 let mut p = params("HH");
418 p.cls = &cls;
419 let raised = render_bounds(&p).unwrap();
420 assert_eq!(raised[0], base[0]);
421 assert_eq!(raised[2], base[2]);
422 assert!(raised[1] < base[1] - 30, "{raised:?} vs {base:?}");
423 }
424
425 #[test]
426 fn character_spacing_widens_lines() {
427 let width = |t: f32| {
428 let mut p = params("HHHH");
429 p.tracking = t;
430 let b = render_bounds(&p).unwrap();
431 b[2] - b[0]
432 };
433 assert!(width(1.5) > width(1.0) + 20);
434 }
435
436 #[test]
437 fn justification_anchors_lines() {
438 let at = |h: f32| {
439 let mut p = params("HHHH");
440 p.h_lcr = h;
441 render_bounds(&p).unwrap()
442 };
443 let (left, centre, right) = (at(-1.0), at(0.0), at(1.0));
444 assert!((left[0] - 480).abs() <= 6, "{left:?}");
445 assert!((right[2] - 480).abs() <= 6, "{right:?}");
446 assert!(((centre[0] + centre[2]) / 2 - 480).abs() <= 3, "{centre:?}");
447 }
448}