Coverage Report

Created: 2026-04-01 07:11

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