Skip to main content

ultrafast_geom/
lib.rs

1//! Vector geometry and text on the CPU: paths (SVG data, presets, strokes,
2//! trims, morphs) and text (font lookup, shaping, layout, measuring) built
3//! into flattened geometry for the GPU rasterizer ([`geom`]), inline text
4//! markup ([`markup`]) and fonts fetched by name ([`fontfetch`]).
5//!
6//! The renderer (ultrafast-render) rasterizes this geometry and re-exports
7//! these modules at their old paths; tools that only measure or lay out
8//! type use them without a GPU.
9
10// As in the renderer this code grew in: glyph runs travel as tuples, and
11// `Affine::mul` is a plain method.
12#![allow(clippy::type_complexity, clippy::should_implement_trait)]
13
14pub mod fontfetch;
15pub mod geom;
16pub mod lru;
17pub mod markup;
18
19use ultrafast_graph::{Node, NodeId, Param};
20
21/// Why a node's geometry could not be built (ultrafast-render reports it as
22/// the `RenderError` variant of the same name).
23#[derive(Debug, thiserror::Error)]
24pub enum GeomError {
25    #[error("node `{node}` param `{param}`: {reason}")]
26    BadParam {
27        node: NodeId,
28        param: String,
29        reason: String,
30    },
31}
32
33// Helpers shared with the renderer, which re-exports them from `ops` and
34// `images`.
35
36pub fn text<'a>(node: &'a Node, name: &str) -> Option<&'a str> {
37    match node.params.get(name) {
38        Some(Param::Text(s)) => Some(s.as_str()),
39        _ => None,
40    }
41}
42
43pub fn parse_hex(s: &str) -> Option<[f64; 4]> {
44    let h = s.strip_prefix('#')?;
45    let byte = |i: usize| u8::from_str_radix(h.get(i..i + 2)?, 16).ok().map(|b| b as f64 / 255.0);
46    let nib = |i: usize| u8::from_str_radix(h.get(i..i + 1)?, 16).ok().map(|b| b as f64 / 15.0);
47    match h.len() {
48        3 => Some([nib(0)?, nib(1)?, nib(2)?, 1.0]),
49        4 => Some([nib(0)?, nib(1)?, nib(2)?, nib(3)?]),
50        6 => Some([byte(0)?, byte(2)?, byte(4)?, 1.0]),
51        8 => Some([byte(0)?, byte(2)?, byte(4)?, byte(6)?]),
52        _ => None,
53    }
54}
55
56pub fn srgb_to_linear(x: f64) -> f64 {
57    if x <= 0.04045 {
58        x / 12.92
59    } else {
60        ((x + 0.055) / 1.055).powf(2.4)
61    }
62}
63
64/// 2D affine `[a, b, c, d, e, f]`: x' = a x + c y + e, y' = b x + d y + f.
65#[derive(Debug, Clone, Copy, PartialEq)]
66pub struct Affine(pub [f64; 6]);
67
68impl Affine {
69    pub const IDENTITY: Affine = Affine([1.0, 0.0, 0.0, 1.0, 0.0, 0.0]);
70
71    pub fn translate(x: f64, y: f64) -> Self {
72        Affine([1.0, 0.0, 0.0, 1.0, x, y])
73    }
74    pub fn scale(x: f64, y: f64) -> Self {
75        Affine([x, 0.0, 0.0, y, 0.0, 0.0])
76    }
77    pub fn rotate(r: f64) -> Self {
78        let (s, c) = r.sin_cos();
79        Affine([c, s, -s, c, 0.0, 0.0])
80    }
81    pub fn skew_x(r: f64) -> Self {
82        Affine([1.0, 0.0, r.tan(), 1.0, 0.0, 0.0])
83    }
84    pub fn mul(self, o: Affine) -> Affine {
85        let [a, b, c, d, e, f] = self.0;
86        let [a2, b2, c2, d2, e2, f2] = o.0;
87        Affine([
88            a * a2 + c * b2,
89            b * a2 + d * b2,
90            a * c2 + c * d2,
91            b * c2 + d * d2,
92            a * e2 + c * f2 + e,
93            b * e2 + d * f2 + f,
94        ])
95    }
96    pub fn det(self) -> f64 {
97        self.0[0] * self.0[3] - self.0[1] * self.0[2]
98    }
99    pub fn inverse(self) -> Option<Affine> {
100        let det = self.det();
101        if det.abs() < 1e-12 {
102            return None;
103        }
104        let [a, b, c, d, e, f] = self.0;
105        let inv = 1.0 / det;
106        Some(Affine([
107            d * inv,
108            -b * inv,
109            -c * inv,
110            a * inv,
111            (c * f - d * e) * inv,
112            (b * e - a * f) * inv,
113        ]))
114    }
115    pub fn apply(self, x: f64, y: f64) -> (f64, f64) {
116        let [a, b, c, d, e, f] = self.0;
117        (a * x + c * y + e, b * x + d * y + f)
118    }
119}
120
121/// IEEE half from f32 (round to nearest even).
122pub fn f32_to_f16(v: f32) -> u16 {
123    let x = v.to_bits();
124    let sign = ((x >> 16) & 0x8000) as u16;
125    let exp = ((x >> 23) & 0xff) as i32 - 127 + 15;
126    let mant = x & 0x7f_ffff;
127    if exp <= 0 {
128        if exp < -10 {
129            return sign;
130        }
131        let m = (mant | 0x80_0000) >> (1 - exp);
132        return sign | ((m + 0x1000) >> 13) as u16;
133    }
134    if exp >= 31 {
135        return sign | 0x7c00;
136    }
137    let h = sign as u32 | ((exp as u32) << 10) | (mant >> 13);
138    let rem = mant & 0x1fff;
139    (if rem > 0x1000 || (rem == 0x1000 && h & 1 == 1) {
140        h + 1
141    } else {
142        h
143    }) as u16
144}