Skip to main content

kurbo/
quadbez.rs

1// Copyright 2018 the Kurbo Authors
2// SPDX-License-Identifier: Apache-2.0 OR MIT
3
4//! Quadratic Bézier segments.
5
6use core::ops::{Mul, Range};
7
8use arrayvec::ArrayVec;
9
10use crate::MAX_EXTREMA;
11use crate::common::{solve_cubic, solve_quadratic};
12use crate::{
13    Affine, CubicBez, Line, Nearest, ParamCurve, ParamCurveArclen, ParamCurveArea,
14    ParamCurveCurvature, ParamCurveDeriv, ParamCurveExtrema, ParamCurveNearest, PathEl, Point,
15    Rect, Shape,
16};
17
18#[cfg(not(feature = "std"))]
19use crate::common::FloatFuncs;
20
21/// A single quadratic Bézier segment.
22#[derive(Clone, Copy, Debug, PartialEq)]
23#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
24#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
25#[allow(missing_docs)]
26pub struct QuadBez {
27    pub p0: Point,
28    pub p1: Point,
29    pub p2: Point,
30}
31
32impl QuadBez {
33    /// Create a new quadratic Bézier segment.
34    #[inline]
35    pub fn new<V: Into<Point>>(p0: V, p1: V, p2: V) -> QuadBez {
36        QuadBez {
37            p0: p0.into(),
38            p1: p1.into(),
39            p2: p2.into(),
40        }
41    }
42
43    /// Raise the order by 1.
44    ///
45    /// Returns a cubic Bézier segment that exactly represents this quadratic.
46    #[inline]
47    pub fn raise(&self) -> CubicBez {
48        CubicBez::new(
49            self.p0,
50            self.p0 + (2.0 / 3.0) * (self.p1 - self.p0),
51            self.p2 + (2.0 / 3.0) * (self.p1 - self.p2),
52            self.p2,
53        )
54    }
55
56    /// Estimate the number of subdivisions for flattening.
57    pub(crate) fn estimate_subdiv(&self, sqrt_tol: f64) -> FlattenParams {
58        // Determine transformation to $y = x^2$ parabola.
59        let d01 = self.p1 - self.p0;
60        let d12 = self.p2 - self.p1;
61        let dd = d01 - d12;
62        let cross = (self.p2 - self.p0).cross(dd);
63        let x0 = d01.dot(dd) * cross.recip();
64        let x2 = d12.dot(dd) * cross.recip();
65        let scale = (cross / (dd.hypot() * (x2 - x0))).abs();
66
67        // Compute number of subdivisions needed.
68        let a0 = approx_parabola_integral(x0);
69        let a2 = approx_parabola_integral(x2);
70        let val = if scale.is_finite() {
71            let da = (a2 - a0).abs();
72            let sqrt_scale = scale.sqrt();
73            if x0.signum() == x2.signum() {
74                da * sqrt_scale
75            } else {
76                // Handle cusp case (segment contains curvature maximum)
77                let xmin = sqrt_tol / sqrt_scale;
78                sqrt_tol * da / approx_parabola_integral(xmin)
79            }
80        } else {
81            0.0
82        };
83        let u0 = approx_parabola_inv_integral(a0);
84        let u2 = approx_parabola_inv_integral(a2);
85        let uscale = (u2 - u0).recip();
86        FlattenParams {
87            a0,
88            a2,
89            u0,
90            uscale,
91            val,
92        }
93    }
94
95    // Maps a value from 0..1 to 0..1.
96    pub(crate) fn determine_subdiv_t(&self, params: &FlattenParams, x: f64) -> f64 {
97        let a = params.a0 + (params.a2 - params.a0) * x;
98        let u = approx_parabola_inv_integral(a);
99        (u - params.u0) * params.uscale
100    }
101
102    /// Is this quadratic Bezier curve finite?
103    #[inline]
104    pub const fn is_finite(&self) -> bool {
105        self.p0.is_finite() && self.p1.is_finite() && self.p2.is_finite()
106    }
107
108    /// Is this quadratic Bezier curve NaN?
109    #[inline]
110    pub const fn is_nan(&self) -> bool {
111        self.p0.is_nan() || self.p1.is_nan() || self.p2.is_nan()
112    }
113
114    /// Finds the value of `t` for which `self.eval(t)` is about `y`.
115    ///
116    /// Assumes that this segment is monotonic in `y` and that it crosses
117    /// the height `y`. (Under these assumptions, there is a unique answer.)
118    pub(crate) fn solve_monotonic_for_y(&self, y: f64) -> f64 {
119        let start = self.start();
120        let end = self.end();
121
122        debug_assert!(start.y.min(end.y) <= y && y <= start.y.max(end.y));
123        let a = end.y - 2.0 * self.p1.y + start.y;
124        let b = 2.0 * (self.p1.y - start.y);
125        let c = start.y - y;
126
127        for t in solve_quadratic(c, b, a) {
128            if (0.0..=1.0).contains(&t) {
129                return t;
130            }
131        }
132
133        // Even though we asserted that our y range contains `y`, it's possible
134        // that we failed to find a solution numerically. (For example, rounding
135        // of a, b, or c might have pushed the root outside of [0.0, 1.0].)
136        // If we failed to find a solution, the real solution should be close
137        // to one of the endpoints. So just find whichever endpoint was closer.
138        if (start.y - y).abs() <= (end.y - y).abs() {
139            0.0
140        } else {
141            1.0
142        }
143    }
144}
145
146/// An iterator for quadratic beziers.
147pub struct QuadBezIter {
148    quad: QuadBez,
149    ix: usize,
150}
151
152impl Shape for QuadBez {
153    type PathElementsIter<'iter> = QuadBezIter;
154
155    #[inline]
156    fn path_elements(&self, _tolerance: f64) -> QuadBezIter {
157        QuadBezIter { quad: *self, ix: 0 }
158    }
159
160    fn area(&self) -> f64 {
161        0.0
162    }
163
164    #[inline]
165    fn perimeter(&self, accuracy: f64) -> f64 {
166        self.arclen(accuracy)
167    }
168
169    fn winding(&self, _pt: Point) -> i32 {
170        0
171    }
172
173    #[inline]
174    fn bounding_box(&self) -> Rect {
175        ParamCurveExtrema::bounding_box(self)
176    }
177}
178
179impl Iterator for QuadBezIter {
180    type Item = PathEl;
181
182    fn next(&mut self) -> Option<PathEl> {
183        self.ix += 1;
184        match self.ix {
185            1 => Some(PathEl::MoveTo(self.quad.p0)),
186            2 => Some(PathEl::QuadTo(self.quad.p1, self.quad.p2)),
187            _ => None,
188        }
189    }
190}
191
192pub(crate) struct FlattenParams {
193    a0: f64,
194    a2: f64,
195    u0: f64,
196    uscale: f64,
197    /// The number of `subdivisions * 2 * sqrt_tol`.
198    pub(crate) val: f64,
199}
200
201/// An approximation to $\int (1 + 4x^2) ^ -0.25 dx$
202///
203/// This is used for flattening curves.
204fn approx_parabola_integral(x: f64) -> f64 {
205    const D: f64 = 0.67;
206    x / (1.0 - D + (D.powi(4) + 0.25 * x * x).sqrt().sqrt())
207}
208
209/// An approximation to the inverse parabola integral.
210fn approx_parabola_inv_integral(x: f64) -> f64 {
211    const B: f64 = 0.39;
212    x * (1.0 - B + (B * B + 0.25 * x * x).sqrt())
213}
214
215impl ParamCurve for QuadBez {
216    #[inline]
217    fn eval(&self, t: f64) -> Point {
218        let mt = 1.0 - t;
219        (self.p0.to_vec2() * (mt * mt)
220            + (self.p1.to_vec2() * (mt * 2.0) + self.p2.to_vec2() * t) * t)
221            .to_point()
222    }
223
224    fn subsegment(&self, range: Range<f64>) -> QuadBez {
225        let (t0, t1) = (range.start, range.end);
226        let p0 = self.eval(t0);
227        let p2 = self.eval(t1);
228        let p1 = p0 + (self.p1 - self.p0).lerp(self.p2 - self.p1, t0) * (t1 - t0);
229        QuadBez { p0, p1, p2 }
230    }
231
232    /// Subdivide into halves, using de Casteljau.
233    #[inline]
234    fn subdivide(&self) -> (QuadBez, QuadBez) {
235        let pm = self.eval(0.5);
236        (
237            QuadBez::new(self.p0, self.p0.midpoint(self.p1), pm),
238            QuadBez::new(pm, self.p1.midpoint(self.p2), self.p2),
239        )
240    }
241
242    #[inline]
243    fn start(&self) -> Point {
244        self.p0
245    }
246
247    #[inline]
248    fn end(&self) -> Point {
249        self.p2
250    }
251}
252
253impl ParamCurveDeriv for QuadBez {
254    type DerivResult = Line;
255
256    #[inline]
257    fn deriv(&self) -> Line {
258        Line::new(
259            (2.0 * (self.p1.to_vec2() - self.p0.to_vec2())).to_point(),
260            (2.0 * (self.p2.to_vec2() - self.p1.to_vec2())).to_point(),
261        )
262    }
263}
264
265impl ParamCurveArclen for QuadBez {
266    /// Arclength of a quadratic Bézier segment.
267    ///
268    /// This computation is based on an analytical formula. Since that formula suffers
269    /// from numerical instability when the curve is very close to a straight line, we
270    /// detect that case and fall back to Legendre-Gauss quadrature.
271    ///
272    /// Accuracy should be better than 1e-13 over the entire range.
273    ///
274    /// Adapted from <http://www.malczak.linuxpl.com/blog/quadratic-bezier-curve-length/>
275    /// with permission.
276    fn arclen(&self, _accuracy: f64) -> f64 {
277        let d2 = self.p0.to_vec2() - 2.0 * self.p1.to_vec2() + self.p2.to_vec2();
278        let a = d2.hypot2();
279        let d1 = self.p1 - self.p0;
280        let c = d1.hypot2();
281        if a < 5e-4 * c {
282            // This case happens for nearly straight Béziers.
283            //
284            // Calculate arclength using Legendre-Gauss quadrature using formula from Behdad
285            // in https://github.com/Pomax/BezierInfo-2/issues/77
286            let v0 = (-0.492943519233745 * self.p0.to_vec2()
287                + 0.430331482911935 * self.p1.to_vec2()
288                + 0.0626120363218102 * self.p2.to_vec2())
289            .hypot();
290            let v1 = ((self.p2 - self.p0) * 0.4444444444444444).hypot();
291            let v2 = (-0.0626120363218102 * self.p0.to_vec2()
292                - 0.430331482911935 * self.p1.to_vec2()
293                + 0.492943519233745 * self.p2.to_vec2())
294            .hypot();
295            return v0 + v1 + v2;
296        }
297        let b = 2.0 * d2.dot(d1);
298
299        let sabc = (a + b + c).sqrt();
300        let a2 = a.powf(-0.5);
301        let a32 = a2.powi(3);
302        let c2 = 2.0 * c.sqrt();
303        let ba_c2 = b * a2 + c2;
304
305        let v0 = 0.25 * a2 * a2 * b * (2.0 * sabc - c2) + sabc;
306        // TODO: justify and fine-tune this exact constant.
307        // The factor of a2 here is a little arbitrary: we really want
308        // to test whether ba_c2 is small, but it's also important for
309        // this comparison to be scale-invariant. We chose a2 (instead of,
310        // for example, c2 on the rhs) because it's unchanged under
311        // reversing the parametrization.
312        if ba_c2 * a2 < 1e-13 {
313            // This case happens for Béziers with a sharp kink.
314            v0
315        } else {
316            v0 + 0.25
317                * a32
318                * (4.0 * c * a - b * b)
319                * (((2.0 * a + b) * a2 + 2.0 * sabc) / ba_c2).ln()
320        }
321    }
322}
323
324impl ParamCurveArea for QuadBez {
325    #[inline]
326    fn signed_area(&self) -> f64 {
327        (self.p0.x * (2.0 * self.p1.y + self.p2.y) + 2.0 * self.p1.x * (self.p2.y - self.p0.y)
328            - self.p2.x * (self.p0.y + 2.0 * self.p1.y))
329            * (1.0 / 6.0)
330    }
331}
332
333impl ParamCurveNearest for QuadBez {
334    /// Find the nearest point, using analytical algorithm based on cubic root finding.
335    fn nearest(&self, p: Point, _accuracy: f64) -> Nearest {
336        fn eval_t(p: Point, t_best: &mut f64, r_best: &mut Option<f64>, t: f64, p0: Point) {
337            let r = (p0 - p).hypot2();
338            if r_best.map(|r_best| r < r_best).unwrap_or(true) {
339                *r_best = Some(r);
340                *t_best = t;
341            }
342        }
343        fn try_t(
344            q: &QuadBez,
345            p: Point,
346            t_best: &mut f64,
347            r_best: &mut Option<f64>,
348            t: f64,
349        ) -> bool {
350            if !(0.0..=1.0).contains(&t) {
351                return true;
352            }
353            eval_t(p, t_best, r_best, t, q.eval(t));
354            false
355        }
356        let d0 = self.p1 - self.p0;
357        let d1 = self.p0.to_vec2() + self.p2.to_vec2() - 2.0 * self.p1.to_vec2();
358        let d = self.p0 - p;
359        let c0 = d.dot(d0);
360        let c1 = 2.0 * d0.hypot2() + d.dot(d1);
361        let c2 = 3.0 * d1.dot(d0);
362        let c3 = d1.hypot2();
363        let roots = solve_cubic(c0, c1, c2, c3);
364        let mut r_best = None;
365        let mut t_best = 0.0;
366        let mut need_ends = false;
367        if roots.is_empty() {
368            need_ends = true;
369        }
370        for &t in &roots {
371            need_ends |= try_t(self, p, &mut t_best, &mut r_best, t);
372        }
373        if need_ends {
374            eval_t(p, &mut t_best, &mut r_best, 0.0, self.p0);
375            eval_t(p, &mut t_best, &mut r_best, 1.0, self.p2);
376        }
377
378        Nearest {
379            t: t_best,
380            distance_sq: r_best.unwrap(),
381        }
382    }
383}
384
385impl ParamCurveCurvature for QuadBez {}
386
387impl ParamCurveExtrema for QuadBez {
388    fn extrema(&self) -> ArrayVec<f64, MAX_EXTREMA> {
389        let mut result = ArrayVec::new();
390        let d0 = self.p1 - self.p0;
391        let d1 = self.p2 - self.p1;
392        let dd = d1 - d0;
393        if dd.x != 0.0 {
394            let t = -d0.x / dd.x;
395            if t > 0.0 && t < 1.0 {
396                result.push(t);
397            }
398        }
399        if dd.y != 0.0 {
400            let t = -d0.y / dd.y;
401            if t > 0.0 && t < 1.0 {
402                result.push(t);
403                if result.len() == 2 && result[0] > t {
404                    result.swap(0, 1);
405                }
406            }
407        }
408        result
409    }
410}
411
412impl Mul<QuadBez> for Affine {
413    type Output = QuadBez;
414
415    #[inline]
416    fn mul(self, other: QuadBez) -> QuadBez {
417        QuadBez {
418            p0: self * other.p0,
419            p1: self * other.p1,
420            p2: self * other.p2,
421        }
422    }
423}
424
425#[cfg(test)]
426mod tests {
427    use crate::{
428        Affine, Nearest, ParamCurve, ParamCurveArclen, ParamCurveArea, ParamCurveDeriv,
429        ParamCurveExtrema, ParamCurveNearest, Point, QuadBez,
430    };
431
432    fn assert_near(p0: Point, p1: Point, epsilon: f64) {
433        assert!((p1 - p0).hypot() < epsilon, "{p0:?} != {p1:?}");
434    }
435
436    #[test]
437    fn quadbez_deriv() {
438        let q = QuadBez::new((0.0, 0.0), (0.0, 0.5), (1.0, 1.0));
439        let deriv = q.deriv();
440
441        let n = 10;
442        for i in 0..=n {
443            let t = (i as f64) * (n as f64).recip();
444            let delta = 1e-6;
445            let p = q.eval(t);
446            let p1 = q.eval(t + delta);
447            let d_approx = (p1 - p) * delta.recip();
448            let d = deriv.eval(t).to_vec2();
449            assert!((d - d_approx).hypot() < delta * 2.0);
450        }
451    }
452
453    #[test]
454    fn quadbez_arclen() {
455        let q = QuadBez::new((0.0, 0.0), (0.0, 0.5), (1.0, 1.0));
456        let true_arclen = 0.5 * 5.0f64.sqrt() + 0.25 * (2.0 + 5.0f64.sqrt()).ln();
457        for i in 0..12 {
458            let accuracy = 0.1f64.powi(i);
459            let est = q.arclen(accuracy);
460            let error = est - true_arclen;
461            assert!(error.abs() < accuracy, "{est} != {true_arclen}");
462        }
463    }
464
465    #[test]
466    fn quadbez_arclen_pathological() {
467        let q = QuadBez::new((-1.0, 0.0), (1.03, 0.0), (1.0, 0.0));
468        let true_arclen = 2.0008737864167325; // A rough empirical calculation
469        let accuracy = 1e-11;
470        let est = q.arclen(accuracy);
471        assert!(
472            (est - true_arclen).abs() < accuracy,
473            "{est} != {true_arclen}"
474        );
475    }
476
477    #[test]
478    fn quadbez_subsegment() {
479        let q = QuadBez::new((3.1, 4.1), (5.9, 2.6), (5.3, 5.8));
480        let t0 = 0.1;
481        let t1 = 0.8;
482        let qs = q.subsegment(t0..t1);
483        let epsilon = 1e-12;
484        let n = 10;
485        for i in 0..=n {
486            let t = (i as f64) * (n as f64).recip();
487            let ts = t0 + t * (t1 - t0);
488            assert_near(q.eval(ts), qs.eval(t), epsilon);
489        }
490    }
491
492    #[test]
493    fn quadbez_raise() {
494        let q = QuadBez::new((3.1, 4.1), (5.9, 2.6), (5.3, 5.8));
495        let c = q.raise();
496        let qd = q.deriv();
497        let cd = c.deriv();
498        let epsilon = 1e-12;
499        let n = 10;
500        for i in 0..=n {
501            let t = (i as f64) * (n as f64).recip();
502            assert_near(q.eval(t), c.eval(t), epsilon);
503            assert_near(qd.eval(t), cd.eval(t), epsilon);
504        }
505    }
506
507    #[test]
508    fn quadbez_signed_area() {
509        // y = 1 - x^2
510        let q = QuadBez::new((1.0, 0.0), (0.5, 1.0), (0.0, 1.0));
511        let epsilon = 1e-12;
512        assert!((q.signed_area() - 2.0 / 3.0).abs() < epsilon);
513        assert!(((Affine::rotate(0.5) * q).signed_area() - 2.0 / 3.0).abs() < epsilon);
514        assert!(((Affine::translate((0.0, 1.0)) * q).signed_area() - 3.5 / 3.0).abs() < epsilon);
515        assert!(((Affine::translate((1.0, 0.0)) * q).signed_area() - 3.5 / 3.0).abs() < epsilon);
516    }
517
518    fn verify(result: Nearest, expected: f64) {
519        assert!(
520            (result.t - expected).abs() < 1e-6,
521            "got {result:?} expected {expected}"
522        );
523    }
524
525    #[test]
526    fn quadbez_nearest() {
527        // y = x^2
528        let q = QuadBez::new((-1.0, 1.0), (0.0, -1.0), (1.0, 1.0));
529        verify(q.nearest((0.0, 0.0).into(), 1e-3), 0.5);
530        verify(q.nearest((0.0, 0.1).into(), 1e-3), 0.5);
531        verify(q.nearest((0.0, -0.1).into(), 1e-3), 0.5);
532        verify(q.nearest((0.5, 0.25).into(), 1e-3), 0.75);
533        verify(q.nearest((1.0, 1.0).into(), 1e-3), 1.0);
534        verify(q.nearest((1.1, 1.1).into(), 1e-3), 1.0);
535        verify(q.nearest((-1.1, 1.1).into(), 1e-3), 0.0);
536        let a = Affine::rotate(0.5);
537        verify((a * q).nearest(a * Point::new(0.5, 0.25), 1e-3), 0.75);
538    }
539
540    // This test exposes a degenerate case in the solver used internally
541    // by the "nearest" calculation - the cubic term is zero.
542    #[test]
543    fn quadbez_nearest_low_order() {
544        let q = QuadBez::new((-1.0, 0.0), (0.0, 0.0), (1.0, 0.0));
545
546        verify(q.nearest((0.0, 0.0).into(), 1e-3), 0.5);
547        verify(q.nearest((0.0, 1.0).into(), 1e-3), 0.5);
548    }
549
550    #[test]
551    fn quadbez_nearest_rounding_panic() {
552        let quad = QuadBez::new(
553            (-1.0394736842105263, 0.0),
554            (0.8210526315789474, -1.511111111111111),
555            (0.0, 1.9333333333333333),
556        );
557        let test = Point::new(-1.7976931348623157e308, 0.8571428571428571);
558        // accuracy ignored
559        let _res = quad.nearest(test, 1e-6);
560        // if we got here then we didn't panic
561    }
562
563    #[test]
564    fn quadbez_extrema() {
565        // y = x^2
566        let q = QuadBez::new((-1.0, 1.0), (0.0, -1.0), (1.0, 1.0));
567        let extrema = q.extrema();
568        assert_eq!(extrema.len(), 1);
569        assert!((extrema[0] - 0.5).abs() < 1e-6);
570
571        let q = QuadBez::new((0.0, 0.5), (1.0, 1.0), (0.5, 0.0));
572        let extrema = q.extrema();
573        assert_eq!(extrema.len(), 2);
574        assert!((extrema[0] - 1.0 / 3.0).abs() < 1e-6);
575        assert!((extrema[1] - 2.0 / 3.0).abs() < 1e-6);
576
577        // Reverse direction
578        let q = QuadBez::new((0.5, 0.0), (1.0, 1.0), (0.0, 0.5));
579        let extrema = q.extrema();
580        assert_eq!(extrema.len(), 2);
581        assert!((extrema[0] - 1.0 / 3.0).abs() < 1e-6);
582        assert!((extrema[1] - 2.0 / 3.0).abs() < 1e-6);
583    }
584
585    // A regression test for #477: the approximate-linearity test for
586    // using the analytic solution needs to be scale-invariant.
587    #[test]
588    fn perimeter_not_nan() {
589        let q = QuadBez::new((2685., -1251.), (2253., -1303.), (2253., -1303.));
590
591        let len = q.arclen(crate::DEFAULT_ACCURACY);
592        assert!(len.is_finite());
593    }
594}