Skip to main content

ultrafast_geom/
geom.rs

1//! Vector geometry for the GPU rasterizer: paths (SVG data, presets,
2//! strokes, dashes, trims) and text (font lookup, shaping, layout).
3//!
4//! Everything expensive is cached: shaped lines by (font, size, text),
5//! glyph outlines by (font, glyph), and final flattened segments by a hash
6//! of every input (params, transform, time when animated). A static path or
7//! label costs nothing per frame; an animated one re-flattens only.
8
9use crate::{Affine, GeomError, text};
10use kurbo::{BezPath, ParamCurve, ParamCurveArclen, PathEl, Point, Shape};
11use std::collections::HashMap;
12use std::hash::{Hash, Hasher};
13use std::path::{Path, PathBuf};
14use std::sync::Arc;
15use ultrafast_graph::{Format, Node, Param};
16use unicode_script::{Script, UnicodeScript};
17
18/// Flattened geometry ready for upload: per segment two float4s,
19/// (x0, y0, x1, y1) and (weight, color group, 0, 0), in output pixels.
20#[derive(Debug, Clone, Default)]
21pub struct Geometry {
22    pub segments: Vec<f32>,
23    /// Bounds in output pixels (min x, min y, max x, max y).
24    pub bounds: [f32; 4],
25    /// Colors of the segment groups, composited in order (each over the
26    /// ones before): linear straight-alpha, or None for the node's own
27    /// color. Empty means one group in the node's color.
28    pub groups: Vec<Option<[f32; 4]>>,
29    /// Color glyphs (emoji) drawn from their bitmaps over the groups.
30    pub images: Vec<GlyphImage>,
31    /// A text's glyph units laid out: what its `reveal` counts (0 for
32    /// paths).
33    pub units: usize,
34}
35
36/// A color glyph's bitmap (an sbix or CBDT strike): linear premultiplied
37/// RGBA as half floats, row-major from the top.
38pub struct GlyphBitmap {
39    /// Identifies the bitmap (face, glyph, strike) for GPU caches.
40    pub key: u64,
41    pub width: u32,
42    pub height: u32,
43    pub rgba: Vec<u16>,
44    /// Where it sits in font units: left, bottom, width, height (y up).
45    pub place: [f64; 4],
46}
47
48impl std::fmt::Debug for GlyphBitmap {
49    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
50        write!(f, "GlyphBitmap({:x}, {}x{})", self.key, self.width, self.height)
51    }
52}
53
54/// A color glyph placed in the output.
55#[derive(Clone, Debug)]
56pub struct GlyphImage {
57    pub bitmap: Arc<GlyphBitmap>,
58    /// Maps the bitmap's unit square (u right, v down) to output pixels.
59    pub xf: [f64; 6],
60    /// Coverage weight (reveal, per-glyph opacity).
61    pub weight: f32,
62}
63
64impl Geometry {
65    pub fn count(&self) -> usize {
66        self.segments.len() / 8
67    }
68
69    fn push(&mut self, a: Point, b: Point, w: f32, group: u32) {
70        if a == b {
71            return;
72        }
73        self.segments.extend([
74            a.x as f32,
75            a.y as f32,
76            b.x as f32,
77            b.y as f32,
78            w,
79            group as f32,
80            0.0,
81            0.0,
82        ]);
83        for p in [a, b] {
84            self.bounds[0] = self.bounds[0].min(p.x as f32);
85            self.bounds[1] = self.bounds[1].min(p.y as f32);
86            self.bounds[2] = self.bounds[2].max(p.x as f32);
87            self.bounds[3] = self.bounds[3].max(p.y as f32);
88        }
89    }
90
91    fn empty() -> Self {
92        Geometry {
93            segments: Vec::new(),
94            bounds: [f32::MAX, f32::MAX, f32::MIN, f32::MIN],
95            groups: Vec::new(),
96            images: Vec::new(),
97            units: 0,
98        }
99    }
100
101    /// Adds a color glyph, growing the bounds by its corners.
102    fn push_image(&mut self, im: GlyphImage) {
103        let m = im.xf;
104        for (u, v) in [(0.0, 0.0), (1.0, 0.0), (0.0, 1.0), (1.0, 1.0)] {
105            let x = (m[0] * u + m[2] * v + m[4]) as f32;
106            let y = (m[1] * u + m[3] * v + m[5]) as f32;
107            self.bounds[0] = self.bounds[0].min(x);
108            self.bounds[1] = self.bounds[1].min(y);
109            self.bounds[2] = self.bounds[2].max(x);
110            self.bounds[3] = self.bounds[3].max(y);
111        }
112        self.images.push(im);
113    }
114
115    /// Whether there is nothing to draw.
116    pub fn is_empty(&self) -> bool {
117        self.segments.is_empty() && self.images.is_empty()
118    }
119}
120
121/// Flattening tolerance in output pixels.
122const TOLERANCE: f64 = 0.1;
123
124/// Appends `path` (already in output space) as closed contours: fills need
125/// every subpath closed, whether or not the data closes it.
126fn flatten_closed(path: &BezPath, weight: f32, group: u32, out: &mut Geometry) {
127    let mut start = Point::ZERO;
128    let mut last = Point::ZERO;
129    let mut open = false;
130    kurbo::flatten(path.iter(), TOLERANCE, |el| match el {
131        PathEl::MoveTo(p) => {
132            if open {
133                out.push(last, start, weight, group);
134            }
135            start = p;
136            last = p;
137            open = true;
138        }
139        PathEl::LineTo(p) => {
140            out.push(last, p, weight, group);
141            last = p;
142        }
143        PathEl::ClosePath => {
144            out.push(last, start, weight, group);
145            last = start;
146            open = false;
147        }
148        _ => {}
149    });
150    if open {
151        out.push(last, start, weight, group);
152    }
153}
154
155pub struct Fonts {
156    db: Option<fontdb::Database>,
157    data: HashMap<fontdb::ID, (Arc<Vec<u8>>, u32)>,
158    files: HashMap<PathBuf, fontdb::ID>,
159    shaped: crate::lru::Lru<u64, Arc<ShapedLine>>,
160    /// Outlines by face, glyph and variation-instance hash.
161    glyphs: crate::lru::Lru<(fontdb::ID, u16, u64), Arc<BezPath>>,
162    /// Whether a face has a glyph for a character, and which face stands in
163    /// for characters the requested one lacks.
164    covers: HashMap<(fontdb::ID, char), bool>,
165    fallback: HashMap<char, Option<fontdb::ID>>,
166    /// Families looked up by name: whether the database has them (after
167    /// fetching from the font cache or Google Fonts when it did not).
168    families: HashMap<String, bool>,
169    /// Decoded color glyph bitmaps by face, glyph and strike.
170    bitmaps: crate::lru::Lru<(fontdb::ID, u16, u16), Option<Arc<GlyphBitmap>>>,
171    /// Color emoji faces installed, in preference order.
172    emoji: Option<Vec<fontdb::ID>>,
173    /// Whether a face has color bitmaps (sbix, CBDT).
174    color: HashMap<fontdb::ID, bool>,
175    /// Faces resolved by (font, weight, italic, base dir) hash: matching a
176    /// family by weight scans every face, so it happens once (and again
177    /// when faces are added).
178    resolved: HashMap<u64, fontdb::ID>,
179    /// Pinned faces by (lowercase family, weight, italic): ahead of every
180    /// other source until [`Fonts::unpin`].
181    pins: HashMap<(String, u16, bool), fontdb::ID>,
182    /// How this document sets writing systems its fonts do not cover. Empty
183    /// for almost every document, which then lays out exactly as it always
184    /// has.
185    script_fonts: Vec<ScriptFont>,
186}
187
188/// How a document sets one writing system: the face that stands in for each
189/// requested font, and what that system's text may do. `meta.script_fonts`
190/// in a document, for this render only.
191#[derive(Debug, Clone, PartialEq, serde::Deserialize, serde::Serialize)]
192#[serde(deny_unknown_fields)]
193pub struct ScriptFont {
194    /// ISO 15924 codes this row sets ("Deva", or "Hani", "Hira", "Kana" for
195    /// Japanese).
196    pub scripts: Vec<String>,
197    /// Requested family (lowercase) to the family that sets this script,
198    /// "Family@800" to set it at that weight whatever the text asks for.
199    #[serde(default)]
200    pub faces: HashMap<String, String>,
201    /// The family for any other requested font.
202    pub default: String,
203    /// Size relative to the requested one, so a line reads at one size.
204    #[serde(default = "one")]
205    pub scale: f64,
206    /// Line height relative to the requested one, for tall marks.
207    #[serde(default = "one")]
208    pub leading: f64,
209    /// Whether letter spacing applies. Connected scripts and scripts whose
210    /// letters hang from one line break apart with it.
211    #[serde(default = "yes")]
212    pub tracking: bool,
213    /// Whether per-letter animation moves whole words instead of clusters
214    /// (the same scripts).
215    #[serde(default)]
216    pub whole_words: bool,
217    /// Language for the font's localized forms ("mr", "ur").
218    #[serde(default)]
219    pub language: Option<String>,
220}
221
222fn one() -> f64 {
223    1.0
224}
225
226fn yes() -> bool {
227    true
228}
229
230/// A font file that answers for a family, weight and style (see
231/// [`Fonts::pin`]).
232#[derive(Debug, Clone, PartialEq)]
233pub struct FontPin {
234    pub family: String,
235    pub weight: u16,
236    pub italic: bool,
237    pub path: PathBuf,
238}
239
240/// A glyph of a laid-out line: its face (the requested one, or a fallback
241/// for characters it lacks), position and advance in pixels.
242#[derive(Debug, Clone)]
243pub struct LineGlyph {
244    pub font: fontdb::ID,
245    pub id: u16,
246    pub x: f64,
247    pub y: f64,
248    pub advance: f64,
249    /// Byte offset of the text it sets.
250    pub cluster: usize,
251    /// Pixels per font unit of its face.
252    pub scale: f64,
253    /// Letter spacing units before it. Each glyph's own in Latin text;
254    /// a vowel sign shares its letter's, and a connected script has none.
255    pub track: u32,
256    /// Which animation unit it moves with, in reading order: each glyph in
257    /// Latin text, a letter with its marks, or a whole word.
258    pub unit: u32,
259    /// Set in a stand-in face for its script: never slanted to fake italics.
260    pub upright: bool,
261}
262
263/// Faces tried first for characters the requested font lacks.
264const FALLBACK_FAMILIES: &[&str] = &[
265    "Helvetica Neue",
266    "Apple Symbols",
267    "Arial Unicode MS",
268    "PingFang SC",
269    "Hiragino Sans",
270    "Apple SD Gothic Neo",
271    "Noto Sans",
272    "Noto Sans Symbols 2",
273    "DejaVu Sans",
274    "Segoe UI Symbol",
275];
276
277/// Color emoji faces, in preference order.
278const EMOJI_FAMILIES: &[&str] = &[
279    "Apple Color Emoji",
280    "Noto Color Emoji",
281    "Segoe UI Emoji",
282    "Twemoji Mozilla",
283];
284
285/// Whether `c` (followed by `next`) is shown as an emoji: characters whose
286/// default presentation is emoji (Unicode's Emoji_Presentation), and any
287/// character asking for it with VARIATION SELECTOR-16.
288fn emoji_presentation(c: char, next: Option<char>) -> bool {
289    match next {
290        Some('\u{fe0f}') => return true,
291        Some('\u{fe0e}') => return false,
292        _ => {}
293    }
294    matches!(c as u32,
295        0x231A..=0x231B | 0x23E9..=0x23EC | 0x23F0 | 0x23F3 | 0x25FD..=0x25FE | 0x2614..=0x2615
296        | 0x2648..=0x2653 | 0x267F | 0x2693 | 0x26A1 | 0x26AA..=0x26AB | 0x26BD..=0x26BE
297        | 0x26C4..=0x26C5 | 0x26CE | 0x26D4 | 0x26EA | 0x26F2..=0x26F3 | 0x26F5 | 0x26FA | 0x26FD
298        | 0x2705 | 0x270A..=0x270B | 0x2728 | 0x274C | 0x274E | 0x2753..=0x2755 | 0x2757
299        | 0x2795..=0x2797 | 0x27B0 | 0x27BF | 0x2B1B..=0x2B1C | 0x2B50 | 0x2B55
300        | 0x1F004 | 0x1F0CF | 0x1F18E | 0x1F191..=0x1F19A | 0x1F1E6..=0x1F1FF | 0x1F201 | 0x1F21A
301        | 0x1F22F | 0x1F232..=0x1F236 | 0x1F238..=0x1F23A | 0x1F250..=0x1F251 | 0x1F300..=0x1F320
302        | 0x1F32D..=0x1F335 | 0x1F337..=0x1F37C | 0x1F37E..=0x1F393 | 0x1F3A0..=0x1F3CA
303        | 0x1F3CF..=0x1F3D3 | 0x1F3E0..=0x1F3F0 | 0x1F3F4 | 0x1F3F8..=0x1F43E | 0x1F440
304        | 0x1F442..=0x1F4FC | 0x1F4FF..=0x1F53D | 0x1F54B..=0x1F54E | 0x1F550..=0x1F567 | 0x1F57A
305        | 0x1F595..=0x1F596 | 0x1F5A4 | 0x1F5FB..=0x1F64F | 0x1F680..=0x1F6C5 | 0x1F6CC
306        | 0x1F6D0..=0x1F6D2 | 0x1F6D5..=0x1F6D7 | 0x1F6DC..=0x1F6DF | 0x1F6EB..=0x1F6EC
307        | 0x1F6F4..=0x1F6FC | 0x1F7E0..=0x1F7EB | 0x1F7F0 | 0x1F90C..=0x1F93A | 0x1F93C..=0x1F945
308        | 0x1F947..=0x1F9FF | 0x1FA70..=0x1FAFF)
309}
310
311/// Characters that belong to the one before them in an emoji sequence.
312fn attaches(c: char) -> bool {
313    matches!(c as u32, 0x200D | 0xFE0E | 0xFE0F | 0x20E3 | 0x1F3FB..=0x1F3FF | 0xE0020..=0xE007F)
314}
315
316/// Decodes a glyph's raster image to linear premultiplied RGBA (half
317/// floats) and its placement in font units (left, bottom, width, height).
318fn decode_glyph_image(
319    img: &rustybuzz::ttf_parser::RasterGlyphImage,
320    units_per_em: f64,
321) -> Option<(u32, u32, Vec<u16>, [f64; 4])> {
322    use rustybuzz::ttf_parser::RasterImageFormat;
323    // Straight-alpha sRGB8 or premultiplied sRGB8 pixels.
324    let (w, h, px, premultiplied): (u32, u32, Vec<u8>, bool) = match img.format {
325        RasterImageFormat::PNG => {
326            let im = image::load_from_memory_with_format(img.data, image::ImageFormat::Png).ok()?;
327            let im = im.to_rgba8();
328            (im.width(), im.height(), im.into_raw(), false)
329        }
330        RasterImageFormat::BitmapPremulBgra32 => {
331            let (w, h) = (img.width as u32, img.height as u32);
332            let mut px = img.data.get(..(w * h * 4) as usize)?.to_vec();
333            for p in px.chunks_exact_mut(4) {
334                p.swap(0, 2);
335            }
336            (w, h, px, true)
337        }
338        _ => return None,
339    };
340    if w == 0 || h == 0 {
341        return None;
342    }
343    let lut: Vec<f32> = (0..256)
344        .map(|v| {
345            let c = v as f32 / 255.0;
346            if c <= 0.04045 {
347                c / 12.92
348            } else {
349                ((c + 0.055) / 1.055).powf(2.4)
350            }
351        })
352        .collect();
353    let mut rgba = Vec::with_capacity(px.len());
354    for p in px.chunks_exact(4) {
355        let a = p[3] as f32 / 255.0;
356        let un = |v: u8| {
357            if premultiplied && a > 0.0 {
358                lut[((v as f32 / a).round().min(255.0)) as usize]
359            } else {
360                lut[v as usize]
361            }
362        };
363        for c in [un(p[0]) * a, un(p[1]) * a, un(p[2]) * a, a] {
364            rgba.push(crate::f32_to_f16(c));
365        }
366    }
367    let s = units_per_em / img.pixels_per_em.max(1) as f64;
368    // The image may be larger than its metrics say: scale to what it is.
369    let (mw, mh) = (img.width.max(1) as f64, img.height.max(1) as f64);
370    let place = [img.x as f64 * s, img.y as f64 * s, mw * s, mh * s];
371    let _ = (w, h);
372    Some((w, h, rgba, place))
373}
374
375/// A variable font instance: axis tag and value pairs.
376pub type Variations = Vec<rustybuzz::Variation>;
377
378fn variations_key(vars: &[rustybuzz::Variation]) -> u64 {
379    let mut h = std::collections::hash_map::DefaultHasher::new();
380    for v in vars {
381        v.tag.to_bytes().hash(&mut h);
382        v.value.to_bits().hash(&mut h);
383    }
384    h.finish()
385}
386
387#[derive(Debug, Clone)]
388pub struct ShapedGlyph {
389    pub id: u16,
390    /// Pen position and offset in font units.
391    pub x: f32,
392    pub y: f32,
393    /// Advance in font units, and the byte offset of the text it came from.
394    pub advance: f32,
395    pub cluster: u32,
396}
397
398#[derive(Debug)]
399pub struct ShapedLine {
400    pub glyphs: Vec<ShapedGlyph>,
401    /// Total advance in font units.
402    pub advance: f32,
403}
404
405/// Applies a face's pair-kerning `kerx` subtables (formats 0, 2 and 6),
406/// which rustybuzz 0.20 reads but never applies (its skipping iterator
407/// ignores base glyphs), as HarfBuzz does: half of each pair's value on
408/// each glyph. Faces such as macOS's Helvetica Neue kern only through
409/// `kerx`. Shaping that applied a state-machine `kerx` (formats 1, 4) or
410/// GPOS is left alone.
411fn kerx_pairs(face: &rustybuzz::Face, infos: &[rustybuzz::GlyphInfo], pos: &mut [(i32, i32, i32)]) {
412    use rustybuzz::ttf_parser::{GlyphId, kerx::Format};
413    let t = face.tables();
414    let Some(kerx) = t.kerx else { return };
415    if t.gpos.is_some() && t.gsub.is_some() {
416        return;
417    }
418    for sub in kerx.subtables {
419        if sub.variable || !sub.horizontal || sub.has_cross_stream {
420            continue;
421        }
422        if !matches!(sub.format, Format::Format0(_) | Format::Format2(_) | Format::Format6(_)) {
423            continue;
424        }
425        for i in 0..infos.len().saturating_sub(1) {
426            let k = sub
427                .glyphs_kerning(GlyphId(infos[i].glyph_id as u16), GlyphId(infos[i + 1].glyph_id as u16))
428                .unwrap_or(0) as i32;
429            if k != 0 {
430                let k1 = k >> 1;
431                let k2 = k - k1;
432                pos[i].0 += k1;
433                pos[i + 1].0 += k2;
434                pos[i + 1].1 += k2;
435            }
436        }
437    }
438}
439
440struct FontMetrics {
441    units_per_em: f32,
442    ascender: f32,
443    descender: f32,
444}
445
446/// Faces bundled into ultrafast (SIL Open Font License; see
447/// examples/assets/fonts/licenses, linked from this crate's fonts/), loadable by family name or as
448/// `ultrafast:sans`, `ultrafast:mono`, `ultrafast:serif`, `ultrafast:display`, `ultrafast:wide`.
449const BUNDLED: &[&[u8]] = &[
450    include_bytes!("../fonts/Geist-VF.ttf"),
451    include_bytes!("../fonts/GeistMono-VF.ttf"),
452    include_bytes!("../fonts/InstrumentSerif-Regular.ttf"),
453    include_bytes!("../fonts/InstrumentSerif-Italic.ttf"),
454    include_bytes!("../fonts/Fraunces-VF.ttf"),
455    include_bytes!("../fonts/Fraunces-Italic-VF.ttf"),
456    include_bytes!("../fonts/Unbounded-VF.ttf"),
457];
458
459/// The font files bundled into ultrafast (for tools that search faces).
460pub fn bundled_fonts() -> &'static [&'static [u8]] {
461    BUNDLED
462}
463
464/// The faces text is set from: the system's fonts, ultrafast's bundled
465/// faces, and CSS's generic families mapped to faces this machine has.
466/// The text op and SVG import both start from it.
467pub fn base_database() -> fontdb::Database {
468    let mut db = fontdb::Database::new();
469    db.load_system_fonts();
470    // Bundled faces (SIL Open Font License): the same type on every
471    // machine, servers included, by family name.
472    for data in BUNDLED {
473        db.load_font_data(data.to_vec());
474    }
475    // CSS generic families resolve to faces this machine has
476    // (fontdb's defaults, Arial and friends, are missing on servers):
477    // on Linux what Chrome's fontconfig picks (Liberation, metric
478    // twins of Arial, Times New Roman and Courier New), on a Mac what
479    // Safari and Chrome show.
480    let pick = |db: &fontdb::Database, names: &[&str]| {
481        names
482            .iter()
483            .find(|n| db.faces().any(|f| f.families.iter().any(|(fam, _)| fam == *n)))
484            .map(|n| n.to_string())
485    };
486    let mac = cfg!(target_os = "macos");
487    let sans: &[&str] = if mac {
488        &["Helvetica", "Arial", "Geist"]
489    } else {
490        &["Liberation Sans", "Arial", "DejaVu Sans", "Noto Sans", "Geist"]
491    };
492    let serif: &[&str] = if mac {
493        &["Times", "Times New Roman", "Instrument Serif"]
494    } else {
495        &[
496            "Liberation Serif",
497            "Times New Roman",
498            "DejaVu Serif",
499            "Noto Serif",
500            "Instrument Serif",
501        ]
502    };
503    let mono: &[&str] = if mac {
504        &["Courier", "Courier New", "Menlo", "Geist Mono"]
505    } else {
506        &[
507            "Liberation Mono",
508            "Courier New",
509            "DejaVu Sans Mono",
510            "Noto Sans Mono",
511            "Geist Mono",
512        ]
513    };
514    if let Some(f) = pick(&db, sans) {
515        db.set_sans_serif_family(f.clone());
516        db.set_cursive_family(f.clone());
517        db.set_fantasy_family(f);
518    }
519    if let Some(f) = pick(&db, serif) {
520        db.set_serif_family(f);
521    }
522    if let Some(f) = pick(&db, mono) {
523        db.set_monospace_family(f);
524    }
525    db
526}
527
528impl Fonts {
529    pub fn new() -> Self {
530        Self {
531            db: None,
532            data: HashMap::new(),
533            files: HashMap::new(),
534            // Bounded: text edited live would otherwise grow these forever.
535            shaped: crate::lru::Lru::new(4096),
536            glyphs: crate::lru::Lru::new(32768),
537            covers: HashMap::new(),
538            fallback: HashMap::new(),
539            families: HashMap::new(),
540            bitmaps: crate::lru::Lru::new(512),
541            emoji: None,
542            color: HashMap::new(),
543            resolved: HashMap::new(),
544            pins: HashMap::new(),
545            script_fonts: Vec::new(),
546        }
547    }
548
549    /// How this document sets the writing systems its fonts do not cover,
550    /// until [`Fonts::unpin`] or the next call.
551    pub fn set_script_fonts(&mut self, rows: Vec<ScriptFont>) {
552        self.script_fonts = rows;
553    }
554
555    /// The row that sets `c`, when a document has one for its script.
556    fn script_row(&self, c: char) -> Option<usize> {
557        if self.script_fonts.is_empty() {
558            return None;
559        }
560        let script = c.script();
561        if matches!(script, Script::Common | Script::Inherited | Script::Unknown) {
562            return None;
563        }
564        let name = script.short_name();
565        self.script_fonts
566            .iter()
567            .position(|row| row.scripts.iter().any(|s| s == name))
568    }
569
570    /// Line height multiplier of `text`: the tallest of its scripts.
571    pub fn script_leading(&self, text: &str) -> f64 {
572        if self.script_fonts.is_empty() {
573            return 1.0;
574        }
575        text.chars()
576            .filter_map(|c| self.script_row(c))
577            .map(|row| self.script_fonts[row].leading)
578            .fold(1.0, f64::max)
579    }
580
581    /// Whether `text` reads right to left (for a document that sets a
582    /// script: every other document lays out as it always has).
583    pub fn reads_rtl(&self, text: &str) -> bool {
584        !self.script_fonts.is_empty() && unicode_bidi::get_base_direction(text) == unicode_bidi::Direction::Rtl
585    }
586
587    /// The family, weight and italic a face answers for.
588    fn face_key(&mut self, id: fontdb::ID) -> (String, u16, bool) {
589        if let Some(((family, weight, italic), _)) = self.pins.iter().find(|(_, v)| **v == id) {
590            return (family.clone(), *weight, *italic);
591        }
592        self.db()
593            .face(id)
594            .map(|f| {
595                (
596                    f.families.first().map(|(n, _)| n.to_lowercase()).unwrap_or_default(),
597                    f.weight.0,
598                    f.style != fontdb::Style::Normal,
599                )
600            })
601            .unwrap_or_default()
602    }
603
604    /// The face a row sets `primary`'s text in, closest to its weight.
605    fn script_face(&mut self, primary: fontdb::ID, row: usize) -> Result<fontdb::ID, String> {
606        let (family, weight, _) = self.face_key(primary);
607        let spec = &self.script_fonts[row];
608        let target = spec.faces.get(&family).unwrap_or(&spec.default).clone();
609        // "Family@800": a one-weight display font asks for 400 but reads heavy.
610        let (target, weight) = match target
611            .rsplit_once('@')
612            .and_then(|(f, w)| Some((f, w.parse::<u16>().ok()?)))
613        {
614            Some((f, w)) => (f.to_string(), w),
615            None => (target, weight),
616        };
617        if let Some(id) = self.pinned(&target, weight, false) {
618            return Ok(id);
619        }
620        let q = fontdb::Query {
621            families: &[fontdb::Family::Name(&target)],
622            weight: fontdb::Weight(weight),
623            ..Default::default()
624        };
625        self.db()
626            .query(&q)
627            .ok_or_else(|| format!("no face for script font `{target}` (it must be pinned in meta.fonts)"))
628    }
629
630    /// The face a family and weight resolve to (for [`Fonts::missing_glyphs`]).
631    pub fn lookup(&mut self, family: &str, weight: u16) -> Result<fontdb::ID, String> {
632        self.resolve(family, weight, false, Path::new("."))
633    }
634
635    /// Characters of `text` no face in this document can draw, as a render
636    /// would find them (a look's check, before anything renders).
637    pub fn missing_glyphs(&mut self, primary: fontdb::ID, text: &str) -> Vec<char> {
638        let mut out = Vec::new();
639        let chars: Vec<char> = text.chars().collect();
640        for (i, &c) in chars.iter().enumerate() {
641            // Spaces and the marks that draw nothing (joiners, direction marks).
642            if c.is_whitespace()
643                || c.is_control()
644                || attaches(c)
645                || matches!(c as u32, 0xAD | 0x200B..=0x200F | 0x202A..=0x202E | 0x2060..=0x2064 | 0xFEFF)
646            {
647                continue;
648            }
649            if emoji_presentation(c, chars.get(i + 1).copied()) {
650                continue;
651            }
652            let found = match self.script_row(c) {
653                Some(row) => {
654                    self.has_glyph(primary, c)
655                        || self.script_face(primary, row).is_ok_and(|face| self.has_glyph(face, c))
656                }
657                None => self.has_glyph(primary, c) || self.fallback_for(c).is_some(),
658            };
659            if !found && !out.contains(&c) {
660                out.push(c);
661            }
662        }
663        out
664    }
665
666    /// Pins font files to their family, weight and style: until
667    /// [`Fonts::unpin`], those files answer for them ahead of every other
668    /// font (installed, bundled or fetched), so text is set with exactly the
669    /// files it was measured with elsewhere. Replaces earlier pins.
670    pub fn pin(&mut self, pins: &[FontPin]) -> Result<(), String> {
671        self.unpin();
672        for p in pins {
673            let ids = self.db().load_font_source(fontdb::Source::File(p.path.clone()));
674            let id = *ids
675                .first()
676                .ok_or_else(|| format!("no font in {} (pinned for {})", p.path.display(), p.family))?;
677            self.pins
678                .insert((p.family.trim().to_lowercase(), p.weight, p.italic), id);
679        }
680        self.forget_resolved();
681        Ok(())
682    }
683
684    /// Drops the pins (their faces leave the database).
685    pub fn unpin(&mut self) {
686        self.script_fonts.clear();
687        if self.pins.is_empty() {
688            return;
689        }
690        let pinned: Vec<(String, fontdb::ID)> = self.pins.drain().map(|((f, _, _), id)| (f, id)).collect();
691        for (family, id) in pinned {
692            self.db().remove_face(id);
693            self.data.remove(&id);
694            self.color.remove(&id);
695            self.families.remove(&family);
696        }
697        self.forget_resolved();
698    }
699
700    /// After faces come or go: lookups that may name them start over.
701    fn forget_resolved(&mut self) {
702        self.resolved.clear();
703        self.fallback.clear();
704        self.covers.clear();
705        self.emoji = None;
706    }
707
708    /// The pinned face for a family closest to `weight` (same style first).
709    fn pinned(&self, family: &str, weight: u16, italic: bool) -> Option<fontdb::ID> {
710        if self.pins.is_empty() {
711            return None;
712        }
713        let key = family.trim().to_lowercase();
714        self.pins
715            .iter()
716            .filter(|((f, _, _), _)| *f == key)
717            .min_by_key(|((_, w, i), _)| ((*i != italic) as u32, (*w as i32 - weight as i32).unsigned_abs()))
718            .map(|(_, id)| *id)
719    }
720
721    /// Whether `family` is available, loading it from the font cache or
722    /// downloading it from Google Fonts the first time it is missing.
723    fn ensure_family(&mut self, family: &str) -> bool {
724        let key = family.to_lowercase();
725        if let Some(&ok) = self.families.get(&key) {
726            return ok;
727        }
728        let has = |db: &fontdb::Database| {
729            db.faces()
730                .any(|f| f.families.iter().any(|(n, _)| n.to_lowercase() == key))
731        };
732        let mut ok = has(self.db());
733        if !ok {
734            for p in crate::fontfetch::fetch(family) {
735                let _ = self.db().load_font_file(&p);
736            }
737            self.resolved.clear();
738            ok = has(self.db());
739        }
740        self.families.insert(key, ok);
741        ok
742    }
743
744    /// Whether `family` is a named family this machine does not have yet
745    /// (generic families, ultrafast's aliases and font files never are).
746    pub fn lacks(&mut self, family: &str) -> bool {
747        let key = family.trim().to_lowercase();
748        let generic = matches!(
749            key.as_str(),
750            "" | "sans-serif"
751                | "serif"
752                | "monospace"
753                | "cursive"
754                | "fantasy"
755                | "system-ui"
756                | "ui-sans-serif"
757                | "ui-serif"
758                | "ui-monospace"
759                | "-apple-system"
760                | "blinkmacsystemfont"
761        );
762        if generic || key.starts_with("ultrafast:") || [".ttf", ".otf", ".ttc"].iter().any(|e| key.ends_with(e)) {
763            return false;
764        }
765        if self.pins.keys().any(|(f, _, _)| *f == key) {
766            return false;
767        }
768        if let Some(&ok) = self.families.get(&key) {
769            return !ok;
770        }
771        !self
772            .db()
773            .faces()
774            .any(|f| f.families.iter().any(|(n, _)| n.to_lowercase() == key))
775    }
776
777    fn db(&mut self) -> &mut fontdb::Database {
778        self.db.get_or_insert_with(base_database)
779    }
780
781    /// Resolves a font from a family name, a CSS family list (`"Poppins",
782    /// sans-serif`: the first one this machine has or can fetch), a CSS
783    /// generic family, or a font file path.
784    fn resolve(&mut self, font: &str, weight: u16, italic: bool, base: &Path) -> Result<fontdb::ID, String> {
785        let key = {
786            use std::hash::{Hash, Hasher};
787            let mut h = std::collections::hash_map::DefaultHasher::new();
788            (font, weight, italic, base).hash(&mut h);
789            h.finish()
790        };
791        if let Some(&id) = self.resolved.get(&key) {
792            return Ok(id);
793        }
794        let id = self.resolve_uncached(font, weight, italic, base)?;
795        self.resolved.insert(key, id);
796        Ok(id)
797    }
798
799    fn resolve_uncached(&mut self, font: &str, weight: u16, italic: bool, base: &Path) -> Result<fontdb::ID, String> {
800        let names: Vec<&str> = font
801            .split(',')
802            .map(|f| f.trim().trim_matches(|c| c == '"' || c == '\''))
803            .filter(|f| !f.is_empty())
804            .collect();
805        if names.len() > 1 {
806            for (i, name) in names.iter().enumerate() {
807                if let Some(id) = self.resolve_one(name, weight, italic, base, i + 1 == names.len())? {
808                    return Ok(id);
809                }
810            }
811        }
812        self.resolve_one(names.first().copied().unwrap_or(""), weight, italic, base, true)?
813            .ok_or_else(|| format!("no font matches `{font}`"))
814    }
815
816    /// One family (or a file); with `fallback`, a missing family resolves
817    /// to the sans-serif family instead of None.
818    fn resolve_one(
819        &mut self,
820        font: &str,
821        weight: u16,
822        italic: bool,
823        base: &Path,
824        fallback: bool,
825    ) -> Result<Option<fontdb::ID>, String> {
826        let looks_like_file = font.ends_with(".ttf") || font.ends_with(".otf") || font.ends_with(".ttc");
827        if looks_like_file {
828            let path = if Path::new(font).is_absolute() {
829                PathBuf::from(font)
830            } else {
831                base.join(font)
832            };
833            // A service rendering many callers' documents reads font files
834            // only from the document's own inputs (its base directory), so
835            // markup cannot name another path on the machine.
836            if std::env::var("ULTRAFAST_NO_EXTERNAL_FILES").as_deref() == Ok("1")
837                && (!path.starts_with(base) || path.components().any(|c| c == std::path::Component::ParentDir))
838            {
839                return Err(format!("font file {} is outside the document's inputs", path.display()));
840            }
841            if let Some(id) = self.files.get(&path) {
842                return Ok(Some(*id));
843            }
844            let ids = self.db().load_font_source(fontdb::Source::File(path.clone()));
845            self.resolved.clear();
846            let id = *ids.first().ok_or_else(|| format!("no font in {}", path.display()))?;
847            self.files.insert(path, id);
848            return Ok(Some(id));
849        }
850        if let Some(id) = self.pinned(font, weight, italic) {
851            return Ok(Some(id));
852        }
853        let font = match font {
854            "ultrafast:sans" => "Geist",
855            "ultrafast:mono" => "Geist Mono",
856            "ultrafast:serif" => "Instrument Serif",
857            "ultrafast:display" => "Fraunces",
858            "ultrafast:wide" => "Unbounded",
859            f => f,
860        };
861        let generic = match font.to_ascii_lowercase().as_str() {
862            "sans-serif" | "system-ui" | "ui-sans-serif" | "-apple-system" | "blinkmacsystemfont" => {
863                Some(fontdb::Family::SansSerif)
864            }
865            "serif" | "ui-serif" => Some(fontdb::Family::Serif),
866            "monospace" | "ui-monospace" => Some(fontdb::Family::Monospace),
867            "cursive" => Some(fontdb::Family::Cursive),
868            "fantasy" => Some(fontdb::Family::Fantasy),
869            _ => None,
870        };
871        if !font.is_empty() && generic.is_none() {
872            self.ensure_family(font);
873        }
874        let families: Vec<fontdb::Family> = if let Some(g) = generic {
875            vec![g, fontdb::Family::SansSerif]
876        } else if font.is_empty() {
877            vec![
878                fontdb::Family::Name("Helvetica Neue"),
879                fontdb::Family::Name("Geist"),
880                fontdb::Family::SansSerif,
881            ]
882        } else if fallback {
883            vec![fontdb::Family::Name(font), fontdb::Family::SansSerif]
884        } else {
885            vec![fontdb::Family::Name(font)]
886        };
887        let q = fontdb::Query {
888            families: &families,
889            weight: fontdb::Weight(weight),
890            stretch: fontdb::Stretch::Normal,
891            style: if italic {
892                fontdb::Style::Italic
893            } else {
894                fontdb::Style::Normal
895            },
896        };
897        let Some(found) = self.db().query(&q) else {
898            return Ok(None);
899        };
900        if font.is_empty() || generic.is_some() {
901            return Ok(Some(found));
902        }
903        // Google's static families name each extra weight as its own family
904        // ("Poppins Medium", weight class 500), which a query for "Poppins"
905        // never sees, so 500 fell back to 400. Match those faces by weight.
906        let key = font.to_lowercase();
907        let prefix = format!("{key} ");
908        let want_italic = italic;
909        // A face of another width is not a weight of this family, even when
910        // its file calls it a member with normal width ("Helvetica Neue
911        // Condensed Black" in macOS's HelveticaNeue.ttc).
912        let other_width = |f: &fontdb::FaceInfo| {
913            let names = format!(
914                "{} {}",
915                f.post_script_name,
916                f.families.iter().map(|(n, _)| n.as_str()).collect::<Vec<_>>().join(" ")
917            )
918            .to_lowercase();
919            f.stretch != fontdb::Stretch::Normal
920                || ["condensed", "compressed", "narrow", "extended", "expanded"]
921                    .iter()
922                    .any(|w| names.contains(w) && !key.contains(w))
923        };
924        let mut best: Option<(fontdb::ID, i32, bool)> = None;
925        for f in self.db().faces() {
926            let named = f.families.iter().any(|(n, _)| {
927                let n = n.to_lowercase();
928                n == key || n.starts_with(&prefix)
929            });
930            if !named || other_width(f) {
931                continue;
932            }
933            let style_ok = (f.style != fontdb::Style::Normal) == want_italic;
934            let d = (f.weight.0 as i32 - weight as i32).abs();
935            let better = match best {
936                None => true,
937                Some((_, bd, bs)) => (style_ok && !bs) || (style_ok == bs && d < bd),
938            };
939            if better {
940                best = Some((f.id, d, style_ok));
941            }
942        }
943        let found_d = self
944            .db()
945            .face(found)
946            .map(|f| (f.weight.0 as i32 - weight as i32).abs())
947            .unwrap_or(i32::MAX);
948        let found_style = self
949            .db()
950            .face(found)
951            .is_some_and(|f| (f.style != fontdb::Style::Normal) == want_italic);
952        let found_width = self.db().face(found).is_some_and(other_width);
953        match best {
954            Some((id, d, style_ok)) if found_width || (style_ok && (d < found_d || !found_style)) => Ok(Some(id)),
955            _ => Ok(Some(found)),
956        }
957    }
958
959    /// Whether a face is an italic or oblique design.
960    fn is_italic(&mut self, id: fontdb::ID) -> bool {
961        self.db().face(id).is_some_and(|f| f.style != fontdb::Style::Normal)
962    }
963
964    fn face_data(&mut self, id: fontdb::ID) -> Result<(Arc<Vec<u8>>, u32), String> {
965        if let Some(d) = self.data.get(&id) {
966            return Ok(d.clone());
967        }
968        let d = self
969            .db()
970            .with_face_data(id, |data, index| (Arc::new(data.to_vec()), index))
971            .ok_or("font data unavailable")?;
972        self.data.insert(id, d.clone());
973        Ok(d)
974    }
975
976    fn metrics(&mut self, id: fontdb::ID) -> Result<FontMetrics, String> {
977        let (data, index) = self.face_data(id)?;
978        let face = rustybuzz::Face::from_slice(&data, index).ok_or("unparseable font")?;
979        Ok(FontMetrics {
980            units_per_em: face.units_per_em() as f32,
981            ascender: face.ascender() as f32,
982            descender: face.descender() as f32,
983        })
984    }
985
986    /// Variation axes of a face: (tag, min, default, max).
987    fn axes(&mut self, id: fontdb::ID) -> Result<Vec<([u8; 4], f32, f32, f32)>, String> {
988        let (data, index) = self.face_data(id)?;
989        let face = rustybuzz::Face::from_slice(&data, index).ok_or("unparseable font")?;
990        Ok(face
991            .variation_axes()
992            .into_iter()
993            .map(|a| (a.tag.to_bytes(), a.min_value, a.def_value, a.max_value))
994            .collect())
995    }
996
997    fn has_glyph(&mut self, id: fontdb::ID, c: char) -> bool {
998        if let Some(&v) = self.covers.get(&(id, c)) {
999            return v;
1000        }
1001        let v = self
1002            .db()
1003            .with_face_data(id, |data, index| {
1004                rustybuzz::Face::from_slice(data, index).is_some_and(|f| f.glyph_index(c).is_some())
1005            })
1006            .unwrap_or(false);
1007        self.covers.insert((id, c), v);
1008        v
1009    }
1010
1011    /// A face that has `c`: preferred fallback families first, then any.
1012    fn fallback_for(&mut self, c: char) -> Option<fontdb::ID> {
1013        if let Some(v) = self.fallback.get(&c) {
1014            return *v;
1015        }
1016        let mut found = None;
1017        for fam in FALLBACK_FAMILIES {
1018            let q = fontdb::Query {
1019                families: &[fontdb::Family::Name(fam)],
1020                ..Default::default()
1021            };
1022            if let Some(id) = self.db().query(&q)
1023                && self.has_glyph(id, c)
1024            {
1025                found = Some(id);
1026                break;
1027            }
1028        }
1029        if found.is_none() {
1030            let ids: Vec<fontdb::ID> = self.db().faces().map(|f| f.id).collect();
1031            found = ids.into_iter().find(|&id| self.has_glyph(id, c));
1032        }
1033        self.fallback.insert(c, found);
1034        found
1035    }
1036
1037    /// The preferred color emoji face that has `c`.
1038    fn emoji_face(&mut self, c: char) -> Option<fontdb::ID> {
1039        if self.emoji.is_none() {
1040            let mut ids = self.emoji_faces();
1041            // Color emoji are drawn from bitmap strikes. Windows has only
1042            // Segoe UI Emoji (COLR layers) and a server may have none: then
1043            // Noto Color Emoji, what the render service draws with, is
1044            // fetched once.
1045            if !ids.iter().any(|&id| self.has_color_bitmaps(id)) {
1046                for p in crate::fontfetch::fetch_emoji() {
1047                    let _ = self.db().load_font_file(&p);
1048                }
1049                ids = self.emoji_faces();
1050            }
1051            self.emoji = Some(ids);
1052        }
1053        let ids = self.emoji.clone().unwrap_or_default();
1054        ids.into_iter().find(|&id| self.has_glyph(id, c))
1055    }
1056
1057    /// Installed emoji faces, in order of preference.
1058    fn emoji_faces(&mut self) -> Vec<fontdb::ID> {
1059        let mut ids = Vec::new();
1060        for fam in EMOJI_FAMILIES {
1061            let q = fontdb::Query {
1062                families: &[fontdb::Family::Name(fam)],
1063                ..Default::default()
1064            };
1065            if let Some(id) = self.db().query(&q) {
1066                ids.push(id);
1067            }
1068        }
1069        ids
1070    }
1071
1072    /// Whether a face draws (some) glyphs from color bitmaps.
1073    pub fn has_color_bitmaps(&mut self, id: fontdb::ID) -> bool {
1074        if let Some(&c) = self.color.get(&id) {
1075            return c;
1076        }
1077        let c = self.face_data(id).ok().is_some_and(|(data, index)| {
1078            rustybuzz::ttf_parser::Face::parse(&data, index)
1079                .is_ok_and(|f| f.tables().sbix.is_some() || f.tables().cbdt.is_some())
1080        });
1081        self.color.insert(id, c);
1082        c
1083    }
1084
1085    /// The bitmap of a color glyph at the strike nearest `ppem` (pixels per
1086    /// em on screen), or None for glyphs without one.
1087    pub fn glyph_bitmap(&mut self, id: fontdb::ID, glyph: u16, ppem: f64) -> Option<Arc<GlyphBitmap>> {
1088        let (data, index) = self.face_data(id).ok()?;
1089        let face = rustybuzz::ttf_parser::Face::parse(&data, index).ok()?;
1090        let want = ppem.ceil().clamp(1.0, u16::MAX as f64) as u16;
1091        let img = face.glyph_raster_image(rustybuzz::ttf_parser::GlyphId(glyph), want)?;
1092        let key = (id, glyph, img.pixels_per_em);
1093        if let Some(b) = self.bitmaps.get(&key) {
1094            return b;
1095        }
1096        let decoded = decode_glyph_image(&img, face.units_per_em() as f64).map(|(width, height, rgba, place)| {
1097            let mut h = std::collections::hash_map::DefaultHasher::new();
1098            key.hash(&mut h);
1099            Arc::new(GlyphBitmap {
1100                key: h.finish(),
1101                width,
1102                height,
1103                rgba,
1104                place,
1105            })
1106        });
1107        self.bitmaps.insert(key, decoded.clone());
1108        decoded
1109    }
1110
1111    /// Shapes a line in `primary`, setting characters it has no glyph for
1112    /// in a fallback face (split into runs; variations apply to `primary`).
1113    pub fn layout(
1114        &mut self,
1115        primary: fontdb::ID,
1116        text: &str,
1117        size: f64,
1118        features: &[rustybuzz::Feature],
1119        vars: &[rustybuzz::Variation],
1120    ) -> Result<(Vec<LineGlyph>, f64), String> {
1121        if !self.script_fonts.is_empty() {
1122            return self.layout_scripts(primary, text, size, features, vars);
1123        }
1124        // Runs of characters by the face that sets them. Characters shown
1125        // as emoji by default (or asking for it with VS16) are set in a
1126        // color emoji face, as browsers do, even when the font has a plain
1127        // glyph for them.
1128        let mut runs: Vec<(fontdb::ID, usize, usize)> = Vec::new();
1129        let mut chars = text.char_indices().peekable();
1130        while let Some((i, c)) = chars.next() {
1131            let next = chars.peek().map(|&(_, n)| n);
1132            let face = if c.is_whitespace() || c.is_control() {
1133                primary
1134            } else if let Some(e) = emoji_presentation(c, next).then(|| self.emoji_face(c)).flatten() {
1135                e
1136            } else if self.has_glyph(primary, c) {
1137                primary
1138            } else {
1139                self.fallback_for(c).unwrap_or(primary)
1140            };
1141            match runs.last_mut() {
1142                // Joiners, variation selectors, keycaps, skin tones and tag
1143                // characters stay with what they attach to, so the face
1144                // shapes the whole sequence (one glyph for a family or flag).
1145                Some(r) if r.0 == face || attaches(c) => r.2 = i + c.len_utf8(),
1146                _ => runs.push((face, i, i + c.len_utf8())),
1147            }
1148        }
1149        let mut out = Vec::new();
1150        let mut pen = 0.0f64;
1151        for (face, start, end) in runs {
1152            let fv: &[rustybuzz::Variation] = if face == primary { vars } else { &[] };
1153            let shaped = self.shape(face, &text[start..end], features, fv, None, None)?;
1154            let scale = size / self.metrics(face)?.units_per_em as f64;
1155            for g in &shaped.glyphs {
1156                let k = out.len() as u32;
1157                out.push(LineGlyph {
1158                    font: face,
1159                    id: g.id,
1160                    x: pen + g.x as f64 * scale,
1161                    y: g.y as f64 * scale,
1162                    advance: g.advance as f64 * scale,
1163                    cluster: start + g.cluster as usize,
1164                    scale,
1165                    track: k,
1166                    unit: k,
1167                    upright: false,
1168                });
1169            }
1170            pen += shaped.advance as f64 * scale;
1171        }
1172        Ok((out, pen))
1173    }
1174
1175    /// [`Fonts::layout`] for a document that sets scripts: each character in
1176    /// the face its script's row gives (unless the requested font has all of
1177    /// that stretch itself), right-to-left text in visual order, spacing and
1178    /// animation by whole clusters or words.
1179    fn layout_scripts(
1180        &mut self,
1181        primary: fontdb::ID,
1182        text: &str,
1183        size: f64,
1184        features: &[rustybuzz::Feature],
1185        vars: &[rustybuzz::Variation],
1186    ) -> Result<(Vec<LineGlyph>, f64), String> {
1187        let mut out: Vec<LineGlyph> = Vec::new();
1188        let mut pen = 0.0f64;
1189        let (mut track, mut unit) = (0u32, 0u32);
1190        let info = unicode_bidi::BidiInfo::new(text, None);
1191        for para in &info.paragraphs {
1192            let (levels, level_runs) = info.visual_runs(para, para.range.clone());
1193            for level_run in level_runs {
1194                let rtl = levels[level_run.start].is_rtl();
1195                let mut pieces = self.script_pieces(primary, text, level_run.clone())?;
1196                if rtl {
1197                    pieces.reverse();
1198                }
1199                let dir = if rtl {
1200                    rustybuzz::Direction::RightToLeft
1201                } else {
1202                    rustybuzz::Direction::LeftToRight
1203                };
1204                for (face, row, start, end) in pieces {
1205                    let spec = row.map(|r| self.script_fonts[r].clone());
1206                    let fv: &[rustybuzz::Variation] = if face == primary { vars } else { &[] };
1207                    let language = spec.as_ref().and_then(|s| s.language.clone());
1208                    let shaped = self.shape(face, &text[start..end], features, fv, Some(dir), language.as_deref())?;
1209                    let scale = size * spec.as_ref().map_or(1.0, |s| s.scale) / self.metrics(face)?.units_per_em as f64;
1210                    let (spaced, whole) = spec.as_ref().map_or((true, false), |s| (s.tracking, s.whole_words));
1211                    if !out.is_empty() {
1212                        track += 1;
1213                        unit += 1;
1214                    }
1215                    let mut previous: Option<u32> = None;
1216                    for g in &shaped.glyphs {
1217                        // Latin glyphs each move alone; in a stand-in face a
1218                        // cluster (a letter and its marks) moves as one.
1219                        let cluster = start + g.cluster as usize;
1220                        let new_cluster = previous.is_some_and(|p| row.is_none() || p != g.cluster);
1221                        if new_cluster && (spaced || row.is_none()) {
1222                            track += 1;
1223                        }
1224                        if new_cluster {
1225                            let at_space = text[cluster..].chars().next().is_some_and(char::is_whitespace);
1226                            let after_space = out.last().is_some_and(|l: &LineGlyph| {
1227                                text[l.cluster..].chars().next().is_some_and(char::is_whitespace)
1228                            });
1229                            if !whole || at_space || after_space {
1230                                unit += 1;
1231                            }
1232                        }
1233                        previous = Some(g.cluster);
1234                        out.push(LineGlyph {
1235                            font: face,
1236                            id: g.id,
1237                            x: pen + g.x as f64 * scale,
1238                            y: g.y as f64 * scale,
1239                            advance: g.advance as f64 * scale,
1240                            cluster,
1241                            scale,
1242                            track,
1243                            unit,
1244                            upright: row.is_some(),
1245                        });
1246                    }
1247                    pen += shaped.advance as f64 * scale;
1248                }
1249            }
1250        }
1251        // Reading order: a right-to-left line reveals from its right.
1252        if unicode_bidi::get_base_direction(text) == unicode_bidi::Direction::Rtl {
1253            let last = out.iter().map(|g| g.unit).max().unwrap_or(0);
1254            for g in &mut out {
1255                g.unit = last - g.unit;
1256            }
1257        }
1258        Ok((out, pen))
1259    }
1260
1261    /// Stretches of `text[range]` (in logical order) by the face that sets
1262    /// them: (face, script row, start, end).
1263    fn script_pieces(
1264        &mut self,
1265        primary: fontdb::ID,
1266        text: &str,
1267        range: std::ops::Range<usize>,
1268    ) -> Result<Vec<(fontdb::ID, Option<usize>, usize, usize)>, String> {
1269        let chars: Vec<(usize, char)> = text[range.clone()]
1270            .char_indices()
1271            .map(|(i, c)| (i + range.start, c))
1272            .collect();
1273        let mut pieces: Vec<(fontdb::ID, Option<usize>, usize, usize)> = Vec::new();
1274        // The face for the stretch of one script being read, and where it ends.
1275        let mut stretch: Option<(usize, fontdb::ID)> = None;
1276        for (index, &(at, c)) in chars.iter().enumerate() {
1277            let end = at + c.len_utf8();
1278            let next = chars.get(index + 1).map(|&(_, n)| n);
1279            let row = self.script_row(c);
1280            let neutral = matches!(c.script(), Script::Common | Script::Inherited | Script::Unknown);
1281            let (face, face_row) = if let Some(e) = emoji_presentation(c, next).then(|| self.emoji_face(c)).flatten() {
1282                (e, None)
1283            } else if let Some(r) = row {
1284                let face = match stretch {
1285                    Some((until, face)) if index < until => face,
1286                    _ => {
1287                        // The stretch runs to the next letter of another script.
1288                        let until = chars[index..]
1289                            .iter()
1290                            .position(|&(_, n)| {
1291                                self.script_row(n) != Some(r)
1292                                    && !matches!(n.script(), Script::Common | Script::Inherited | Script::Unknown)
1293                            })
1294                            .map_or(chars.len(), |p| index + p);
1295                        // A font that has every letter of it sets it itself.
1296                        let mut own = true;
1297                        for &(_, n) in &chars[index..until] {
1298                            if self.script_row(n) == Some(r) && !self.has_glyph(primary, n) {
1299                                own = false;
1300                                break;
1301                            }
1302                        }
1303                        let face = if own { primary } else { self.script_face(primary, r)? };
1304                        stretch = Some((until, face));
1305                        face
1306                    }
1307                };
1308                // A letter even the stand-in lacks still gets a glyph.
1309                if self.has_glyph(face, c) {
1310                    (face, (face != primary).then_some(r))
1311                } else {
1312                    (self.fallback_for(c).unwrap_or(face), Some(r))
1313                }
1314            } else if neutral {
1315                // Spaces, digits, punctuation and marks stay with what they
1316                // are next to when its face can draw them.
1317                match pieces.last() {
1318                    Some(&(face, r, _, _))
1319                        if c.is_whitespace()
1320                            || c.is_control()
1321                            || attaches(c)
1322                            || c == '\u{200C}'
1323                            || self.has_glyph(face, c) =>
1324                    {
1325                        (face, r)
1326                    }
1327                    _ => {
1328                        let ahead = chars[index + 1..]
1329                            .iter()
1330                            .find(|&&(_, n)| {
1331                                !matches!(n.script(), Script::Common | Script::Inherited | Script::Unknown)
1332                            })
1333                            .and_then(|&(_, n)| self.script_row(n));
1334                        let candidate = match ahead {
1335                            Some(r) => Some((self.script_face(primary, r)?, r)),
1336                            None => None,
1337                        };
1338                        match candidate {
1339                            Some((face, r)) if self.has_glyph(face, c) && !self.has_glyph(primary, c) => {
1340                                (face, Some(r))
1341                            }
1342                            _ if c.is_whitespace() || c.is_control() || self.has_glyph(primary, c) => (primary, None),
1343                            _ => (self.fallback_for(c).unwrap_or(primary), None),
1344                        }
1345                    }
1346                }
1347            } else if self.has_glyph(primary, c) {
1348                (primary, None)
1349            } else {
1350                (self.fallback_for(c).unwrap_or(primary), None)
1351            };
1352            match pieces.last_mut() {
1353                Some(last) if last.0 == face && last.1 == face_row => last.3 = end,
1354                _ => pieces.push((face, face_row, at, end)),
1355            }
1356        }
1357        Ok(pieces)
1358    }
1359
1360    fn shape(
1361        &mut self,
1362        id: fontdb::ID,
1363        text: &str,
1364        features: &[rustybuzz::Feature],
1365        vars: &[rustybuzz::Variation],
1366        direction: Option<rustybuzz::Direction>,
1367        language: Option<&str>,
1368    ) -> Result<Arc<ShapedLine>, String> {
1369        let mut h = std::collections::hash_map::DefaultHasher::new();
1370        id.hash(&mut h);
1371        text.hash(&mut h);
1372        if direction.is_some() || language.is_some() {
1373            format!("{direction:?}{language:?}").hash(&mut h);
1374        }
1375        for f in features {
1376            format!("{f:?}").hash(&mut h);
1377        }
1378        variations_key(vars).hash(&mut h);
1379        let key = h.finish();
1380        if let Some(s) = self.shaped.get(&key) {
1381            return Ok(s);
1382        }
1383        let (data, index) = self.face_data(id)?;
1384        let mut face = rustybuzz::Face::from_slice(&data, index).ok_or("unparseable font")?;
1385        if !vars.is_empty() {
1386            face.set_variations(vars);
1387        }
1388        let mut buf = rustybuzz::UnicodeBuffer::new();
1389        buf.push_str(text);
1390        buf.guess_segment_properties();
1391        if let Some(direction) = direction {
1392            buf.set_direction(direction);
1393        }
1394        if let Some(language) = language.and_then(|l| l.parse().ok()) {
1395            buf.set_language(language);
1396        }
1397        let out = rustybuzz::shape(&face, features, buf);
1398        let mut pos: Vec<(i32, i32, i32)> = out
1399            .glyph_positions()
1400            .iter()
1401            .map(|p| (p.x_advance, p.x_offset, p.y_offset))
1402            .collect();
1403        let kerning = !features
1404            .iter()
1405            .any(|f| f.tag == rustybuzz::ttf_parser::Tag::from_bytes(b"kern") && f.value == 0);
1406        if kerning {
1407            kerx_pairs(&face, out.glyph_infos(), &mut pos);
1408        }
1409        let mut pen = 0.0f32;
1410        let mut glyphs = Vec::with_capacity(out.len());
1411        for (info, &(adv, xo, yo)) in out.glyph_infos().iter().zip(&pos) {
1412            glyphs.push(ShapedGlyph {
1413                id: info.glyph_id as u16,
1414                x: pen + xo as f32,
1415                y: yo as f32,
1416                advance: adv as f32,
1417                cluster: info.cluster,
1418            });
1419            pen += adv as f32;
1420        }
1421        let line = Arc::new(ShapedLine { glyphs, advance: pen });
1422        self.shaped.insert(key, line.clone());
1423        Ok(line)
1424    }
1425
1426    /// Glyph outline in font units, y up.
1427    fn glyph(&mut self, id: fontdb::ID, glyph: u16, vars: &[rustybuzz::Variation]) -> Result<Arc<BezPath>, String> {
1428        let vkey = variations_key(vars);
1429        if let Some(p) = self.glyphs.get(&(id, glyph, vkey)) {
1430            return Ok(p);
1431        }
1432        let (data, index) = self.face_data(id)?;
1433        let mut face = rustybuzz::Face::from_slice(&data, index).ok_or("unparseable font")?;
1434        if !vars.is_empty() {
1435            face.set_variations(vars);
1436        }
1437        struct B(BezPath);
1438        impl rustybuzz::ttf_parser::OutlineBuilder for B {
1439            fn move_to(&mut self, x: f32, y: f32) {
1440                self.0.move_to((x as f64, y as f64));
1441            }
1442            fn line_to(&mut self, x: f32, y: f32) {
1443                self.0.line_to((x as f64, y as f64));
1444            }
1445            fn quad_to(&mut self, x1: f32, y1: f32, x: f32, y: f32) {
1446                self.0.quad_to((x1 as f64, y1 as f64), (x as f64, y as f64));
1447            }
1448            fn curve_to(&mut self, x1: f32, y1: f32, x2: f32, y2: f32, x: f32, y: f32) {
1449                self.0
1450                    .curve_to((x1 as f64, y1 as f64), (x2 as f64, y2 as f64), (x as f64, y as f64));
1451            }
1452            fn close(&mut self) {
1453                self.0.close_path();
1454            }
1455        }
1456        let mut b = B(BezPath::new());
1457        face.outline_glyph(rustybuzz::ttf_parser::GlyphId(glyph), &mut b);
1458        let p = Arc::new(b.0);
1459        self.glyphs.insert((id, glyph, vkey), p.clone());
1460        Ok(p)
1461    }
1462}
1463
1464impl Default for Fonts {
1465    fn default() -> Self {
1466        Self::new()
1467    }
1468}
1469
1470struct Reader<'a> {
1471    id: &'a str,
1472    node: &'a Node,
1473    t: f64,
1474}
1475
1476impl Reader<'_> {
1477    fn vecn(&self, name: &str, default: &[f64]) -> ultrafast_graph::Vals {
1478        let mut v = self
1479            .node
1480            .params
1481            .get(name)
1482            .and_then(|p| p.eval_vals(self.t))
1483            .unwrap_or_else(|| ultrafast_graph::Vals::from_slice(default));
1484        // Broadcast a scalar to the expected width; pad or truncate otherwise.
1485        if v.len() == 1 && default.len() > 1 {
1486            v = ultrafast_graph::Vals::filled(v[0], default.len());
1487        }
1488        v.resize(default.len(), 0.0);
1489        v
1490    }
1491    fn num(&self, name: &str, default: f64) -> f64 {
1492        self.vecn(name, &[default])[0]
1493    }
1494    fn text(&self, name: &str) -> Option<&str> {
1495        text(self.node, name)
1496    }
1497    fn bad(&self, param: &str, reason: impl Into<String>) -> GeomError {
1498        GeomError::BadParam {
1499            node: self.id.to_string(),
1500            param: param.to_string(),
1501            reason: reason.into(),
1502        }
1503    }
1504}
1505
1506/// The node's own placement: position, anchor, scale, rotation (degrees).
1507/// Unlike the `transform` op, geometry stays vector until rasterization.
1508fn placement(r: &Reader, default_anchor: [f64; 2]) -> Affine {
1509    let pos = r.vecn("position", &default_anchor);
1510    let anchor = r.vecn("anchor", &default_anchor);
1511    let scale = r.vecn("scale", &[1.0, 1.0]);
1512    let rot = r.num("rotation", 0.0).to_radians();
1513    Affine::translate(pos[0], pos[1])
1514        .mul(Affine::rotate(rot))
1515        .mul(Affine::scale(scale[0], scale[1]))
1516        .mul(Affine::translate(-anchor[0], -anchor[1]))
1517}
1518
1519fn to_kurbo(a: Affine) -> kurbo::Affine {
1520    kurbo::Affine::new(a.0)
1521}
1522
1523fn stroke_style(r: &Reader) -> Result<Option<kurbo::Stroke>, GeomError> {
1524    let width = r.num("stroke", 0.0);
1525    if width <= 0.0 {
1526        return Ok(None);
1527    }
1528    let join = match r.text("join").unwrap_or("miter") {
1529        "miter" => kurbo::Join::Miter,
1530        "round" => kurbo::Join::Round,
1531        "bevel" => kurbo::Join::Bevel,
1532        o => return Err(r.bad("join", format!("unknown join `{o}`"))),
1533    };
1534    let cap = match r.text("cap").unwrap_or("butt") {
1535        "butt" => kurbo::Cap::Butt,
1536        "round" => kurbo::Cap::Round,
1537        "square" => kurbo::Cap::Square,
1538        o => return Err(r.bad("cap", format!("unknown cap `{o}`"))),
1539    };
1540    let mut s = kurbo::Stroke::new(width).with_join(join).with_caps(cap);
1541    if let Some(dash) = r.node.params.get("dash").and_then(|p| p.eval(r.t))
1542        && !dash.is_empty()
1543        && dash.iter().any(|d| *d > 0.0)
1544    {
1545        s = s.with_dashes(r.num("dash_offset", 0.0), dash);
1546    }
1547    Ok(Some(s))
1548}
1549
1550/// Keeps the part of `path` between fractions `a` and `b` of its length.
1551fn trim(path: &BezPath, a: f64, b: f64) -> BezPath {
1552    let (a, b) = (a.clamp(0.0, 1.0), b.clamp(0.0, 1.0));
1553    if a <= 0.0 && b >= 1.0 {
1554        return path.clone();
1555    }
1556    let segs: Vec<kurbo::PathSeg> = path.segments().collect();
1557    let lens: Vec<f64> = segs.iter().map(|s| s.arclen(1e-3)).collect();
1558    let total: f64 = lens.iter().sum();
1559    let (from, to) = (a * total, b * total);
1560    let mut out = BezPath::new();
1561    let mut acc = 0.0;
1562    let mut last_end: Option<Point> = None;
1563    for (seg, len) in segs.iter().zip(&lens) {
1564        let (s0, s1) = (acc, acc + len);
1565        acc = s1;
1566        if s1 <= from || s0 >= to || *len <= 0.0 {
1567            continue;
1568        }
1569        let t0 = if from > s0 {
1570            seg.inv_arclen(from - s0, 1e-4)
1571        } else {
1572            0.0
1573        };
1574        let t1 = if to < s1 { seg.inv_arclen(to - s0, 1e-4) } else { 1.0 };
1575        let sub = seg.subsegment(t0..t1);
1576        if last_end.is_none_or(|p| p.distance(sub.start()) > 1e-6) {
1577            out.move_to(sub.start());
1578        }
1579        match sub {
1580            kurbo::PathSeg::Line(l) => out.line_to(l.p1),
1581            kurbo::PathSeg::Quad(q) => out.quad_to(q.p1, q.p2),
1582            kurbo::PathSeg::Cubic(c) => out.curve_to(c.p1, c.p2, c.p3),
1583        }
1584        last_end = Some(sub.end());
1585    }
1586    out
1587}
1588
1589fn preset_path(r: &Reader, kind: &str, fmt: &Format) -> Result<BezPath, GeomError> {
1590    let c = r.vecn("center", &[fmt.width as f64 / 2.0, fmt.height as f64 / 2.0]);
1591    let radius = r.num("radius", fmt.height as f64 / 4.0);
1592    let mut p = BezPath::new();
1593    match kind {
1594        "polygon" | "star" => {
1595            let sides = r.num("sides", if kind == "star" { 5.0 } else { 6.0 }).round().max(3.0) as usize;
1596            let inner = r.num("inner_radius", radius * 0.45);
1597            let n = if kind == "star" { sides * 2 } else { sides };
1598            for i in 0..n {
1599                let a = -std::f64::consts::FRAC_PI_2 + i as f64 * std::f64::consts::TAU / n as f64;
1600                let rr = if kind == "star" && i % 2 == 1 { inner } else { radius };
1601                let pt = (c[0] + rr * a.cos(), c[1] + rr * a.sin());
1602                if i == 0 {
1603                    p.move_to(pt);
1604                } else {
1605                    p.line_to(pt);
1606                }
1607            }
1608            p.close_path();
1609        }
1610        "circle" => p = kurbo::Circle::new((c[0], c[1]), radius).to_path(0.01),
1611        "line" => {
1612            let pts = r.vecn("points", &[0.0, 0.0, 100.0, 100.0]);
1613            p.move_to((pts[0], pts[1]));
1614            p.line_to((pts[2], pts[3]));
1615        }
1616        "polyline" | "polygon_points" => {
1617            let pts = r
1618                .node
1619                .params
1620                .get("points")
1621                .and_then(|p| p.eval(r.t))
1622                .unwrap_or_default();
1623            for (i, xy) in pts.chunks_exact(2).enumerate() {
1624                if i == 0 {
1625                    p.move_to((xy[0], xy[1]));
1626                } else {
1627                    p.line_to((xy[0], xy[1]));
1628                }
1629            }
1630            if kind == "polygon_points" {
1631                p.close_path();
1632            }
1633        }
1634        o => return Err(r.bad("kind", format!("unknown path kind `{o}`"))),
1635    }
1636    Ok(p)
1637}
1638
1639/// Builds the geometry of a `path` node under `outer` (absorbed transforms).
1640pub fn path(id: &str, node: &Node, fmt: &Format, t: f64, outer: Affine) -> Result<Geometry, GeomError> {
1641    let r = Reader { id, node, t };
1642    let local = match (r.text("d"), r.text("kind")) {
1643        (Some(d), _) => BezPath::from_svg(d).map_err(|e| r.bad("d", format!("invalid SVG path data: {e}")))?,
1644        (None, Some(kind)) => preset_path(&r, kind, fmt)?,
1645        (None, None) => return Err(r.bad("d", "path needs `d` (SVG path data) or `kind`")),
1646    };
1647    // Shape morphing toward `to` (another path's data).
1648    let local = match r.text("to") {
1649        // Several targets (`|`-separated): `morph` runs 0..n through them.
1650        Some(to) => {
1651            // Only the two shapes `morph` is between are parsed.
1652            let n = to.matches('|').count() + 2;
1653            let m = r.num("morph", 0.0).clamp(0.0, (n - 1) as f64);
1654            let k = (m.floor() as usize).min(n - 2);
1655            let f = m - k as f64;
1656            let shape = |i: usize| -> Result<BezPath, GeomError> {
1657                if i == 0 {
1658                    return Ok(local.clone());
1659                }
1660                let part = to.split('|').nth(i - 1).unwrap_or("");
1661                BezPath::from_svg(part.trim()).map_err(|e| r.bad("to", format!("invalid SVG path data: {e}")))
1662            };
1663            if f <= 0.0 {
1664                shape(k)?
1665            } else {
1666                morph(&shape(k)?, &shape(k + 1)?, f)
1667            }
1668        }
1669        None => local,
1670    };
1671    let local = trim(&local, r.num("trim_start", 0.0), r.num("trim_end", 1.0));
1672    let xf = outer.mul(placement(&r, [0.0, 0.0]));
1673    let mut g = Geometry::empty();
1674    match stroke_style(&r)? {
1675        Some(style) => {
1676            // Stroke in local space so width scales with the transform.
1677            let outline = kurbo::stroke(local.iter(), &style, &kurbo::StrokeOpts::default(), TOLERANCE * 0.25);
1678            flatten_closed(&(to_kurbo(xf) * outline), 1.0, 0, &mut g);
1679        }
1680        None => flatten_closed(&(to_kurbo(xf) * local), 1.0, 0, &mut g),
1681    }
1682    Ok(g)
1683}
1684
1685/// The variable-font instance for a `text` node: `weight` drives the
1686/// `wght` axis (so weight animates smoothly), the optical size axis follows
1687/// the type's size in px (as browsers do: display cuts for big type, sturdy
1688/// ones for small), `variations` sets axes by tag (`"wdth=80, opsz=144"`),
1689/// and `axis_<tag>` params set one axis each, animatable (`axis_wdth`,
1690/// `axis_SOFT`). Values are clamped to the font's ranges; static fonts get
1691/// none.
1692fn font_variations(
1693    r: &Reader,
1694    fonts: &mut Fonts,
1695    font: fontdb::ID,
1696    weight: f64,
1697    size: f64,
1698) -> Result<Variations, GeomError> {
1699    let axes = fonts.axes(font).map_err(|e| r.bad("font", e))?;
1700    if axes.is_empty() {
1701        return Ok(Vec::new());
1702    }
1703    let mut set: Vec<([u8; 4], f64)> = Vec::new();
1704    if axes.iter().any(|a| &a.0 == b"wght") {
1705        set.push((*b"wght", weight));
1706    }
1707    if axes.iter().any(|a| &a.0 == b"opsz") {
1708        set.push((*b"opsz", size));
1709    }
1710    let tag_of = |s: &str| -> Option<[u8; 4]> {
1711        let b = s.trim().as_bytes();
1712        (!b.is_empty() && b.len() <= 4).then(|| std::array::from_fn(|i| *b.get(i).unwrap_or(&b' ')))
1713    };
1714    if let Some(spec) = r.text("variations") {
1715        for part in spec.split(',').filter(|p| !p.trim().is_empty()) {
1716            let (tag, value) = part
1717                .split_once('=')
1718                .and_then(|(t, v)| Some((tag_of(t)?, v.trim().parse::<f64>().ok()?)))
1719                .ok_or_else(|| r.bad("variations", format!("`{part}` is not tag=value")))?;
1720            set.push((tag, value));
1721        }
1722    }
1723    for (name, _) in r.node.params.iter().filter(|(k, _)| k.starts_with("axis_")) {
1724        let tag = tag_of(&name[5..]).ok_or_else(|| r.bad(name, "axis tags are 1-4 characters"))?;
1725        let def = axes.iter().find(|a| a.0 == tag).map(|a| a.2 as f64).unwrap_or(0.0);
1726        set.push((tag, r.num(name, def)));
1727    }
1728    let mut out: Variations = Vec::new();
1729    for (tag, value) in set {
1730        let Some(axis) = axes.iter().find(|a| a.0 == tag) else {
1731            continue;
1732        };
1733        let v = (value as f32).clamp(axis.1, axis.3);
1734        out.retain(|x| x.tag.to_bytes() != tag);
1735        out.push(rustybuzz::Variation {
1736            tag: rustybuzz::ttf_parser::Tag::from_bytes(&tag),
1737            value: v,
1738        });
1739    }
1740    Ok(out)
1741}
1742
1743/// Text params evaluated per glyph at its staggered time.
1744const GLYPH_ANIMATORS: [&str; 4] = ["glyph_offset", "glyph_scale", "glyph_rotation", "glyph_opacity"];
1745
1746/// Closed polylines of a path's subpaths.
1747fn polylines(p: &BezPath) -> Vec<Vec<Point>> {
1748    let mut out: Vec<Vec<Point>> = Vec::new();
1749    let mut cur: Vec<Point> = Vec::new();
1750    kurbo::flatten(p.iter(), 0.2, |el| match el {
1751        PathEl::MoveTo(q) => {
1752            if cur.len() > 1 {
1753                out.push(std::mem::take(&mut cur));
1754            }
1755            cur.clear();
1756            cur.push(q);
1757        }
1758        PathEl::LineTo(q) => cur.push(q),
1759        PathEl::ClosePath => {
1760            if cur.len() > 1 {
1761                out.push(std::mem::take(&mut cur));
1762            }
1763        }
1764        _ => {}
1765    });
1766    if cur.len() > 1 {
1767        out.push(cur);
1768    }
1769    out
1770}
1771
1772fn signed_area(c: &[Point]) -> f64 {
1773    (0..c.len())
1774        .map(|i| {
1775            let (a, b) = (c[i], c[(i + 1) % c.len()]);
1776            a.x * b.y - b.x * a.y
1777        })
1778        .sum::<f64>()
1779        / 2.0
1780}
1781
1782/// `n` points evenly spaced along the closed polyline.
1783fn resample(c: &[Point], n: usize) -> Vec<Point> {
1784    let len: Vec<f64> = (0..c.len()).map(|i| c[i].distance(c[(i + 1) % c.len()])).collect();
1785    let total: f64 = len.iter().sum::<f64>().max(1e-9);
1786    let mut out = Vec::with_capacity(n);
1787    let (mut seg, mut acc) = (0usize, 0.0f64);
1788    for k in 0..n {
1789        let target = total * k as f64 / n as f64;
1790        while seg < c.len() - 1 && acc + len[seg] < target {
1791            acc += len[seg];
1792            seg += 1;
1793        }
1794        let u = if len[seg] > 0.0 {
1795            ((target - acc) / len[seg]).clamp(0.0, 1.0)
1796        } else {
1797            0.0
1798        };
1799        out.push(c[seg].lerp(c[(seg + 1) % c.len()], u));
1800    }
1801    out
1802}
1803
1804/// Morphs `a` into `b` at `m` (0..1): contours are paired largest to
1805/// largest (missing partners grow from a point), resampled to matching
1806/// point counts, wound the same way and rotated to line up, then blended.
1807pub fn morph(a: &BezPath, b: &BezPath, m: f64) -> BezPath {
1808    if m <= 0.0 {
1809        return a.clone();
1810    }
1811    if m >= 1.0 {
1812        return b.clone();
1813    }
1814    // Paths built alike (same commands in the same order) interpolate point
1815    // for point: exact, and how Lottie and most editors morph.
1816    let (ea, eb) = (a.elements(), b.elements());
1817    if ea.len() == eb.len()
1818        && ea
1819            .iter()
1820            .zip(eb)
1821            .all(|(x, y)| std::mem::discriminant(x) == std::mem::discriminant(y))
1822    {
1823        let l = |p: Point, q: Point| p.lerp(q, m);
1824        let mut out = BezPath::new();
1825        for (x, y) in ea.iter().zip(eb) {
1826            match (x, y) {
1827                (PathEl::MoveTo(p), PathEl::MoveTo(q)) => out.move_to(l(*p, *q)),
1828                (PathEl::LineTo(p), PathEl::LineTo(q)) => out.line_to(l(*p, *q)),
1829                (PathEl::QuadTo(p1, p2), PathEl::QuadTo(q1, q2)) => out.quad_to(l(*p1, *q1), l(*p2, *q2)),
1830                (PathEl::CurveTo(p1, p2, p3), PathEl::CurveTo(q1, q2, q3)) => {
1831                    out.curve_to(l(*p1, *q1), l(*p2, *q2), l(*p3, *q3))
1832                }
1833                _ => out.close_path(),
1834            }
1835        }
1836        return out;
1837    }
1838    let by_size = |p: &BezPath| {
1839        let mut v = polylines(p);
1840        v.sort_by(|x, y| signed_area(y).abs().partial_cmp(&signed_area(x).abs()).unwrap());
1841        v
1842    };
1843    let (ca, cb) = (by_size(a), by_size(b));
1844    let centroid = |c: &[Point]| {
1845        let n = c.len().max(1) as f64;
1846        Point::new(
1847            c.iter().map(|p| p.x).sum::<f64>() / n,
1848            c.iter().map(|p| p.y).sum::<f64>() / n,
1849        )
1850    };
1851    let mut out = BezPath::new();
1852    for i in 0..ca.len().max(cb.len()) {
1853        let (pa, pb) = match (ca.get(i), cb.get(i)) {
1854            (Some(x), Some(y)) => (x.clone(), y.clone()),
1855            (Some(x), None) => (x.clone(), vec![centroid(x); 3]),
1856            (None, Some(y)) => (vec![centroid(y); 3], y.clone()),
1857            (None, None) => unreachable!(),
1858        };
1859        let perim = |c: &[Point]| (0..c.len()).map(|k| c[k].distance(c[(k + 1) % c.len()])).sum::<f64>();
1860        let n = ((perim(&pa).max(perim(&pb)) / 3.0) as usize).clamp(48, 600);
1861        let ra = resample(&pa, n);
1862        let mut rb = resample(&pb, n);
1863        if signed_area(&ra) * signed_area(&rb) < 0.0 {
1864            rb.reverse();
1865        }
1866        // The rotation of b that best lines up with a.
1867        let step = (n / 120).max(1);
1868        let best = (0..n)
1869            .step_by(step)
1870            .min_by(|&x, &y| {
1871                let cost = |o: usize| {
1872                    (0..n)
1873                        .step_by(step)
1874                        .map(|k| ra[k].distance_squared(rb[(k + o) % n]))
1875                        .sum::<f64>()
1876                };
1877                cost(x).partial_cmp(&cost(y)).unwrap()
1878            })
1879            .unwrap_or(0);
1880        for k in 0..n {
1881            let p = ra[k].lerp(rb[(k + best) % n], m);
1882            if k == 0 {
1883                out.move_to(p);
1884            } else {
1885                out.line_to(p);
1886            }
1887        }
1888        out.close_path();
1889    }
1890    out
1891}
1892
1893/// Glyph outlines of a `text` node, positioned in output space (laid out,
1894/// revealed, stroked), each with its reveal weight.
1895/// Paths of a text node, each with its weight (reveal and glyph opacity)
1896/// and color group, and the colors of the groups (see [`Geometry::groups`]).
1897pub type TextPaths = (Vec<(BezPath, f32, u32)>, Vec<Option<[f32; 4]>>);
1898
1899/// At most this many differently colored layers in one text node; more
1900/// colors share the last.
1901const MAX_GROUPS: usize = 16;
1902
1903/// The style of a run of rich text, resolved to a face.
1904#[derive(Clone)]
1905struct RunStyle {
1906    font: fontdb::ID,
1907    size: f64,
1908    vars: Variations,
1909    /// Synthetic oblique (tangent of the slant) for an italic the face lacks.
1910    slant: f64,
1911    /// Linear straight alpha; None is the node's own color.
1912    color: Option<[f32; 4]>,
1913    highlight: Option<[f32; 4]>,
1914    underline: f64,
1915    underline_color: Option<[f32; 4]>,
1916    rise: f64,
1917    /// How much of the highlight and underline is drawn, from the left.
1918    draw: f64,
1919}
1920
1921/// A style before resolution: what the node, the `em_*` params or a span
1922/// set (unset fields inherit).
1923#[derive(Clone, Default)]
1924struct StyleSpec {
1925    font: Option<String>,
1926    weight: Option<f64>,
1927    italic: Option<bool>,
1928    size: Option<f64>,
1929    color: Option<[f32; 4]>,
1930    highlight: Option<[f32; 4]>,
1931    underline: Option<f64>,
1932    underline_color: Option<[f32; 4]>,
1933    rise: Option<f64>,
1934    draw: Option<f64>,
1935}
1936
1937impl StyleSpec {
1938    fn over(&self, o: &StyleSpec) -> StyleSpec {
1939        StyleSpec {
1940            font: o.font.clone().or_else(|| self.font.clone()),
1941            weight: o.weight.or(self.weight),
1942            italic: o.italic.or(self.italic),
1943            size: o.size.or(self.size),
1944            color: o.color.or(self.color),
1945            highlight: o.highlight.or(self.highlight),
1946            underline: o.underline.or(self.underline),
1947            underline_color: o.underline_color.or(self.underline_color),
1948            rise: o.rise.or(self.rise),
1949            draw: o.draw.or(self.draw),
1950        }
1951    }
1952}
1953
1954/// Attributes a `[text]{...}` span takes.
1955pub const SPAN_ATTRS: &[&str] = &[
1956    "color",
1957    "font",
1958    "weight",
1959    "style",
1960    "size",
1961    "highlight",
1962    "underline",
1963    "underline_color",
1964    "rise",
1965    "draw",
1966];
1967
1968fn linear_color(c: [f64; 4]) -> [f32; 4] {
1969    let l = |x: f64| crate::srgb_to_linear(x) as f32;
1970    [l(c[0]), l(c[1]), l(c[2]), c[3].clamp(0.0, 1.0) as f32]
1971}
1972
1973impl Reader<'_> {
1974    /// A color param as linear straight alpha.
1975    fn color(&self, name: &str) -> Result<Option<[f32; 4]>, GeomError> {
1976        let c = match self.node.params.get(name) {
1977            None => return Ok(None),
1978            Some(Param::Text(s)) => crate::parse_hex(s)
1979                .ok_or_else(|| self.bad(name, format!("`{s}` is not a #rgb, #rrggbb or #rrggbbaa color")))?,
1980            Some(p) => {
1981                let v = p.eval(self.t).unwrap_or_default();
1982                match v.len() {
1983                    3 => [v[0], v[1], v[2], 1.0],
1984                    4 => [v[0], v[1], v[2], v[3]],
1985                    _ => return Err(self.bad(name, "color needs 3 or 4 components")),
1986                }
1987            }
1988        };
1989        Ok(Some(linear_color(c)))
1990    }
1991    fn opt(&self, name: &str) -> Option<f64> {
1992        self.node.params.contains_key(name).then(|| self.num(name, 0.0))
1993    }
1994}
1995
1996/// The emphasis style of `*words*`: the `em_*` params, or italic when
1997/// none is set.
1998fn em_spec(r: &Reader) -> Result<StyleSpec, GeomError> {
1999    let set = r.node.params.keys().any(|k| k.starts_with("em_"));
2000    Ok(StyleSpec {
2001        font: r.text("em_font").map(String::from),
2002        weight: r.opt("em_weight"),
2003        italic: match r.text("em_style") {
2004            Some(s) => Some(s == "italic"),
2005            None if !set => Some(true),
2006            None => None,
2007        },
2008        size: r.opt("em_size"),
2009        color: r.color("em_color")?,
2010        highlight: r.color("em_highlight")?,
2011        underline: r.opt("em_underline"),
2012        underline_color: r.color("em_underline_color")?,
2013        rise: r.opt("em_rise"),
2014        draw: r.opt("em_draw"),
2015    })
2016}
2017
2018fn attr_spec(r: &Reader, a: &std::collections::BTreeMap<String, String>) -> Result<StyleSpec, GeomError> {
2019    if let Some(k) = a.keys().find(|k| !SPAN_ATTRS.contains(&k.as_str())) {
2020        return Err(r.bad(
2021            "text",
2022            format!("unknown span attribute `{k}` ({})", SPAN_ATTRS.join(", ")),
2023        ));
2024    }
2025    let num = |k: &str| -> Result<Option<f64>, GeomError> {
2026        a.get(k)
2027            .map(|v| {
2028                v.parse::<f64>()
2029                    .map_err(|_| r.bad("text", format!("span `{k}={v}` is not a number")))
2030            })
2031            .transpose()
2032    };
2033    let col = |k: &str| -> Result<Option<[f32; 4]>, GeomError> {
2034        a.get(k)
2035            .map(|v| {
2036                crate::parse_hex(v).map(linear_color).ok_or_else(|| {
2037                    r.bad(
2038                        "text",
2039                        format!("span `{k}={v}` is not a #rgb, #rrggbb or #rrggbbaa color"),
2040                    )
2041                })
2042            })
2043            .transpose()
2044    };
2045    Ok(StyleSpec {
2046        font: a.get("font").cloned(),
2047        weight: match a.get("weight").map(String::as_str) {
2048            Some("bold") => Some(700.0),
2049            Some("regular" | "normal") => Some(400.0),
2050            _ => num("weight")?,
2051        },
2052        italic: a.get("style").map(|s| s == "italic"),
2053        size: num("size")?,
2054        color: col("color")?,
2055        highlight: col("highlight")?,
2056        // A bare `underline` is a hairline sized to the type.
2057        underline: match a.get("underline").map(String::as_str) {
2058            Some("true") => Some(-1.0),
2059            _ => num("underline")?,
2060        },
2061        underline_color: col("underline_color")?,
2062        rise: num("rise")?,
2063        draw: num("draw")?,
2064    })
2065}
2066
2067/// A text node's content as styled runs.
2068struct Rich {
2069    plain: String,
2070    /// (start, end, style) byte ranges of `plain`, in order.
2071    runs: Vec<(usize, usize, usize)>,
2072    /// Style 0 is the node's own.
2073    styles: Vec<RunStyle>,
2074    features: Vec<rustybuzz::Feature>,
2075    ascent: f64,
2076    descent: f64,
2077    size: f64,
2078}
2079
2080impl Rich {
2081    /// Glyphs of `plain[a..b]` laid out on one line, with their styles.
2082    fn shape(&self, fonts: &mut Fonts, a: usize, b: usize) -> Result<(Vec<(LineGlyph, usize)>, f64), String> {
2083        let mut out: Vec<(LineGlyph, usize)> = Vec::new();
2084        let mut pen = 0.0;
2085        // Styled spans of a right-to-left line run from its right.
2086        let rtl = fonts.reads_rtl(&self.plain[a..b]);
2087        let order: Vec<&(usize, usize, usize)> = if rtl {
2088            self.runs.iter().rev().collect()
2089        } else {
2090            self.runs.iter().collect()
2091        };
2092        for &&(rs, re, si) in &order {
2093            let (s, e) = (rs.max(a), re.min(b));
2094            if s >= e {
2095                continue;
2096            }
2097            let st = &self.styles[si];
2098            let (glyphs, adv) = fonts.layout(st.font, &self.plain[s..e], st.size, &self.features, &st.vars)?;
2099            let (track, unit) = out.last().map_or((0, 0), |(g, _)| (g.track + 1, g.unit + 1));
2100            for mut g in glyphs {
2101                g.x += pen;
2102                g.cluster += s;
2103                g.track += track;
2104                g.unit += unit;
2105                out.push((g, si));
2106            }
2107            pen += adv;
2108        }
2109        Ok((out, pen))
2110    }
2111}
2112
2113/// The text a node sets, with markup parsed into spans (`markup: false`
2114/// turns parsing off).
2115fn rich_content(r: &Reader) -> (String, Vec<crate::markup::Span>) {
2116    let raw = number_content(r).unwrap_or_else(|| r.text("text").unwrap_or("").to_string());
2117    let on = !matches!(r.node.params.get("markup"), Some(Param::Bool(false)));
2118    let (plain, mut spans) = if on && crate::markup::has_markup(&raw) {
2119        crate::markup::parse(&raw)
2120    } else {
2121        (raw, Vec::new())
2122    };
2123    let Some(p) = r
2124        .node
2125        .params
2126        .get("scramble")
2127        .and_then(|p| p.eval(r.t))
2128        .and_then(|v| v.first().copied())
2129    else {
2130        return (plain, spans);
2131    };
2132    // Scrambling swaps characters in place; spans follow them.
2133    let s = scramble(&plain, p, r);
2134    if !spans.is_empty() && s.len() != plain.len() {
2135        let bytes: Vec<usize> = s.char_indices().map(|(i, _)| i).chain([s.len()]).collect();
2136        let at = |b: usize| bytes[plain[..b].chars().count()];
2137        for sp in &mut spans {
2138            (sp.start, sp.end) = (at(sp.start), at(sp.end));
2139        }
2140    }
2141    (s, spans)
2142}
2143
2144/// What a `text` node shows at `t`, markup removed (for reading checks).
2145pub fn display_text(node: &Node, t: f64) -> String {
2146    rich_content(&Reader { id: "", node, t }).0
2147}
2148
2149/// Resolves a node's styled runs: `r` reads styles, `content` the text
2150/// (counters read it on the frame).
2151fn rich(r: &Reader, content: &Reader, fonts: &mut Fonts, base: &Path) -> Result<Rich, GeomError> {
2152    let (plain, spans) = rich_content(content);
2153    let size = r.num("size", 64.0);
2154    let base_spec = StyleSpec {
2155        font: Some(r.text("font").unwrap_or("").to_string()),
2156        weight: Some(r.num("weight", 400.0)),
2157        italic: Some(r.text("style") == Some("italic")),
2158        size: Some(size),
2159        rise: Some(0.0),
2160        draw: Some(1.0),
2161        ..Default::default()
2162    };
2163    let em = if spans.iter().any(|s| s.style == crate::markup::Style::Em) {
2164        Some(em_spec(r)?)
2165    } else {
2166        None
2167    };
2168    let resolve = |spec: &StyleSpec, fonts: &mut Fonts| -> Result<RunStyle, GeomError> {
2169        let weight = spec.weight.unwrap_or(400.0).clamp(1.0, 1000.0);
2170        let italic = spec.italic.unwrap_or(false);
2171        let name = spec.font.as_deref().unwrap_or("");
2172        let field = if spec.font == base_spec.font { "font" } else { "text" };
2173        let font = fonts
2174            .resolve(name, weight as u16, italic, base)
2175            .map_err(|e| r.bad(field, e))?;
2176        let size = spec.size.unwrap_or(size);
2177        let vars = font_variations(r, fonts, font, weight, size)?;
2178        Ok(RunStyle {
2179            font,
2180            size,
2181            vars,
2182            slant: if italic && !fonts.is_italic(font) { 0.2 } else { 0.0 },
2183            color: spec.color,
2184            highlight: spec.highlight,
2185            underline: match spec.underline {
2186                Some(v) if v < 0.0 => (size * 0.06).max(1.0),
2187                Some(v) => v,
2188                None => 0.0,
2189            },
2190            underline_color: spec.underline_color,
2191            rise: spec.rise.unwrap_or(0.0),
2192            draw: spec.draw.unwrap_or(1.0).clamp(0.0, 1.0),
2193        })
2194    };
2195    let mut styles = vec![resolve(&base_spec, fonts)?];
2196    let mut runs: Vec<(usize, usize, usize)> = Vec::new();
2197    if spans.is_empty() {
2198        runs.push((0, plain.len(), 0));
2199    } else {
2200        let mut cuts: Vec<usize> = spans.iter().flat_map(|s| [s.start, s.end]).collect();
2201        cuts.extend([0, plain.len()]);
2202        cuts.sort_unstable();
2203        cuts.dedup();
2204        let mut keys: Vec<Vec<usize>> = vec![Vec::new()];
2205        for w in cuts.windows(2) {
2206            let (a, b) = (w[0], w[1]);
2207            // Spans covering this piece, outermost first.
2208            let mut cover: Vec<usize> = (0..spans.len())
2209                .filter(|&i| spans[i].start <= a && spans[i].end >= b)
2210                .collect();
2211            cover.sort_by_key(|&i| std::cmp::Reverse(spans[i].end - spans[i].start));
2212            let si = match keys.iter().position(|k| *k == cover) {
2213                Some(si) => si,
2214                None => {
2215                    let mut spec = base_spec.clone();
2216                    for &i in &cover {
2217                        let s = match &spans[i].style {
2218                            crate::markup::Style::Em => em.clone().unwrap_or_default(),
2219                            crate::markup::Style::Attrs(a) => attr_spec(r, a)?,
2220                        };
2221                        spec = spec.over(&s);
2222                    }
2223                    styles.push(resolve(&spec, fonts)?);
2224                    keys.push(cover);
2225                    keys.len() - 1
2226                }
2227            };
2228            match runs.last_mut() {
2229                Some(last) if last.2 == si && last.1 == a => last.1 = b,
2230                _ => runs.push((a, b, si)),
2231            }
2232        }
2233    }
2234    let m = fonts.metrics(styles[0].font).map_err(|e| r.bad("font", e))?;
2235    let scale = size / m.units_per_em as f64;
2236    Ok(Rich {
2237        plain,
2238        runs,
2239        styles,
2240        features: text_features(r),
2241        ascent: m.ascender as f64 * scale,
2242        descent: -m.descender as f64 * scale,
2243        size,
2244    })
2245}
2246
2247pub fn text_paths(
2248    id: &str,
2249    node: &Node,
2250    fmt: &Format,
2251    t: f64,
2252    outer: Affine,
2253    fonts: &mut Fonts,
2254    base: &Path,
2255) -> Result<TextPaths, GeomError> {
2256    layout_text(id, node, fmt, t, outer, fonts, base).map(|(paths, _, _)| paths)
2257}
2258
2259/// A text node's glyph outlines and colors ([`text_paths`]) and its color
2260/// glyphs (emoji bitmaps), under `outer`.
2261pub fn text_layout(
2262    id: &str,
2263    node: &Node,
2264    fmt: &Format,
2265    t: f64,
2266    outer: Affine,
2267    fonts: &mut Fonts,
2268    base: &Path,
2269) -> Result<(TextPaths, Vec<GlyphImage>), GeomError> {
2270    layout_text(id, node, fmt, t, outer, fonts, base).map(|(paths, images, _)| (paths, images))
2271}
2272
2273/// [`text_layout`], and the glyph units laid out (what `reveal` counts).
2274fn layout_text(
2275    id: &str,
2276    node: &Node,
2277    fmt: &Format,
2278    t: f64,
2279    outer: Affine,
2280    fonts: &mut Fonts,
2281    base: &Path,
2282) -> Result<(TextPaths, Vec<GlyphImage>, usize), GeomError> {
2283    let r = Reader { id, node, t };
2284    // Counters change digits, they do not move: read the number on the
2285    // frame (motion-blur samples share it), so digits never smear.
2286    let on_frame = Reader {
2287        id,
2288        node,
2289        t: (t * fmt.fps).round() / fmt.fps,
2290    };
2291    let rich = rich(&r, &on_frame, fonts, base)?;
2292    let plain = rich.plain.as_str();
2293    let size = rich.size;
2294    let line_height = r.num("line_height", 1.2) * size * fonts.script_leading(plain);
2295    let tracking = r.num("tracking", 0.0);
2296    let wrap = r
2297        .node
2298        .params
2299        .get("width")
2300        .and_then(|p| p.eval(t))
2301        .and_then(|v| v.first().copied());
2302
2303    // Break into lines (byte ranges of the plain text): explicit newlines,
2304    // then greedy wrapping at Unicode line-break opportunities when a width
2305    // is set.
2306    let mut lines: Vec<(usize, usize)> = Vec::new();
2307    let mut para_start = 0;
2308    for para in plain.split('\n') {
2309        let p0 = para_start;
2310        para_start += para.len() + 1;
2311        let Some(width) = wrap else {
2312            lines.push((p0, p0 + para.len()));
2313            continue;
2314        };
2315        let mut start = 0;
2316        let mut last_ok: Option<usize> = None;
2317        for (pos, _) in unicode_linebreak::linebreaks(para) {
2318            let end = start + para[start..pos].trim_end().len();
2319            let (glyphs, adv) = rich.shape(fonts, p0 + start, p0 + end).map_err(|e| r.bad("text", e))?;
2320            let w = adv + tracking * glyphs.last().map_or(0, |g| g.0.track + 1) as f64;
2321            if w > width
2322                && let Some(ok) = last_ok
2323            {
2324                lines.push((p0 + start, p0 + start + para[start..ok].trim_end().len()));
2325                start = ok;
2326                last_ok = Some(pos);
2327                continue;
2328            }
2329            last_ok = Some(pos);
2330        }
2331        lines.push((p0 + start, p0 + start + para[start..].trim_end().len()));
2332    }
2333
2334    let align = r.text("align").unwrap_or("left");
2335    let valign = r.text("valign").unwrap_or("top");
2336    let (ascent, descent) = (rich.ascent, rich.descent);
2337    let block_h = ascent + descent + line_height * (lines.len().max(1) - 1) as f64;
2338    let first_baseline = match valign {
2339        "top" => ascent,
2340        "baseline" => 0.0,
2341        "middle" => ascent - block_h / 2.0,
2342        "bottom" => ascent - block_h,
2343        o => return Err(r.bad("valign", format!("unknown valign `{o}`"))),
2344    };
2345
2346    // Per-glyph reveal: glyph i has weight clamp((reveal - i) / softness).
2347    let total_glyphs: f64 = 1e9;
2348    let reveal = r.num("reveal", total_glyphs);
2349    let softness = r.num("reveal_softness", 1.0).max(1e-3);
2350    let reveal_offset = r.vecn("reveal_offset", &[0.0, 0.0]);
2351
2352    let xf = outer.mul(placement(&r, [0.0, 0.0]));
2353    let style = stroke_style(&r)?;
2354    // Output pixels per layout pixel: color glyphs pick their bitmap strike
2355    // by the size they appear at.
2356    let screen_scale = (xf.0[0] * xf.0[3] - xf.0[1] * xf.0[2]).abs().sqrt().max(1e-6);
2357    let mut images: Vec<GlyphImage> = Vec::new();
2358
2359    // Per-glyph animators: each glyph evaluates the glyph_* params at its
2360    // own time, t - stagger * (its place in stagger_order).
2361    let animated = GLYPH_ANIMATORS.iter().any(|p| r.node.params.contains_key(*p));
2362    let stagger = r.num("stagger", 0.0);
2363    let order_mode = r.text("stagger_order").unwrap_or("forward");
2364    let total = if animated {
2365        let mut n = 0;
2366        for &(a, b) in &lines {
2367            let shaped = rich.shape(fonts, a, b).map_err(|e| r.bad("text", e))?.0;
2368            n += shaped.iter().map(|g| g.0.unit as usize + 1).max().unwrap_or(0);
2369        }
2370        n
2371    } else {
2372        0
2373    };
2374    let order = |g: usize| -> f64 {
2375        match order_mode {
2376            "reverse" => (total.saturating_sub(1) - g.min(total.saturating_sub(1))) as f64,
2377            "center" => (g as f64 - (total as f64 - 1.0) / 2.0).abs(),
2378            "random" => {
2379                let mut x = (g as u32 ^ 0x9E37_79B9).wrapping_mul(0x85EB_CA6B);
2380                x ^= x >> 13;
2381                x = x.wrapping_mul(0xC2B2_AE35);
2382                x ^= x >> 16;
2383                (x as f64 / u32::MAX as f64 * total as f64).floor()
2384            }
2385            _ => g as f64,
2386        }
2387    };
2388    let at = |name: &str, tk: f64, default: &[f64]| -> Vec<f64> {
2389        let mut v = r
2390            .node
2391            .params
2392            .get(name)
2393            .and_then(|p| p.eval(tk))
2394            .unwrap_or_else(|| default.to_vec());
2395        if v.len() == 1 && default.len() > 1 {
2396            v = vec![v[0]; default.len()];
2397        }
2398        v.resize(default.len(), 0.0);
2399        v
2400    };
2401
2402    // Text on a path: each glyph's center rides the path (its baseline on
2403    // the path for valign baseline), turned to the path's direction.
2404    let on_path = match r.text("on_path") {
2405        Some(d) => Some(ArcPath::new(
2406            &BezPath::from_svg(d).map_err(|e| r.bad("on_path", format!("invalid SVG path data: {e}")))?,
2407        )),
2408        None => None,
2409    };
2410    let path_offset = r.num("path_offset", 0.0);
2411
2412    // Lay out every line first: marks (highlights, underlines) sweep
2413    // across lines in reading order.
2414    let mut laid: Vec<(Vec<(LineGlyph, usize)>, f64, f64)> = Vec::with_capacity(lines.len());
2415    for (li, &(la, lb)) in lines.iter().enumerate() {
2416        let (glyphs, adv) = rich.shape(fonts, la, lb).map_err(|e| r.bad("text", e))?;
2417        let width = adv + tracking * glyphs.last().map_or(0, |g| g.0.track) as f64;
2418        let x0 = match (align, &on_path) {
2419            ("left", None) => 0.0,
2420            ("center", None) => -width / 2.0,
2421            ("right", None) => -width,
2422            // Along a path, alignment is to the path's start, middle or end.
2423            ("left", Some(_)) => 0.0,
2424            ("center", Some(p)) => (p.length - width) / 2.0,
2425            ("right", Some(p)) => p.length - width,
2426            (o, _) => return Err(r.bad("align", format!("unknown align `{o}`"))),
2427        } + if on_path.is_some() { path_offset } else { 0.0 };
2428        laid.push((glyphs, x0, first_baseline + li as f64 * line_height));
2429    }
2430
2431    // Marks: runs of consecutive glyphs whose style highlights or
2432    // underlines, as (style, x from, x to, baseline).
2433    let mut marks: Vec<(usize, f64, f64, f64)> = Vec::new();
2434    if on_path.is_none() {
2435        for (glyphs, x0, baseline) in &laid {
2436            let mut prev: Option<usize> = None;
2437            for (gl, si) in glyphs {
2438                let st = &rich.styles[*si];
2439                if st.highlight.is_none() && st.underline <= 0.0 {
2440                    prev = None;
2441                    continue;
2442                }
2443                let gx = x0 + gl.x + tracking * gl.track as f64;
2444                match marks.last_mut() {
2445                    Some(m) if prev == Some(*si) => m.2 = gx + gl.advance,
2446                    _ => marks.push((*si, gx, gx + gl.advance, *baseline)),
2447                }
2448                prev = Some(*si);
2449            }
2450        }
2451    }
2452    // `draw` is the share of a style's marks drawn, as one stroke.
2453    let mut length: HashMap<usize, (f64, f64)> = HashMap::new();
2454    for &(si, xa, xb, _) in &marks {
2455        length.entry(si).or_default().0 += xb - xa;
2456    }
2457
2458    // Highlights go behind the type; glyphs and underlines in front.
2459    let mut back: Vec<(BezPath, [f32; 4])> = Vec::new();
2460    let mut front: Vec<(BezPath, f32, Option<[f32; 4]>)> = Vec::new();
2461    for &(si, xa, xb, baseline) in &marks {
2462        let st = &rich.styles[si];
2463        let (total, done) = length[&si];
2464        let d = ((st.draw * total - done) / (xb - xa).max(1e-9)).clamp(0.0, 1.0);
2465        length.get_mut(&si).unwrap().1 += xb - xa;
2466        if d <= 0.0 {
2467            continue;
2468        }
2469        let y = baseline - st.rise;
2470        if let Some(c) = st.highlight {
2471            let pad = st.size * 0.12;
2472            let (a, b) = (xa - pad, xb + pad);
2473            let rect =
2474                kurbo::RoundedRect::new(a, y - st.size * 0.8, a + (b - a) * d, y + st.size * 0.22, st.size * 0.1);
2475            back.push((to_kurbo(xf) * kurbo::Shape::to_path(&rect, 0.05), c));
2476        }
2477        if st.underline > 0.0 {
2478            let (th, uy) = (st.underline, y + st.size * 0.13);
2479            let rect = kurbo::RoundedRect::new(xa, uy - th / 2.0, xa + (xb - xa) * d, uy + th / 2.0, th / 2.0);
2480            front.push((
2481                to_kurbo(xf) * kurbo::Shape::to_path(&rect, 0.05),
2482                1.0,
2483                st.underline_color.or(st.color),
2484            ));
2485        }
2486    }
2487
2488    // Glyphs reveal and animate by their unit: the glyph itself in Latin text.
2489    let mut unit_base = 0usize;
2490    for (glyphs, x0, baseline) in &laid {
2491        let (x0, baseline) = (*x0, *baseline);
2492        let units = glyphs.iter().map(|g| g.0.unit as usize + 1).max().unwrap_or(0);
2493        // The span of a unit of several glyphs: it turns about its middle.
2494        let mut spans: HashMap<u32, (f64, f64, u32)> = HashMap::new();
2495        if animated {
2496            for (gl, _) in glyphs {
2497                let x = x0 + gl.x + tracking * gl.track as f64;
2498                let e = spans.entry(gl.unit).or_insert((x, x, 0));
2499                (e.0, e.1, e.2) = (e.0.min(x), e.1.max(x + gl.advance), e.2 + 1);
2500            }
2501        }
2502        for (gl, si) in glyphs {
2503            let st = &rich.styles[*si];
2504            let gi = unit_base + gl.unit as usize;
2505            let w = ((reveal - gi as f64) / softness).clamp(0.0, 1.0);
2506            if w <= 0.0 {
2507                continue;
2508            }
2509            let gv: &[rustybuzz::Variation] = if gl.font == st.font { &st.vars } else { &[] };
2510            let outline = fonts.glyph(gl.font, gl.id, gv).map_err(|e| r.bad("font", e))?;
2511            // Color glyphs (emoji) are drawn from their bitmaps (their
2512            // outlines, if any, are placeholders).
2513            let bitmap = if fonts.has_color_bitmaps(gl.font) {
2514                fonts.glyph_bitmap(gl.font, gl.id, st.size * screen_scale)
2515            } else {
2516                None
2517            };
2518            if bitmap.is_none() && outline.elements().is_empty() {
2519                continue;
2520            }
2521            let scale = gl.scale;
2522            let ox = x0 + gl.x + tracking * gl.track as f64 + reveal_offset[0] * (1.0 - w);
2523            let oy = baseline - gl.y - st.rise + reveal_offset[1] * (1.0 - w);
2524            let (anim, w) = if animated {
2525                let tk = r.t - stagger * order(gi);
2526                let off = at("glyph_offset", tk, &[0.0, 0.0]);
2527                let sc = at("glyph_scale", tk, &[1.0, 1.0]);
2528                let rot = at("glyph_rotation", tk, &[0.0])[0].to_radians();
2529                let op = at("glyph_opacity", tk, &[1.0])[0].clamp(0.0, 1.0);
2530                // About the glyph's own ink center.
2531                let bb = match &bitmap {
2532                    Some(b) => {
2533                        kurbo::Rect::new(b.place[0], b.place[1], b.place[0] + b.place[2], b.place[1] + b.place[3])
2534                    }
2535                    None => outline.bounding_box(),
2536                };
2537                let (cx, cy) = match spans.get(&gl.unit) {
2538                    Some(&(a, b, n)) if n > 1 => ((a + b) / 2.0, baseline - st.rise - st.size * 0.35),
2539                    _ => (ox + (bb.x0 + bb.x1) / 2.0 * scale, oy - (bb.y0 + bb.y1) / 2.0 * scale),
2540                };
2541                let a = Affine::translate(cx + off[0], cy + off[1])
2542                    .mul(Affine::rotate(rot))
2543                    .mul(Affine::scale(sc[0], sc[1]))
2544                    .mul(Affine::translate(-cx, -cy));
2545                (a, w * op)
2546            } else {
2547                (Affine::IDENTITY, w)
2548            };
2549            if w <= 0.0 {
2550                continue;
2551            }
2552            let xf = match &on_path {
2553                Some(p) => {
2554                    let c = x0 + gl.x + tracking * gl.track as f64 + gl.advance / 2.0;
2555                    let ((px, py), angle) = p.at(c);
2556                    xf.mul(Affine::translate(px, py))
2557                        .mul(Affine::rotate(angle))
2558                        .mul(Affine::translate(-c, 0.0))
2559                }
2560                None => xf,
2561            };
2562            let xf = xf.mul(anim);
2563            // Font units are y-up; flip into pixel space (slanted for a
2564            // synthetic italic).
2565            let slant = if gl.upright { 0.0 } else { st.slant };
2566            let local = Affine([scale, 0.0, slant * scale, -scale, 0.0, 0.0]);
2567            if let Some(b) = bitmap {
2568                // The bitmap's unit square onto its place in font units.
2569                let p = b.place;
2570                let m = xf.mul(Affine::translate(ox, oy)).mul(local).mul(Affine([
2571                    p[2],
2572                    0.0,
2573                    0.0,
2574                    -p[3],
2575                    p[0],
2576                    p[1] + p[3],
2577                ]));
2578                images.push(GlyphImage {
2579                    bitmap: b,
2580                    xf: m.0,
2581                    weight: w as f32,
2582                });
2583                continue;
2584            }
2585            match &style {
2586                Some(s) => {
2587                    let unit = kurbo::stroke(
2588                        (to_kurbo(local) * (*outline).clone()).iter(),
2589                        s,
2590                        &kurbo::StrokeOpts::default(),
2591                        TOLERANCE * 0.25,
2592                    );
2593                    let place = xf.mul(Affine::translate(ox, oy));
2594                    front.push((to_kurbo(place) * unit, w as f32, st.color));
2595                }
2596                None => {
2597                    let glyph_xf = xf.mul(Affine::translate(ox, oy)).mul(local);
2598                    front.push((to_kurbo(glyph_xf) * (*outline).clone(), w as f32, st.color));
2599                }
2600            }
2601        }
2602        unit_base += units;
2603    }
2604
2605    // Color groups: every highlight color, then every type color, each
2606    // composited over the ones before.
2607    let mut groups: Vec<Option<[f32; 4]>> = Vec::new();
2608    let group_of = |c: Option<[f32; 4]>, from: usize, groups: &mut Vec<Option<[f32; 4]>>| -> u32 {
2609        match groups[from..].iter().position(|g| *g == c) {
2610            Some(i) => (from + i) as u32,
2611            None if groups.len() < MAX_GROUPS => {
2612                groups.push(c);
2613                (groups.len() - 1) as u32
2614            }
2615            None => (MAX_GROUPS - 1) as u32,
2616        }
2617    };
2618    let mut out = Vec::with_capacity(back.len() + front.len());
2619    for (p, c) in back {
2620        let g = group_of(Some(c), 0, &mut groups);
2621        out.push((p, 1.0, g));
2622    }
2623    let first_front = groups.len();
2624    for (p, w, c) in front {
2625        let g = group_of(c, first_front, &mut groups);
2626        out.push((p, w, g));
2627    }
2628    if groups.len() == 1 && groups[0].is_none() {
2629        groups.clear();
2630    }
2631    Ok(((out, groups), images, unit_base))
2632}
2633
2634/// Decoding text: characters settle into place in a shuffled order as
2635/// `scramble` goes 0 to 1; the rest cycle through `scramble_chars`, a new
2636/// pick every other frame. Spaces and line breaks keep their place.
2637fn scramble(content: &str, progress: f64, r: &Reader) -> String {
2638    let chars: Vec<char> = r
2639        .text("scramble_chars")
2640        .unwrap_or("ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789#%&*+/<>=?")
2641        .chars()
2642        .collect();
2643    if chars.is_empty() || progress >= 1.0 {
2644        return content.to_string();
2645    }
2646    let hash = |a: u64, b: u64| {
2647        let mut x = a.wrapping_mul(0x9E37_79B9_7F4A_7C15) ^ b.wrapping_mul(0xC2B2_AE3D_27D4_EB4F);
2648        x ^= x >> 29;
2649        x = x.wrapping_mul(0xBF58_476D_1CE4_E5B9);
2650        x ^ (x >> 32)
2651    };
2652    let n = content.chars().filter(|c| !c.is_whitespace()).count().max(1);
2653    let tick = (r.t * 15.0).floor() as u64;
2654    let mut k = 0;
2655    content
2656        .chars()
2657        .enumerate()
2658        .map(|(i, c)| {
2659            if c.is_whitespace() {
2660                return c;
2661            }
2662            k += 1;
2663            // Each character settles at its own point of the progress.
2664            let order = (hash(i as u64, 7) % 10_000) as f64 / 10_000.0 * 0.6 + (k as f64 / n as f64) * 0.4;
2665            if order < progress {
2666                c
2667            } else {
2668                chars[(hash(i as u64, tick) % chars.len() as u64) as usize]
2669            }
2670        })
2671        .collect()
2672}
2673
2674/// With `number` (animatable), the text is that value formatted with
2675/// `decimals`, `thousands` separator, `prefix` and `suffix`, for counters.
2676fn number_content(r: &Reader) -> Option<String> {
2677    let v = r
2678        .node
2679        .params
2680        .get("number")
2681        .and_then(|p| p.eval(r.t))
2682        .and_then(|v| v.first().copied())?;
2683    let decimals = r.num("decimals", 0.0).clamp(0.0, 8.0) as usize;
2684    let s = format!("{:.*}", decimals, v.abs());
2685    let (int, frac) = s
2686        .split_once('.')
2687        .map(|(a, b)| (a, Some(b)))
2688        .unwrap_or((s.as_str(), None));
2689    let sep = r.text("thousands").unwrap_or(",");
2690    let mut grouped = String::new();
2691    for (i, c) in int.chars().enumerate() {
2692        if i > 0 && (int.len() - i) % 3 == 0 {
2693            grouped.push_str(sep);
2694        }
2695        grouped.push(c);
2696    }
2697    let sign = if v < 0.0 && s.chars().any(|c| c.is_ascii_digit() && c != '0') {
2698        "-"
2699    } else {
2700        ""
2701    };
2702    Some(format!(
2703        "{}{sign}{grouped}{}{}",
2704        r.text("prefix").unwrap_or(""),
2705        frac.map(|f| format!(".{f}")).unwrap_or_default(),
2706        r.text("suffix").unwrap_or("")
2707    ))
2708}
2709
2710/// OpenType features: the node's own, plus tabular figures for counters so
2711/// digits do not jitter as they change.
2712fn text_features(r: &Reader) -> Vec<rustybuzz::Feature> {
2713    let mut f: Vec<rustybuzz::Feature> = match r.text("features") {
2714        Some(f) => f.split(',').filter_map(|s| s.trim().parse().ok()).collect(),
2715        None => Vec::new(),
2716    };
2717    if (r.node.params.contains_key("number") || r.node.params.contains_key("scramble"))
2718        && !r.text("features").is_some_and(|s| s.contains("tnum"))
2719        && let Ok(t) = "tnum".parse()
2720    {
2721        f.push(t);
2722    }
2723    f
2724}
2725
2726/// A path measured by arc length, for text that follows it.
2727struct ArcPath {
2728    pts: Vec<(f64, f64)>,
2729    cum: Vec<f64>,
2730    length: f64,
2731    closed: bool,
2732}
2733
2734impl ArcPath {
2735    fn new(p: &BezPath) -> Self {
2736        let mut pts: Vec<(f64, f64)> = Vec::new();
2737        let mut closed = false;
2738        // Text follows the first subpath only.
2739        let mut done = false;
2740        kurbo::flatten(p.iter(), 0.05, |el| match el {
2741            _ if done => {}
2742            kurbo::PathEl::MoveTo(q) => {
2743                if pts.is_empty() {
2744                    pts.push((q.x, q.y));
2745                } else {
2746                    done = true;
2747                }
2748            }
2749            kurbo::PathEl::LineTo(q) => pts.push((q.x, q.y)),
2750            kurbo::PathEl::ClosePath => {
2751                closed = true;
2752                done = true;
2753            }
2754            _ => {}
2755        });
2756        if closed && pts.len() > 1 && pts.first() != pts.last() {
2757            pts.push(pts[0]);
2758        }
2759        if pts.len() < 2 {
2760            pts = vec![(0.0, 0.0), (1.0, 0.0)];
2761        }
2762        let mut cum = vec![0.0];
2763        for w in pts.windows(2) {
2764            let d = ((w[1].0 - w[0].0).powi(2) + (w[1].1 - w[0].1).powi(2)).sqrt();
2765            cum.push(cum.last().unwrap() + d);
2766        }
2767        let length = cum.last().copied().unwrap_or(0.0).max(1e-9);
2768        ArcPath {
2769            pts,
2770            cum,
2771            length,
2772            closed,
2773        }
2774    }
2775
2776    /// Point and direction (radians) at arc length `s`. Closed paths wrap;
2777    /// open ones continue straight past their ends.
2778    fn at(&self, s: f64) -> ((f64, f64), f64) {
2779        let s = if self.closed { s.rem_euclid(self.length) } else { s };
2780        let i = match self.cum.binary_search_by(|c| c.total_cmp(&s)) {
2781            Ok(i) => i.min(self.pts.len() - 2),
2782            Err(i) => i.saturating_sub(1).min(self.pts.len() - 2),
2783        };
2784        let (a, b) = (self.pts[i], self.pts[i + 1]);
2785        let seg = (self.cum[i + 1] - self.cum[i]).max(1e-9);
2786        let u = (s - self.cum[i]) / seg;
2787        let angle = (b.1 - a.1).atan2(b.0 - a.0);
2788        ((a.0 + (b.0 - a.0) * u, a.1 + (b.1 - a.1) * u), angle)
2789    }
2790}
2791
2792/// One glyph of a measured line, in pixels from the baseline origin (before
2793/// alignment and placement).
2794#[derive(Debug, Clone, serde::Serialize)]
2795pub struct GlyphBox {
2796    /// The text this glyph sets (a ligature covers several characters).
2797    pub text: String,
2798    /// Pen position and advance, tracking included.
2799    pub x: f64,
2800    pub advance: f64,
2801    /// Ink box [x0, y0, x1, y1] (y down; None for spaces).
2802    pub ink: Option<[f64; 4]>,
2803}
2804
2805/// Line metrics of a single-line `text` node: glyph boxes, total advance,
2806/// ascent and descent (pixels). For agents laying out type by hand, such as
2807/// one 3D mesh per letter.
2808#[derive(Debug, Clone, serde::Serialize)]
2809pub struct LineMetrics {
2810    pub glyphs: Vec<GlyphBox>,
2811    pub advance: f64,
2812    pub ascent: f64,
2813    pub descent: f64,
2814}
2815
2816pub fn measure(id: &str, node: &Node, t: f64, fonts: &mut Fonts, base: &Path) -> Result<LineMetrics, GeomError> {
2817    let r = Reader { id, node, t };
2818    let rich = rich(&r, &r, fonts, base)?;
2819    let content = rich.plain.as_str();
2820    let tracking = r.num("tracking", 0.0);
2821    let (laid, adv) = rich.shape(fonts, 0, content.len()).map_err(|e| r.bad("text", e))?;
2822    let mut glyphs = Vec::new();
2823    for (gl, si) in laid.iter() {
2824        let st = &rich.styles[*si];
2825        let start = gl.cluster;
2826        let end = laid
2827            .iter()
2828            .map(|g| g.0.cluster)
2829            .filter(|&c| c > start)
2830            .min()
2831            .unwrap_or(content.len());
2832        let x = gl.x + tracking * gl.track as f64;
2833        let gv: &[rustybuzz::Variation] = if gl.font == st.font { &st.vars } else { &[] };
2834        let outline = fonts.glyph(gl.font, gl.id, gv).map_err(|e| r.bad("font", e))?;
2835        let ink = (!outline.elements().is_empty()).then(|| {
2836            let b = outline.bounding_box();
2837            let s = gl.scale;
2838            let y = gl.y + st.rise;
2839            [x + b.x0 * s, -b.y1 * s - y, x + b.x1 * s, -b.y0 * s - y]
2840        });
2841        glyphs.push(GlyphBox {
2842            text: content.get(start..end).unwrap_or("").to_string(),
2843            x,
2844            advance: gl.advance + tracking,
2845            ink,
2846        });
2847    }
2848    Ok(LineMetrics {
2849        advance: adv + tracking * laid.last().map_or(0, |g| g.0.track) as f64,
2850        ascent: rich.ascent,
2851        descent: rich.descent,
2852        glyphs,
2853    })
2854}
2855
2856/// Builds the geometry of a `text` node under `outer`.
2857pub fn text_node(
2858    id: &str,
2859    node: &Node,
2860    fmt: &Format,
2861    t: f64,
2862    outer: Affine,
2863    fonts: &mut Fonts,
2864    base: &Path,
2865) -> Result<Geometry, GeomError> {
2866    let mut g = Geometry::empty();
2867    let ((paths, groups), images, units) = layout_text(id, node, fmt, t, outer, fonts, base)?;
2868    for (path, w, group) in paths {
2869        flatten_closed(&path, w, group, &mut g);
2870    }
2871    g.groups = groups;
2872    g.units = units;
2873    for im in images {
2874        g.push_image(im);
2875    }
2876    Ok(g)
2877}
2878
2879/// The node's own placement affine at `t` (position, anchor, scale,
2880/// rotation), as text and path geometry apply it.
2881pub fn placement_affine(node: &Node, t: f64) -> Affine {
2882    placement(&Reader { id: "", node, t }, [0.0, 0.0])
2883}
2884
2885/// Hash of what a geometry's shape depends on apart from where it is
2886/// placed: everything but `position` and the outer transform. Two
2887/// geometries with equal content keys and the same linear transform differ
2888/// only by a translation.
2889pub fn content_key(node: &Node, t: f64) -> u64 {
2890    let mut n = node.clone();
2891    n.params.remove("position");
2892    geometry_key(&n, t, &Affine::IDENTITY)
2893}
2894
2895impl Geometry {
2896    /// The same geometry moved by (dx, dy).
2897    /// The geometry mapped through the affine `m` (output px to output px):
2898    /// type that turns or scales but keeps its shape.
2899    pub fn transformed(&self, m: [f64; 6]) -> Geometry {
2900        let map = |x: f32, y: f32| {
2901            let (x, y) = (x as f64, y as f64);
2902            ((m[0] * x + m[2] * y + m[4]) as f32, (m[1] * x + m[3] * y + m[5]) as f32)
2903        };
2904        let mut out = Geometry::empty();
2905        out.segments = self.segments.clone();
2906        for s in out.segments.chunks_exact_mut(8) {
2907            let (ax, ay) = map(s[0], s[1]);
2908            let (bx, by) = map(s[2], s[3]);
2909            s[..4].copy_from_slice(&[ax, ay, bx, by]);
2910            out.bounds = [
2911                out.bounds[0].min(ax.min(bx)),
2912                out.bounds[1].min(ay.min(by)),
2913                out.bounds[2].max(ax.max(bx)),
2914                out.bounds[3].max(ay.max(by)),
2915            ];
2916        }
2917        out.groups = self.groups.clone();
2918        out.units = self.units;
2919        for im in &self.images {
2920            let x = im.xf;
2921            let mut im = im.clone();
2922            im.xf = [
2923                m[0] * x[0] + m[2] * x[1],
2924                m[1] * x[0] + m[3] * x[1],
2925                m[0] * x[2] + m[2] * x[3],
2926                m[1] * x[2] + m[3] * x[3],
2927                m[0] * x[4] + m[2] * x[5] + m[4],
2928                m[1] * x[4] + m[3] * x[5] + m[5],
2929            ];
2930            out.push_image(im);
2931        }
2932        out
2933    }
2934
2935    pub fn translated(&self, dx: f64, dy: f64) -> Geometry {
2936        let (dx, dy) = (dx as f32, dy as f32);
2937        let mut segments = self.segments.clone();
2938        for s in segments.chunks_exact_mut(8) {
2939            s[0] += dx;
2940            s[1] += dy;
2941            s[2] += dx;
2942            s[3] += dy;
2943        }
2944        let b = self.bounds;
2945        let images = self
2946            .images
2947            .iter()
2948            .map(|im| {
2949                let mut im = im.clone();
2950                im.xf[4] += dx as f64;
2951                im.xf[5] += dy as f64;
2952                im
2953            })
2954            .collect();
2955        Geometry {
2956            segments,
2957            bounds: [b[0] + dx, b[1] + dy, b[2] + dx, b[3] + dy],
2958            groups: self.groups.clone(),
2959            images,
2960            units: self.units,
2961        }
2962    }
2963}
2964
2965/// Stable hash of everything a geometry depends on, for caching.
2966pub fn geometry_key(node: &Node, t: f64, outer: &Affine) -> u64 {
2967    let mut h = std::collections::hash_map::DefaultHasher::new();
2968    node.op.hash(&mut h);
2969    for (k, p) in &node.params {
2970        k.hash(&mut h);
2971        match p {
2972            Param::Text(s) => s.hash(&mut h),
2973            p => {
2974                for v in p.eval(t).unwrap_or_default() {
2975                    v.to_bits().hash(&mut h);
2976                }
2977            }
2978        }
2979    }
2980    for v in outer.0 {
2981        v.to_bits().hash(&mut h);
2982    }
2983    // Scrambling text changes characters on its own clock until it is done.
2984    if node
2985        .params
2986        .get("scramble")
2987        .and_then(|p| p.eval(t))
2988        .is_some_and(|v| v.first().is_some_and(|&p| p < 1.0))
2989    {
2990        ((t * 15.0).floor() as i64).hash(&mut h);
2991    }
2992    // Staggered glyph animators read their params at shifted times, so the
2993    // geometry can change while the values at `t` hold still.
2994    let staggered = node
2995        .params
2996        .get("stagger")
2997        .and_then(|p| p.eval(t))
2998        .is_some_and(|v| v.first() != Some(&0.0));
2999    if staggered
3000        && GLYPH_ANIMATORS
3001            .iter()
3002            .any(|p| node.params.get(*p).is_some_and(Param::is_animated))
3003    {
3004        t.to_bits().hash(&mut h);
3005    }
3006    h.finish()
3007}
3008
3009#[cfg(test)]
3010mod tests {
3011    use super::*;
3012
3013    fn node(json: &str) -> Node {
3014        serde_json::from_str(json).unwrap()
3015    }
3016
3017    #[test]
3018    fn square_flattens_to_four_segments() {
3019        let n = node(r#"{"op":"path","params":{"d":"M10 10 H 20 V 20 H 10 Z"}}"#);
3020        let fmt = Format {
3021            width: 64,
3022            height: 64,
3023            fps: 30.0,
3024            duration: 1.0,
3025            motion_blur: None,
3026        };
3027        let g = path("p", &n, &fmt, 0.0, Affine::IDENTITY).unwrap();
3028        assert_eq!(g.count(), 4);
3029        assert_eq!(g.bounds, [10.0, 10.0, 20.0, 20.0]);
3030    }
3031
3032    #[test]
3033    fn trim_halves_length() {
3034        let p = BezPath::from_svg("M0 0 L100 0").unwrap();
3035        let t = trim(&p, 0.25, 0.75);
3036        let segs: Vec<_> = t.segments().collect();
3037        assert_eq!(segs.len(), 1);
3038        assert!((segs[0].start().x - 25.0).abs() < 1e-6 && (segs[0].end().x - 75.0).abs() < 1e-6);
3039    }
3040
3041    #[test]
3042    fn text_shapes_and_lays_out() {
3043        let n = node(r#"{"op":"text","params":{"text":"Hi there","size":40,"position":[10,10]}}"#);
3044        let fmt = Format {
3045            width: 400,
3046            height: 100,
3047            fps: 30.0,
3048            duration: 1.0,
3049            motion_blur: None,
3050        };
3051        let mut fonts = Fonts::new();
3052        let g = text_node("t", &n, &fmt, 0.0, Affine::IDENTITY, &mut fonts, Path::new(".")).unwrap();
3053        assert!(g.count() > 20, "{}", g.count());
3054        // Every letter and the space: what `reveal` counts.
3055        assert_eq!(g.units, 8);
3056        assert!(
3057            g.bounds[0] >= 10.0 && g.bounds[1] >= 10.0 && g.bounds[2] < 400.0,
3058            "{:?}",
3059            g.bounds
3060        );
3061    }
3062}
3063
3064#[cfg(test)]
3065mod emoji_tests {
3066    use super::*;
3067
3068    #[test]
3069    fn color_emoji_have_bitmaps() {
3070        let mut f = Fonts::new();
3071        let Some(face) = f.emoji_face('\u{1F525}') else {
3072            eprintln!("no color emoji face installed");
3073            return;
3074        };
3075        if !f.has_color_bitmaps(face) {
3076            // Windows' Segoe UI Emoji draws color with COLR layers, not
3077            // bitmaps: its emoji come out as plain outlines for now.
3078            eprintln!("the installed emoji face has no color bitmaps");
3079            return;
3080        }
3081        let (data, index) = f.face_data(face).unwrap();
3082        let tf = rustybuzz::ttf_parser::Face::parse(&data, index).unwrap();
3083        let gid = tf.glyph_index('\u{1F525}').unwrap();
3084        eprintln!(
3085            "face {:?} glyph {:?} tables sbix {} cbdt {}",
3086            f.db().face(face).map(|x| x.families.clone()),
3087            gid,
3088            tf.tables().sbix.is_some(),
3089            tf.tables().cbdt.is_some()
3090        );
3091        let raw = tf.glyph_raster_image(gid, 80);
3092        eprintln!(
3093            "raw: {:?}",
3094            raw.map(|r| (r.x, r.y, r.width, r.height, r.pixels_per_em, r.format))
3095        );
3096        let b = f.glyph_bitmap(face, gid.0, 80.0);
3097        eprintln!("bitmap: {:?}", b.as_ref().map(|b| (b.width, b.height, b.place)));
3098        assert!(b.is_some());
3099    }
3100}