Skip to main content

brep_render/sketch/
text.rs

1//! Text authoring and embedded font outlines. Only the frame is solver geometry.
2use super::{SketchDoc, SketchGeometry};
3use serde_json::{json, Value};
4use ttf_parser::OutlineBuilder;
5
6pub const FONTS: &[&str] = &["Ubuntu Light", "Hack Regular"];
7
8#[derive(Default)]
9struct Outline {
10    contours: Vec<Vec<[f64; 2]>>,
11    current: Vec<[f64; 2]>,
12    offset: f64,
13}
14impl Outline {
15    fn p(&self, x: f32, y: f32) -> [f64; 2] {
16        [x as f64 + self.offset, y as f64]
17    }
18}
19impl OutlineBuilder for Outline {
20    fn move_to(&mut self, x: f32, y: f32) {
21        self.current = vec![self.p(x, y)];
22    }
23    fn line_to(&mut self, x: f32, y: f32) {
24        let a = *self.current.last().unwrap();
25        let b = self.p(x, y);
26        if a == b {
27            return;
28        }
29        self.current.extend([
30            [a[0] + (b[0] - a[0]) / 3., a[1] + (b[1] - a[1]) / 3.],
31            [
32                a[0] + 2. * (b[0] - a[0]) / 3.,
33                a[1] + 2. * (b[1] - a[1]) / 3.,
34            ],
35            b,
36        ]);
37    }
38    fn quad_to(&mut self, x1: f32, y1: f32, x: f32, y: f32) {
39        let a = *self.current.last().unwrap();
40        let q = self.p(x1, y1);
41        let b = self.p(x, y);
42        self.current.extend([
43            [
44                a[0] + 2. * (q[0] - a[0]) / 3.,
45                a[1] + 2. * (q[1] - a[1]) / 3.,
46            ],
47            [
48                b[0] + 2. * (q[0] - b[0]) / 3.,
49                b[1] + 2. * (q[1] - b[1]) / 3.,
50            ],
51            b,
52        ]);
53    }
54    fn curve_to(&mut self, x1: f32, y1: f32, x2: f32, y2: f32, x: f32, y: f32) {
55        self.current
56            .extend([self.p(x1, y1), self.p(x2, y2), self.p(x, y)]);
57    }
58    fn close(&mut self) {
59        let a = self.current[0];
60        self.line_to((a[0] - self.offset) as f32, a[1] as f32);
61        if self.current.len() >= 4 {
62            self.contours.push(std::mem::take(&mut self.current));
63        }
64    }
65}
66
67pub fn outlines(text: &str, font: &str) -> Result<Value, String> {
68    if text.trim().is_empty() {
69        return Err("Enter text containing visible characters".into());
70    }
71    if text.chars().count() > 256 {
72        return Err("Sketch text is limited to 256 characters".into());
73    }
74    if text.chars().any(char::is_control) {
75        return Err("Sketch text must be a single line".into());
76    }
77    let bytes = match font {
78        "Ubuntu Light" => epaint_default_fonts::UBUNTU_LIGHT,
79        "Hack Regular" => epaint_default_fonts::HACK_REGULAR,
80        _ => return Err("Unknown sketch font".into()),
81    };
82    let face = ttf_parser::Face::parse(bytes, 0).map_err(|e| format!("Font: {e:?}"))?;
83    let mut builder = Outline::default();
84    for ch in text.chars() {
85        let glyph = face
86            .glyph_index(ch)
87            .ok_or_else(|| format!("{font} has no glyph for {ch}"))?;
88        face.outline_glyph(glyph, &mut builder);
89        builder.offset += face.glyph_hor_advance(glyph).unwrap_or(0) as f64;
90    }
91    let mut lo = [f64::INFINITY; 2];
92    let mut hi = [f64::NEG_INFINITY; 2];
93    for p in builder.contours.iter().flatten() {
94        for i in 0..2 {
95            lo[i] = lo[i].min(p[i]);
96            hi[i] = hi[i].max(p[i]);
97        }
98    }
99    if (0..2).any(|i| !lo[i].is_finite() || hi[i] <= lo[i]) {
100        return Err("Text has no usable outlines".into());
101    }
102    for p in builder.contours.iter_mut().flatten() {
103        for i in 0..2 {
104            p[i] = (p[i] - lo[i]) / (hi[i] - lo[i]);
105        }
106    }
107    Ok(json!(builder.contours))
108}
109
110pub fn expanded(doc: &SketchDoc) -> Result<SketchDoc, String> {
111    let value = serde_json::to_value(doc).map_err(|e| e.to_string())?;
112    serde_json::from_value(brep_kernel::feature_pipeline::expand_sketch_text(&value)?)
113        .map_err(|e| e.to_string())
114}
115
116pub fn object(
117    id: Value,
118    corners: Vec<Value>,
119    text: &str,
120    font: &str,
121) -> Result<SketchGeometry, String> {
122    Ok(SketchGeometry { id, geom_type: "text".into(), points:corners, extra: serde_json::from_value(json!({"construction":true,"text":text,"font":font,"textContours":outlines(text,font)?})).unwrap() })
123}
124