Skip to main content
← Back to kicad-monkey Rust Docs kicad-monkey Rust Crate API Reference

cad_text_realization/
text_bezier.rs

1//! Bounded KiCad-compatible quadratic and cubic outline decomposition.
2
3use std::fmt;
4
5/// One point in the caller's declared coordinate space.
6#[derive(Clone, Copy, Debug, PartialEq)]
7pub struct TextPoint {
8    pub x: f64,
9    pub y: f64,
10}
11
12/// Flattened points and exact charged work for boundary tests and profiling.
13#[derive(Clone, Debug)]
14pub struct TextBezierOutput {
15    pub points: Vec<TextPoint>,
16    pub work_items: usize,
17}
18
19#[derive(Clone, Copy, Debug, Eq, PartialEq)]
20pub enum TextBezierErrorKind {
21    InvalidInput,
22    ResourceLimit,
23}
24
25#[derive(Clone, Debug, Eq, PartialEq)]
26pub struct TextBezierError {
27    pub kind: TextBezierErrorKind,
28    pub message: &'static str,
29}
30
31impl fmt::Display for TextBezierError {
32    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
33        formatter.write_str(self.message)
34    }
35}
36
37impl std::error::Error for TextBezierError {}
38
39/// Flatten one quadratic curve using KiCad's outline-decomposer approximation.
40pub fn flatten_quadratic_bezier(
41    control: [TextPoint; 3],
42    max_error: f64,
43) -> Result<TextBezierOutput, TextBezierError> {
44    validate_input(&control, max_error)?;
45    let max_error = effective_error(max_error);
46    let mut state = FlattenState::new();
47    state.charge()?;
48    let ddx = 2.0 * control[1].x - control[0].x - control[2].x;
49    let ddy = 2.0 * control[1].y - control[0].y - control[2].y;
50    let u0 = (control[1].x - control[0].x) * ddx + (control[1].y - control[0].y) * ddy;
51    let u2 = (control[2].x - control[1].x) * ddx + (control[2].y - control[1].y) * ddy;
52    let cross = (control[2].x - control[0].x) * ddy - (control[2].y - control[0].y) * ddx;
53    let denominator = ddx.hypot(ddy);
54    if cross == 0.0 || denominator == 0.0 {
55        state.push(control[0])?;
56        state.push(control[2])?;
57        return Ok(state.finish());
58    }
59
60    let x0 = u0 / cross;
61    let x2 = u2 / cross;
62    if x2 == x0 {
63        state.push(control[0])?;
64        state.push(control[2])?;
65        return Ok(state.finish());
66    }
67    let scale = cross.abs() / (denominator * (x2 - x0).abs());
68    if scale <= 0.0 {
69        state.push(control[0])?;
70        state.push(control[2])?;
71        return Ok(state.finish());
72    }
73
74    let a0 = approx_int(x0);
75    let a2 = approx_int(x2);
76    let segment_count_f = (0.5 * (a2 - a0).abs() * (scale / max_error).sqrt()).ceil();
77    let segment_count = bounded_count(segment_count_f)?;
78    let v0 = approx_inv_int(a0);
79    let v2 = approx_inv_int(a2);
80    state.push(control[0])?;
81    if v2 != v0 {
82        for index in 0..segment_count {
83            state.charge()?;
84            let u = approx_inv_int(a0 + (a2 - a0) * index as f64 / segment_count as f64);
85            state.push(eval_quadratic(control, (u - v0) / (v2 - v0)))?;
86        }
87    }
88    state.push(control[2])?;
89    Ok(state.finish())
90}
91
92/// Flatten one cubic curve using KiCad's inflection-aware approximation.
93pub fn flatten_cubic_bezier(
94    control: [TextPoint; 4],
95    max_error: f64,
96) -> Result<TextBezierOutput, TextBezierError> {
97    validate_input(&control, max_error)?;
98    let mut state = FlattenState::new();
99    state.push(control[0])?;
100    cubic_poly(control, effective_error(max_error), &mut state)?;
101    Ok(state.finish())
102}
103
104struct FlattenState {
105    points: Vec<TextPoint>,
106    work_items: usize,
107}
108
109impl FlattenState {
110    fn new() -> Self {
111        Self {
112            points: Vec::with_capacity(256),
113            work_items: 0,
114        }
115    }
116
117    fn push(&mut self, point: TextPoint) -> Result<(), TextBezierError> {
118        self.points.push(point);
119        Ok(())
120    }
121
122    fn charge(&mut self) -> Result<(), TextBezierError> {
123        self.work_items += 1;
124        Ok(())
125    }
126
127    fn reserve_pending(&self, _count: usize) -> Result<(), TextBezierError> {
128        Ok(())
129    }
130
131    fn finish(self) -> TextBezierOutput {
132        TextBezierOutput {
133            points: self.points,
134            work_items: self.work_items,
135        }
136    }
137}
138
139fn cubic_poly(
140    control: [TextPoint; 4],
141    max_error: f64,
142    state: &mut FlattenState,
143) -> Result<(), TextBezierError> {
144    state.charge()?;
145    if inflection_class(control) == 0 {
146        return cubic_parabolic(control, max_error, state);
147    }
148    let (count, first_t, _) = inflection_points(control);
149    match count {
150        2 => cubic_two_inflections(control, first_t, max_error, state),
151        1 => {
152            let (first, second) = subdivide_cubic(control, first_t);
153            cubic_parabolic(first, max_error, state)?;
154            cubic_parabolic(second, max_error, state)
155        }
156        _ => cubic_parabolic(control, max_error, state),
157    }
158}
159
160fn cubic_two_inflections(
161    control: [TextPoint; 4],
162    first_t: f64,
163    max_error: f64,
164    state: &mut FlattenState,
165) -> Result<(), TextBezierError> {
166    let (first, remainder) = subdivide_cubic(control, first_t);
167    cubic_parabolic(first, max_error, state)?;
168    let (second_count, second_t, _) = inflection_points(remainder);
169    if !matches!(second_count, 1 | 2) {
170        return state.push(remainder[3]);
171    }
172    let (middle, last) = subdivide_cubic(remainder, second_t);
173    recursive_cubic(middle, max_error, state)?;
174    cubic_parabolic(last, max_error, state)
175}
176
177fn cubic_parabolic(
178    mut current: [TextPoint; 4],
179    max_error: f64,
180    state: &mut FlattenState,
181) -> Result<(), TextBezierError> {
182    loop {
183        state.charge()?;
184        if current
185            .iter()
186            .any(|point| !point.x.is_finite() || !point.y.is_finite())
187        {
188            return Err(invalid_error(
189                "Bezier subdivision produced a non-finite coordinate",
190            ));
191        }
192        if cubic_is_flat(current, max_error) {
193            return state.push(current[3]);
194        }
195        let deviation = third_control_deviation(current);
196        if deviation <= 0.0 {
197            return recursive_cubic(current, max_error, state);
198        }
199        let t = 2.0 * (max_error / (3.0 * deviation)).sqrt();
200        if !t.is_finite() || t > 1.0 {
201            return recursive_cubic(current, max_error, state);
202        }
203        let (first, second) = subdivide_cubic(current, t);
204        if cubic_is_flat(first, max_error) {
205            state.push(first[3])?;
206        } else {
207            recursive_cubic(first, max_error, state)?;
208        }
209        current = second;
210    }
211}
212
213fn recursive_cubic(
214    control: [TextPoint; 4],
215    max_error: f64,
216    state: &mut FlattenState,
217) -> Result<(), TextBezierError> {
218    let mut stack = vec![control];
219    while let Some(curve) = stack.pop() {
220        state.charge()?;
221        if curve[3] == curve[0] {
222            continue;
223        }
224        if cubic_is_flat(curve, max_error) {
225            state.push(curve[3])?;
226            continue;
227        }
228        state.reserve_pending(stack.len().saturating_add(2))?;
229        let (left, right) = subdivide_cubic(curve, 0.5);
230        stack.push(right);
231        stack.push(left);
232    }
233    Ok(())
234}
235
236fn validate_input<const N: usize>(
237    control: &[TextPoint; N],
238    max_error: f64,
239) -> Result<(), TextBezierError> {
240    if !max_error.is_finite()
241        || control
242            .iter()
243            .any(|point| !point.x.is_finite() || !point.y.is_finite())
244    {
245        Err(invalid_error(
246            "Bezier coordinates and tolerance must be finite",
247        ))
248    } else {
249        Ok(())
250    }
251}
252
253fn effective_error(max_error: f64) -> f64 {
254    if max_error <= 0.0 { 10.0 } else { max_error }
255}
256
257fn bounded_count(value: f64) -> Result<usize, TextBezierError> {
258    if !value.is_finite() || value < 0.0 {
259        Err(invalid_error(
260            "quadratic segment count is not a finite count",
261        ))
262    } else {
263        Ok(value as usize)
264    }
265}
266
267fn approx_int(value: f64) -> f64 {
268    let d = 0.674_489_750_196_081_7;
269    let d4 = d * d * d * d;
270    value / (1.0 - d + (d4 + value * value * 0.25).powf(0.25))
271}
272
273fn approx_inv_int(value: f64) -> f64 {
274    let p = 0.395_388_16;
275    value * (1.0 - p + (p * p + 0.25 * value * value).sqrt())
276}
277
278fn eval_quadratic(control: [TextPoint; 3], t: f64) -> TextPoint {
279    let omt = 1.0 - t;
280    add(
281        add(
282            scale(omt * omt, control[0]),
283            scale(2.0 * omt * t, control[1]),
284        ),
285        scale(t * t, control[2]),
286    )
287}
288
289fn cubic_is_flat(control: [TextPoint; 4], max_error: f64) -> bool {
290    let delta = sub(control[3], control[0]);
291    let delta_norm = squared_norm(delta);
292    if delta_norm == 0.0 {
293        return true;
294    }
295    let cross1 = cross(delta, sub(control[1], control[0]));
296    let cross2 = cross(delta, sub(control[2], control[0]));
297    let d1 = cross1 * cross1 / delta_norm;
298    let d2 = cross2 * cross2 / delta_norm;
299    let factor: f64 = if cross1 * cross2 > 0.0 {
300        3.0 / 4.0
301    } else {
302        4.0 / 9.0
303    };
304    let tolerance = max_error * max_error;
305    d1 * factor.powi(2) <= tolerance && d2 * factor.powi(2) <= tolerance
306}
307
308fn subdivide_cubic(control: [TextPoint; 4], t: f64) -> ([TextPoint; 4], [TextPoint; 4]) {
309    let left1 = add(control[0], scale(t, sub(control[1], control[0])));
310    let middle = add(control[1], scale(t, sub(control[2], control[1])));
311    let left2 = add(left1, scale(t, sub(middle, left1)));
312    let right2 = add(control[2], scale(t, sub(control[3], control[2])));
313    let right1 = add(middle, scale(t, sub(right2, middle)));
314    let shared = add(left2, scale(t, sub(right1, left2)));
315    (
316        [control[0], left1, left2, shared],
317        [shared, right1, right2, control[3]],
318    )
319}
320
321fn inflection_class(control: [TextPoint; 4]) -> i8 {
322    let d21 = sub(control[1], control[0]);
323    let d32 = sub(control[2], control[1]);
324    let d43 = sub(control[3], control[2]);
325    let cross1 = cross(d21, d32) * cross(d32, d43);
326    let cross2 = cross(d21, d32) * cross(d21, d43);
327    if cross1 < 0.0 {
328        1
329    } else if cross2 > 0.0 || (dot(d21, d32) > 0.0) ^ (dot(d32, d43) > 0.0) {
330        0
331    } else {
332        -1
333    }
334}
335
336fn third_control_deviation(control: [TextPoint; 4]) -> f64 {
337    let delta = sub(control[1], control[0]);
338    let length_squared = squared_norm(delta);
339    if length_squared < 1.0e-6 {
340        return 0.0;
341    }
342    let length = length_squared.sqrt();
343    let r = (control[1].y - control[0].y) / length;
344    let s = (control[0].x - control[1].x) / length;
345    let u = (control[1].x * control[0].y - control[0].x * control[1].y) / length;
346    (r * control[2].x + s * control[2].y + u).abs()
347}
348
349fn inflection_points(control: [TextPoint; 4]) -> (u8, f64, f64) {
350    let a = add(
351        add(scale(-1.0, control[0]), scale(3.0, control[1])),
352        add(scale(-3.0, control[2]), control[3]),
353    );
354    let b = add(
355        scale(3.0, control[0]),
356        add(scale(-6.0, control[1]), scale(3.0, control[2])),
357    );
358    let c = add(scale(-3.0, control[0]), scale(3.0, control[1]));
359    let qa = 3.0 * cross(a, b);
360    let qb = 3.0 * cross(a, c);
361    let qc = cross(b, c);
362    let root_term = qb * qb - 4.0 * qa * qc;
363    if root_term < 0.0 || qa == 0.0 {
364        return (0, 0.0, 0.0);
365    }
366    classify_inflection_roots(
367        (-qb + root_term.sqrt()) / (2.0 * qa),
368        (-qb - root_term.sqrt()) / (2.0 * qa),
369    )
370}
371
372fn classify_inflection_roots(mut first: f64, mut second: f64) -> (u8, f64, f64) {
373    let first_inside = 0.0 < first && first < 1.0;
374    let second_inside = 0.0 < second && second < 1.0;
375    if first_inside && second_inside {
376        if first > second {
377            std::mem::swap(&mut first, &mut second);
378        }
379        if second - first > 0.000_01 {
380            (2, first, second)
381        } else {
382            (1, first, second)
383        }
384    } else if first_inside {
385        (1, first, 0.0)
386    } else if second_inside {
387        (1, second, 0.0)
388    } else {
389        (0, 0.0, 0.0)
390    }
391}
392
393fn add(left: TextPoint, right: TextPoint) -> TextPoint {
394    TextPoint {
395        x: left.x + right.x,
396        y: left.y + right.y,
397    }
398}
399
400fn sub(left: TextPoint, right: TextPoint) -> TextPoint {
401    TextPoint {
402        x: left.x - right.x,
403        y: left.y - right.y,
404    }
405}
406
407fn scale(value: f64, point: TextPoint) -> TextPoint {
408    TextPoint {
409        x: value * point.x,
410        y: value * point.y,
411    }
412}
413
414fn dot(left: TextPoint, right: TextPoint) -> f64 {
415    left.x * right.x + left.y * right.y
416}
417
418fn cross(left: TextPoint, right: TextPoint) -> f64 {
419    left.x * right.y - left.y * right.x
420}
421
422fn squared_norm(point: TextPoint) -> f64 {
423    dot(point, point)
424}
425
426fn invalid_error(message: &'static str) -> TextBezierError {
427    TextBezierError {
428        kind: TextBezierErrorKind::InvalidInput,
429        message,
430    }
431}