Skip to main content

cranpose_ui_graphics/
stroke.rs

1//! Stroke styling and analytic arc geometry.
2//!
3//! # Angle convention
4//!
5//! Every angle in this module is expressed in **radians**, with `0` pointing
6//! along the **+X axis** and increasing angles sweeping **clockwise on
7//! screen**. Cranpose uses y-down device coordinates, so a point on the arc of
8//! radius `r` at angle `θ` is
9//!
10//! ```text
11//! (center.x + r * cos(θ), center.y + r * sin(θ))
12//! ```
13//!
14//! which — because `y` grows downwards — visually rotates clockwise as `θ`
15//! grows. This is exactly the convention already baked into the sweep-gradient
16//! branch of `shape.wgsl`, which derives its parameter from `atan2(dy, dx)`.
17
18use crate::{Point, Rect};
19
20/// Shape of the two ends of an open stroked path (an arc, today).
21#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
22pub enum StrokeCap {
23    /// Flat end exactly at the geometric end of the path.
24    #[default]
25    Butt,
26    /// Semicircular end bulging half the stroke width past the path end.
27    Round,
28    /// Flat end projected half the stroke width past the path end.
29    Square,
30}
31
32/// Shape produced where two stroked segments meet at a corner.
33#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
34pub enum StrokeJoin {
35    /// Extend the outer edges until they meet in a sharp point.
36    #[default]
37    Miter,
38    /// Fill the corner with a circular arc of half the stroke width.
39    Round,
40    /// Cut the corner off with a straight chamfer.
41    Bevel,
42}
43
44/// Describes how an outline is stroked.
45///
46/// The stroke is *centered* on the geometry: it extends `width / 2` to either
47/// side of the path, matching Skia / Jetpack Compose semantics.
48#[derive(Clone, Copy, Debug, PartialEq)]
49pub struct Stroke {
50    /// Total stroke width in the caller's coordinate space (dp for
51    /// [`crate::DrawScope`] callers).
52    pub width: f32,
53    pub cap: StrokeCap,
54    pub join: StrokeJoin,
55}
56
57impl Stroke {
58    /// A `width`-wide stroke with butt caps and miter joins.
59    pub const fn new(width: f32) -> Self {
60        Self {
61            width,
62            cap: StrokeCap::Butt,
63            join: StrokeJoin::Miter,
64        }
65    }
66
67    pub const fn with_width(mut self, width: f32) -> Self {
68        self.width = width;
69        self
70    }
71
72    pub const fn with_cap(mut self, cap: StrokeCap) -> Self {
73        self.cap = cap;
74        self
75    }
76
77    pub const fn with_join(mut self, join: StrokeJoin) -> Self {
78        self.join = join;
79        self
80    }
81
82    /// Half the stroke width, clamped to a finite non-negative value.
83    ///
84    /// This is the amount the stroke bleeds outside (and inside) the geometry.
85    pub fn half_width(&self) -> f32 {
86        if self.width.is_finite() {
87            (self.width * 0.5).max(0.0)
88        } else {
89            0.0
90        }
91    }
92
93    /// A stroke is renderable only when it has a strictly positive, finite width.
94    pub fn is_visible(&self) -> bool {
95        self.width.is_finite() && self.width > 0.0
96    }
97
98    /// Scales the stroke width (used when a layer transform scales the shape).
99    pub fn scaled(&self, scale: f32) -> Self {
100        Self {
101            width: self.width * scale,
102            ..*self
103        }
104    }
105}
106
107impl Default for Stroke {
108    fn default() -> Self {
109        Self::new(1.0)
110    }
111}
112
113/// Full turn in radians.
114pub const TAU: f32 = std::f32::consts::PI * 2.0;
115
116/// A resolved circular *band* between two radii, limited to an angular sweep.
117///
118/// Both a stroked arc and a filled annular sector lower to this single form:
119///
120/// * stroked arc — `inner = radius - width/2`, `outer = radius + width/2`,
121///   ends shaped by the stroke's [`StrokeCap`];
122/// * filled annular sector — `inner`/`outer` as given, always butt (flat
123///   radial) ends.
124///
125/// Values are normalized on construction: `sweep_angle` is non-negative and at
126/// most [`TAU`], `outer_radius >= inner_radius >= 0`, and non-finite inputs
127/// collapse to a degenerate geometry (see [`ArcGeometry::is_degenerate`]).
128#[derive(Clone, Copy, Debug, PartialEq)]
129pub struct ArcGeometry {
130    pub center: Point,
131    pub inner_radius: f32,
132    pub outer_radius: f32,
133    /// Normalized to `[0, TAU)`.
134    pub start_angle: f32,
135    /// Normalized to `[0, TAU]`.
136    pub sweep_angle: f32,
137    pub cap: StrokeCap,
138}
139
140/// Exact `x.floor()` without the libm call `f32::floor` lowers to on armv7
141/// (no `vrintm` there): truncate via int cast, fix up negatives. Bit-equal
142/// to `floorf` for every input — casts only run below 2^23, where i32 cannot
143/// saturate, and at 2^23 and above every finite f32 is already an integer.
144/// NaN fails the range test and passes through unchanged, like `floorf`.
145#[inline]
146fn exact_floor(x: f32) -> f32 {
147    if x == 0.0 {
148        // The int round-trip would turn -0.0 into +0.0; floorf keeps the sign.
149        return x;
150    }
151    if x.abs() < 8_388_608.0 {
152        let truncated = x as i32 as f32;
153        truncated - ((x < truncated) as i32 as f32)
154    } else {
155        x
156    }
157}
158
159/// `x mod TAU` into `[0, TAU)` without `rem_euclid`, whose `fmodf` lowers to
160/// the software routine in compiler_builtins on aarch64 Android and shows up
161/// in profiles at two calls per arc per frame. Multiply-floor keeps it to a
162/// couple of instructions; the fixup folds the one-ulp overshoot cases back
163/// into range.
164#[inline]
165fn wrap_angle_tau(x: f32) -> f32 {
166    let wrapped = x - exact_floor(x * (1.0 / TAU)) * TAU;
167    if wrapped >= TAU {
168        wrapped - TAU
169    } else if wrapped < 0.0 {
170        0.0
171    } else {
172        wrapped
173    }
174}
175
176/// `(sin, cos)` by refined parabola, absolute error under [`FAST_TRIG_ERR`].
177/// Bounding boxes only need trig that is close — the box gets padded by the
178/// worst-case position error afterwards — and libm's `sincosf`, called twice
179/// per partial arc, was one of the larger single costs of recording a
180/// shape-heavy frame on a watch-class core.
181#[inline]
182fn fast_sin_cos(angle: f32) -> (f32, f32) {
183    use std::f32::consts::{FRAC_PI_2, PI};
184    #[inline]
185    fn fold_sin(x: f32) -> f32 {
186        const B: f32 = 4.0 / PI;
187        const C: f32 = -4.0 / (PI * PI);
188        let y = B * x + C * x * x.abs();
189        0.225 * (y * y.abs() - y) + y
190    }
191    let x = wrap_angle_tau(angle);
192    let x = if x > PI { x - TAU } else { x };
193    let mut c = x + FRAC_PI_2;
194    if c > PI {
195        c -= TAU;
196    }
197    (fold_sin(x), fold_sin(c))
198}
199
200/// Worst-case absolute error of [`fast_sin_cos`]; bounds derived from it are
201/// padded by radius x this so the approximate box always contains the exact
202/// shape.
203const FAST_TRIG_ERR: f32 = 1.3e-3;
204
205impl ArcGeometry {
206    /// Normalizing constructor. Never panics and never stores a NaN.
207    pub fn new(
208        center: Point,
209        inner_radius: f32,
210        outer_radius: f32,
211        start_angle: f32,
212        sweep_angle: f32,
213        cap: StrokeCap,
214    ) -> Self {
215        let finite = center.x.is_finite()
216            && center.y.is_finite()
217            && inner_radius.is_finite()
218            && outer_radius.is_finite()
219            && start_angle.is_finite()
220            && sweep_angle.is_finite();
221        if !finite {
222            return Self::DEGENERATE;
223        }
224
225        let outer = outer_radius.max(0.0);
226        let inner = inner_radius.clamp(0.0, outer);
227
228        // Fold negative sweeps into a positive sweep starting at the other end
229        // so downstream math (and the shader) only ever sees `0 ..= TAU`.
230        let (mut start, mut sweep) = if sweep_angle < 0.0 {
231            (start_angle + sweep_angle, -sweep_angle)
232        } else {
233            (start_angle, sweep_angle)
234        };
235        if sweep >= TAU {
236            // A closed ring: caps can never be seen, and forcing `Round` keeps
237            // the shader from clipping a hairline seam at the wrap point.
238            sweep = TAU;
239            start = 0.0;
240        }
241        start = wrap_angle_tau(start);
242        if !start.is_finite() {
243            start = 0.0;
244        }
245        let cap = if sweep >= TAU { StrokeCap::Round } else { cap };
246
247        Self {
248            center,
249            inner_radius: inner,
250            outer_radius: outer,
251            start_angle: start,
252            sweep_angle: sweep,
253            cap,
254        }
255    }
256
257    const DEGENERATE: Self = Self {
258        center: Point::ZERO,
259        inner_radius: 0.0,
260        outer_radius: 0.0,
261        start_angle: 0.0,
262        sweep_angle: 0.0,
263        cap: StrokeCap::Butt,
264    };
265
266    /// Radius of the band's centerline (`ra` in the analytic arc SDF).
267    pub fn mid_radius(&self) -> f32 {
268        (self.inner_radius + self.outer_radius) * 0.5
269    }
270
271    /// Half the band thickness (`rb` in the analytic arc SDF). Also the radius
272    /// of a round cap and the projection distance of a square cap.
273    pub fn half_thickness(&self) -> f32 {
274        (self.outer_radius - self.inner_radius) * 0.5
275    }
276
277    /// True when the band encloses no area and therefore must not be emitted.
278    pub fn is_degenerate(&self) -> bool {
279        !(self.outer_radius > 0.0
280            && self.outer_radius > self.inner_radius
281            && self.sweep_angle > 0.0)
282    }
283
284    /// True when `angle` lies inside `[start, start + sweep]` (mod `TAU`).
285    pub fn contains_angle(&self, angle: f32) -> bool {
286        if self.sweep_angle >= TAU {
287            return true;
288        }
289        let delta = wrap_angle_tau(angle - self.start_angle);
290        delta <= self.sweep_angle + 1e-6
291    }
292
293    /// Scales radii and translates the center. Angles are unchanged, so this is
294    /// only valid for a uniform (non-mirroring) scale.
295    pub fn scaled_about(&self, center: Point, scale: f32) -> Self {
296        Self {
297            center,
298            inner_radius: self.inner_radius * scale,
299            outer_radius: self.outer_radius * scale,
300            ..*self
301        }
302    }
303
304    /// Tight axis-aligned bounding box of the rendered band, caps included.
305    ///
306    /// The box is the union of
307    /// * the two radial ends (inner and outer radius, extended for
308    ///   round/square caps), and
309    /// * the outer-radius point at every axis direction (0, 90, 180, 270
310    ///   degrees) that the sweep actually crosses.
311    ///
312    /// Sampling only the endpoints would be wrong for any sweep that crosses an
313    /// axis: a 0..270 degree sweep reaches `center.x + outer` *and*
314    /// `center.x - outer` even though neither endpoint does.
315    pub fn bounds(&self) -> Rect {
316        if self.is_degenerate() {
317            return Rect {
318                x: self.center.x,
319                y: self.center.y,
320                width: 0.0,
321                height: 0.0,
322            };
323        }
324
325        // A closed ring reaches `center ± outer` on all four axes and nothing
326        // in it — caps included — reaches further, so its box needs no
327        // endpoint trig at all. Most primitives in a particle-heavy scene are
328        // full circles (dots, rings, glow discs), and the two `sin_cos` calls
329        // below were the single largest trig cost of recording such a frame.
330        // (`new` forces `Round` at a full sweep; a hand-built square cap can
331        // project past `outer` along the tangent, so it keeps the long path.)
332        if self.sweep_angle >= TAU && self.cap != StrokeCap::Square {
333            let r = self.outer_radius;
334            return Rect {
335                x: self.center.x - r,
336                y: self.center.y - r,
337                width: r + r,
338                height: r + r,
339            };
340        }
341
342        let mut min_x = f32::INFINITY;
343        let mut min_y = f32::INFINITY;
344        let mut max_x = f32::NEG_INFINITY;
345        let mut max_y = f32::NEG_INFINITY;
346        let mut include = |x: f32, y: f32| {
347            min_x = min_x.min(x);
348            min_y = min_y.min(y);
349            max_x = max_x.max(x);
350            max_y = max_y.max(y);
351        };
352
353        let rb = self.half_thickness();
354        let ra = self.mid_radius();
355        let end_angle = self.start_angle + self.sweep_angle;
356
357        for (angle, outward) in [(self.start_angle, -1.0f32), (end_angle, 1.0f32)] {
358            let (sin, cos) = fast_sin_cos(angle);
359            match self.cap {
360                StrokeCap::Butt => {
361                    include(
362                        self.center.x + cos * self.inner_radius,
363                        self.center.y + sin * self.inner_radius,
364                    );
365                    include(
366                        self.center.x + cos * self.outer_radius,
367                        self.center.y + sin * self.outer_radius,
368                    );
369                }
370                StrokeCap::Square => {
371                    // Projected along the tangent, away from the sweep.
372                    let tx = -sin * rb * outward;
373                    let ty = cos * rb * outward;
374                    include(
375                        self.center.x + cos * self.inner_radius + tx,
376                        self.center.y + sin * self.inner_radius + ty,
377                    );
378                    include(
379                        self.center.x + cos * self.outer_radius + tx,
380                        self.center.y + sin * self.outer_radius + ty,
381                    );
382                }
383                StrokeCap::Round => {
384                    // Semicircle of radius `rb` centered on the band centerline.
385                    let cx = self.center.x + cos * ra;
386                    let cy = self.center.y + sin * ra;
387                    include(cx - rb, cy - rb);
388                    include(cx + rb, cy + rb);
389                }
390            }
391        }
392
393        // The axis directions have constant sines and cosines; going through
394        // `sin_cos` here doubled the trig cost of every arc in a shape-heavy
395        // scene.
396        const AXIS_DIRECTIONS: [(f32, f32); 4] = [(0.0, 1.0), (1.0, 0.0), (0.0, -1.0), (-1.0, 0.0)];
397        for (quadrant, (sin, cos)) in AXIS_DIRECTIONS.into_iter().enumerate() {
398            let angle = quadrant as f32 * std::f32::consts::FRAC_PI_2;
399            if self.contains_angle(angle) {
400                include(
401                    self.center.x + cos * self.outer_radius,
402                    self.center.y + sin * self.outer_radius,
403                );
404            }
405        }
406
407        // The endpoint positions above came from approximate trig; grow the
408        // box by their worst-case error (sub-pixel at any plausible radius)
409        // so it still contains the exact shape. Square caps project rb along
410        // an approximate tangent on top of the radial term, hence the sum;
411        // the absolute floor keeps the containment margin real for tiny
412        // radii where f32 rounding competes with the scaled term.
413        let pad = (self.outer_radius + rb) * FAST_TRIG_ERR + 0.02;
414        Rect {
415            x: min_x - pad,
416            y: min_y - pad,
417            width: (max_x - min_x + pad + pad).max(0.0),
418            height: (max_y - min_y + pad + pad).max(0.0),
419        }
420    }
421}
422
423/// Resolves the `(inner, outer, cap)` band described by a
424/// [`crate::DrawPrimitive::Arc`].
425///
426/// * `stroke = Some(_)` — a stroked arc centered on `radius`.
427/// * `stroke = None` — a filled annular sector from `inner_radius` to `radius`
428///   with flat (butt) radial ends. `inner_radius <= 0` yields a filled pie
429///   wedge.
430///
431/// Non-finite input collapses to an empty band so the caller drops the draw
432/// instead of pushing NaN down the pipeline.
433pub fn arc_band(radius: f32, inner_radius: f32, stroke: Option<Stroke>) -> (f32, f32, StrokeCap) {
434    match stroke {
435        Some(stroke) => {
436            if !radius.is_finite() || !stroke.is_visible() {
437                return (0.0, 0.0, stroke.cap);
438            }
439            let half = stroke.half_width();
440            let radius = radius.max(0.0);
441            ((radius - half).max(0.0), radius + half, stroke.cap)
442        }
443        None => {
444            if !radius.is_finite() || !inner_radius.is_finite() {
445                return (0.0, 0.0, StrokeCap::Butt);
446            }
447            let outer = radius.max(0.0);
448            let inner = inner_radius.clamp(0.0, outer);
449            (inner, outer, StrokeCap::Butt)
450        }
451    }
452}
453
454/// Grows `rect` by `amount` on every side, clamping to a non-negative size.
455pub fn inflate_rect(rect: Rect, amount: f32) -> Rect {
456    if !amount.is_finite() || amount <= 0.0 {
457        return rect;
458    }
459    Rect {
460        x: rect.x - amount,
461        y: rect.y - amount,
462        width: (rect.width + amount * 2.0).max(0.0),
463        height: (rect.height + amount * 2.0).max(0.0),
464    }
465}
466
467#[cfg(test)]
468mod tests {
469    use super::*;
470    use std::f32::consts::{FRAC_PI_2, PI};
471
472    /// Bounds are deliberately conservative now: endpoint trig is
473    /// approximate and the box is padded by its worst-case error, so
474    /// "hugs"/"tight" means within that documented slack, not within float
475    /// noise. The containment property test below is the strict guard.
476    fn approx(a: f32, b: f32) -> bool {
477        (a - b).abs() < 0.15
478    }
479
480    /// What a pinch or a scale-on-press does to an arc: the ring grows about a
481    /// point without opening or closing. The angles must survive untouched, or
482    /// a progress ring would appear to jump backwards while being scaled.
483    #[test]
484    fn scaling_an_arc_moves_its_centre_and_its_radii_and_nothing_else() {
485        let arc = ArcGeometry::new(
486            Point { x: 10.0, y: 20.0 },
487            4.0,
488            10.0,
489            FRAC_PI_2,
490            PI,
491            StrokeCap::Round,
492        );
493        let moved = arc.scaled_about(Point { x: 100.0, y: 200.0 }, 2.5);
494
495        assert_eq!(moved.center, Point { x: 100.0, y: 200.0 });
496        assert_eq!(moved.inner_radius, 10.0);
497        assert_eq!(moved.outer_radius, 25.0);
498        assert_eq!(moved.start_angle, arc.start_angle);
499        assert_eq!(moved.sweep_angle, arc.sweep_angle);
500        assert_eq!(moved.cap, arc.cap);
501
502        // Scaling by one is the identity apart from the centre it is told.
503        let same = arc.scaled_about(arc.center, 1.0);
504        assert_eq!(same, arc);
505    }
506
507    #[test]
508    fn exact_floor_is_bit_equal_to_floorf() {
509        let mut probes: Vec<f32> = vec![
510            0.0,
511            -0.0,
512            0.5,
513            -0.5,
514            1.0,
515            -1.0,
516            8_388_607.5,
517            -8_388_607.5,
518            8_388_608.0,
519            -8_388_608.0,
520            1.0e30,
521            -1.0e30,
522            f32::INFINITY,
523            f32::NEG_INFINITY,
524            f32::MIN_POSITIVE,
525            -f32::MIN_POSITIVE,
526        ];
527        for i in -4000..4000 {
528            probes.push(i as f32 * 0.01737);
529            probes.push(i as f32 * PI);
530        }
531        for x in probes {
532            assert_eq!(
533                exact_floor(x).to_bits(),
534                x.floor().to_bits(),
535                "exact_floor({x}) diverged from floorf"
536            );
537        }
538        assert!(exact_floor(f32::NAN).is_nan());
539    }
540
541    #[test]
542    fn stroke_builders_compose() {
543        let stroke = Stroke::new(4.0)
544            .with_cap(StrokeCap::Round)
545            .with_join(StrokeJoin::Bevel);
546        assert_eq!(stroke.width, 4.0);
547        assert_eq!(stroke.cap, StrokeCap::Round);
548        assert_eq!(stroke.join, StrokeJoin::Bevel);
549        assert_eq!(stroke.half_width(), 2.0);
550        assert!(stroke.is_visible());
551        assert_eq!(Stroke::default(), Stroke::new(1.0));
552        assert_eq!(Stroke::new(4.0).with_width(6.0).width, 6.0);
553    }
554
555    #[test]
556    fn stroke_rejects_non_positive_and_non_finite_widths() {
557        assert!(!Stroke::new(0.0).is_visible());
558        assert!(!Stroke::new(-3.0).is_visible());
559        assert!(!Stroke::new(f32::NAN).is_visible());
560        assert!(!Stroke::new(f32::INFINITY).is_visible());
561        assert_eq!(Stroke::new(f32::NAN).half_width(), 0.0);
562        assert_eq!(Stroke::new(-3.0).half_width(), 0.0);
563    }
564
565    #[test]
566    fn arc_geometry_normalizes_negative_sweeps() {
567        let arc = ArcGeometry::new(Point::ZERO, 1.0, 2.0, PI, -FRAC_PI_2, StrokeCap::Butt);
568        assert!(approx(arc.start_angle, PI - FRAC_PI_2));
569        assert!(approx(arc.sweep_angle, FRAC_PI_2));
570    }
571
572    #[test]
573    fn arc_geometry_clamps_full_turns_and_forces_round_caps() {
574        let arc = ArcGeometry::new(Point::ZERO, 1.0, 2.0, 0.3, TAU * 3.0, StrokeCap::Butt);
575        assert_eq!(arc.sweep_angle, TAU);
576        assert_eq!(
577            arc.cap,
578            StrokeCap::Round,
579            "a closed ring must not clip its (invisible) caps"
580        );
581        assert!(arc.contains_angle(0.0));
582        assert!(arc.contains_angle(PI));
583    }
584
585    #[test]
586    fn arc_geometry_sanitizes_non_finite_input() {
587        for arc in [
588            ArcGeometry::new(
589                Point::new(f32::NAN, 0.0),
590                1.0,
591                2.0,
592                0.0,
593                1.0,
594                StrokeCap::Butt,
595            ),
596            ArcGeometry::new(Point::ZERO, f32::NAN, 2.0, 0.0, 1.0, StrokeCap::Butt),
597            ArcGeometry::new(Point::ZERO, 1.0, f32::INFINITY, 0.0, 1.0, StrokeCap::Butt),
598            ArcGeometry::new(Point::ZERO, 1.0, 2.0, f32::NAN, 1.0, StrokeCap::Butt),
599            ArcGeometry::new(Point::ZERO, 1.0, 2.0, 0.0, f32::NAN, StrokeCap::Butt),
600        ] {
601            assert!(arc.is_degenerate());
602            let bounds = arc.bounds();
603            for value in [bounds.x, bounds.y, bounds.width, bounds.height] {
604                assert!(value.is_finite(), "degenerate arc bounds must stay finite");
605            }
606        }
607    }
608
609    /// The strict contract of approximate bounds: the box must CONTAIN the
610    /// box the exact-trig algorithm produces, and must not exceed it by more
611    /// than the documented pad. Sweeps every cap, many radii and angles.
612    #[test]
613    fn approximate_bounds_contain_the_exact_box_within_documented_slack() {
614        for radius in [2.0f32, 10.0, 57.0, 204.0] {
615            for cap in [StrokeCap::Butt, StrokeCap::Round, StrokeCap::Square] {
616                for step in 0..48 {
617                    let start = step as f32 * (TAU / 48.0) * 1.031;
618                    for sweep in [0.05f32, 0.9, FRAC_PI_2, 3.6] {
619                        let arc = ArcGeometry::new(
620                            Point::new(11.0, -7.0),
621                            radius * 0.55,
622                            radius,
623                            start,
624                            sweep,
625                            cap,
626                        );
627                        if arc.is_degenerate() {
628                            continue;
629                        }
630                        let bounds = arc.bounds();
631                        let exact = exact_bounds(&arc);
632                        let slack =
633                            (arc.outer_radius + arc.half_thickness()) * FAST_TRIG_ERR * 2.0 + 0.05;
634                        assert!(
635                            bounds.x <= exact.x + 1e-3
636                                && bounds.y <= exact.y + 1e-3
637                                && bounds.x + bounds.width >= exact.x + exact.width - 1e-3
638                                && bounds.y + bounds.height >= exact.y + exact.height - 1e-3,
639                            "approximate box lost containment: {bounds:?} vs exact {exact:?} \
640                             (radius {radius}, start {start}, sweep {sweep}, cap {cap:?})"
641                        );
642                        assert!(
643                            (bounds.x - exact.x).abs() <= slack
644                                && (bounds.y - exact.y).abs() <= slack
645                                && (bounds.width - exact.width).abs() <= 2.0 * slack
646                                && (bounds.height - exact.height).abs() <= 2.0 * slack,
647                            "approximate box drifted past its slack: {bounds:?} vs exact \
648                             {exact:?} slack {slack} (radius {radius}, start {start}, sweep \
649                             {sweep}, cap {cap:?})"
650                        );
651                    }
652                }
653            }
654        }
655    }
656
657    /// The pre-approximation bounds algorithm, verbatim, with libm trig.
658    fn exact_bounds(arc: &ArcGeometry) -> Rect {
659        let mut min_x = f32::INFINITY;
660        let mut min_y = f32::INFINITY;
661        let mut max_x = f32::NEG_INFINITY;
662        let mut max_y = f32::NEG_INFINITY;
663        let mut include = |x: f32, y: f32| {
664            min_x = min_x.min(x);
665            min_y = min_y.min(y);
666            max_x = max_x.max(x);
667            max_y = max_y.max(y);
668        };
669        let rb = arc.half_thickness();
670        let ra = arc.mid_radius();
671        let end_angle = arc.start_angle + arc.sweep_angle;
672        for (angle, outward) in [(arc.start_angle, -1.0f32), (end_angle, 1.0f32)] {
673            let (sin, cos) = angle.sin_cos();
674            match arc.cap {
675                StrokeCap::Butt => {
676                    include(
677                        arc.center.x + cos * arc.inner_radius,
678                        arc.center.y + sin * arc.inner_radius,
679                    );
680                    include(
681                        arc.center.x + cos * arc.outer_radius,
682                        arc.center.y + sin * arc.outer_radius,
683                    );
684                }
685                StrokeCap::Square => {
686                    let tx = -sin * rb * outward;
687                    let ty = cos * rb * outward;
688                    include(
689                        arc.center.x + cos * arc.inner_radius + tx,
690                        arc.center.y + sin * arc.inner_radius + ty,
691                    );
692                    include(
693                        arc.center.x + cos * arc.outer_radius + tx,
694                        arc.center.y + sin * arc.outer_radius + ty,
695                    );
696                }
697                StrokeCap::Round => {
698                    let cx = arc.center.x + cos * ra;
699                    let cy = arc.center.y + sin * ra;
700                    include(cx - rb, cy - rb);
701                    include(cx + rb, cy + rb);
702                }
703            }
704        }
705        const AXIS_DIRECTIONS: [(f32, f32); 4] = [(0.0, 1.0), (1.0, 0.0), (0.0, -1.0), (-1.0, 0.0)];
706        for (quadrant, (sin, cos)) in AXIS_DIRECTIONS.into_iter().enumerate() {
707            let angle = quadrant as f32 * FRAC_PI_2;
708            if arc.contains_angle(angle) {
709                include(
710                    arc.center.x + cos * arc.outer_radius,
711                    arc.center.y + sin * arc.outer_radius,
712                );
713            }
714        }
715        Rect {
716            x: min_x,
717            y: min_y,
718            width: (max_x - min_x).max(0.0),
719            height: (max_y - min_y).max(0.0),
720        }
721    }
722
723    #[test]
724    fn arc_geometry_flags_degenerate_bands() {
725        // inner >= outer
726        assert!(ArcGeometry::new(Point::ZERO, 5.0, 5.0, 0.0, 1.0, StrokeCap::Butt).is_degenerate());
727        assert!(ArcGeometry::new(Point::ZERO, 9.0, 5.0, 0.0, 1.0, StrokeCap::Butt).is_degenerate());
728        // zero sweep
729        assert!(ArcGeometry::new(Point::ZERO, 1.0, 5.0, 0.0, 0.0, StrokeCap::Butt).is_degenerate());
730        // zero radius
731        assert!(ArcGeometry::new(Point::ZERO, 0.0, 0.0, 0.0, 1.0, StrokeCap::Butt).is_degenerate());
732    }
733
734    #[test]
735    fn arc_bounds_quarter_sweep_hugs_the_quadrant() {
736        let arc = ArcGeometry::new(
737            Point::new(100.0, 100.0),
738            0.0,
739            10.0,
740            0.0,
741            FRAC_PI_2,
742            StrokeCap::Butt,
743        );
744        let bounds = arc.bounds();
745        assert!(approx(bounds.x, 100.0), "{bounds:?}");
746        assert!(approx(bounds.y, 100.0), "{bounds:?}");
747        assert!(approx(bounds.width, 10.0), "{bounds:?}");
748        assert!(approx(bounds.height, 10.0), "{bounds:?}");
749    }
750
751    #[test]
752    fn arc_bounds_three_quarter_sweep_spans_every_axis_it_crosses() {
753        // 0 -> 270 degrees crosses +X, +Y, -X and ends on -Y.
754        let arc = ArcGeometry::new(
755            Point::new(0.0, 0.0),
756            0.0,
757            10.0,
758            0.0,
759            3.0 * FRAC_PI_2,
760            StrokeCap::Butt,
761        );
762        let bounds = arc.bounds();
763        assert!(approx(bounds.x, -10.0), "{bounds:?}");
764        assert!(approx(bounds.y, -10.0), "{bounds:?}");
765        assert!(approx(bounds.width, 20.0), "{bounds:?}");
766        assert!(approx(bounds.height, 20.0), "{bounds:?}");
767    }
768
769    #[test]
770    fn arc_bounds_include_inner_endpoints_when_no_axis_is_crossed() {
771        // 45 -> 135 degrees only crosses +Y; the minimum y comes from the two
772        // *inner* radial endpoints, not from the outer arc.
773        let arc = ArcGeometry::new(
774            Point::ZERO,
775            8.0,
776            10.0,
777            std::f32::consts::FRAC_PI_4,
778            FRAC_PI_2,
779            StrokeCap::Butt,
780        );
781        let bounds = arc.bounds();
782        let sqrt2_2 = std::f32::consts::FRAC_1_SQRT_2;
783        assert!(approx(bounds.y, 8.0 * sqrt2_2), "{bounds:?}");
784        assert!(approx(bounds.y + bounds.height, 10.0), "{bounds:?}");
785        assert!(approx(bounds.x, -10.0 * sqrt2_2), "{bounds:?}");
786        assert!(approx(bounds.width, 20.0 * sqrt2_2), "{bounds:?}");
787    }
788
789    #[test]
790    fn arc_bounds_negative_sweep_matches_equivalent_positive_sweep() {
791        let forward = ArcGeometry::new(Point::ZERO, 4.0, 6.0, 0.0, FRAC_PI_2, StrokeCap::Butt);
792        let backward = ArcGeometry::new(
793            Point::ZERO,
794            4.0,
795            6.0,
796            FRAC_PI_2,
797            -FRAC_PI_2,
798            StrokeCap::Butt,
799        );
800        assert_eq!(forward.bounds(), backward.bounds());
801    }
802
803    #[test]
804    fn arc_bounds_full_turn_is_the_outer_circle() {
805        let arc = ArcGeometry::new(Point::new(5.0, 7.0), 3.0, 9.0, 1.1, TAU, StrokeCap::Butt);
806        let bounds = arc.bounds();
807        assert!(approx(bounds.x, -4.0), "{bounds:?}");
808        assert!(approx(bounds.y, -2.0), "{bounds:?}");
809        assert!(approx(bounds.width, 18.0), "{bounds:?}");
810        assert!(approx(bounds.height, 18.0), "{bounds:?}");
811    }
812
813    #[test]
814    fn arc_bounds_round_caps_bulge_past_the_radial_ends() {
815        let butt = ArcGeometry::new(Point::ZERO, 8.0, 12.0, 0.0, FRAC_PI_2, StrokeCap::Butt);
816        let round = ArcGeometry::new(Point::ZERO, 8.0, 12.0, 0.0, FRAC_PI_2, StrokeCap::Round);
817        let butt_bounds = butt.bounds();
818        let round_bounds = round.bounds();
819        // The start cap at angle 0 bulges to -rb in y; butt stops at y = 0.
820        assert!(approx(butt_bounds.y, 0.0), "{butt_bounds:?}");
821        assert!(approx(round_bounds.y, -2.0), "{round_bounds:?}");
822        assert!(round_bounds.width >= butt_bounds.width);
823        assert!(round_bounds.height >= butt_bounds.height);
824    }
825
826    #[test]
827    fn arc_bounds_square_caps_project_along_the_tangent() {
828        let square = ArcGeometry::new(Point::ZERO, 8.0, 12.0, 0.0, FRAC_PI_2, StrokeCap::Square);
829        let bounds = square.bounds();
830        // Start cap at angle 0: tangent is +Y, projected backwards by rb = 2.
831        assert!(approx(bounds.y, -2.0), "{bounds:?}");
832        assert!(approx(bounds.x + bounds.width, 12.0), "{bounds:?}");
833    }
834
835    #[test]
836    fn arc_band_resolves_stroked_and_filled_forms() {
837        let (inner, outer, cap) =
838            arc_band(10.0, 0.0, Some(Stroke::new(4.0).with_cap(StrokeCap::Round)));
839        assert_eq!((inner, outer), (8.0, 12.0));
840        assert_eq!(cap, StrokeCap::Round);
841
842        let (inner, outer, cap) = arc_band(10.0, 6.0, None);
843        assert_eq!((inner, outer), (6.0, 10.0));
844        assert_eq!(cap, StrokeCap::Butt);
845
846        // inner >= outer clamps rather than producing a negative band.
847        let (inner, outer, _) = arc_band(10.0, 40.0, None);
848        assert_eq!((inner, outer), (10.0, 10.0));
849
850        // A stroke wider than the radius clamps the inner radius at 0.
851        let (inner, outer, _) = arc_band(1.0, 0.0, Some(Stroke::new(10.0)));
852        assert_eq!((inner, outer), (0.0, 6.0));
853    }
854
855    #[test]
856    fn full_ring_bounds_shortcut_matches_the_endpoint_walk() {
857        // The trig-free full-sweep path must return exactly what the endpoint
858        // walk would: `center ± outer` on both axes. The walk's answer for a
859        // full ring is forced by the four axis crossings plus a round cap
860        // whose farthest point sits at `mid + half_thickness == outer`.
861        let ring = ArcGeometry::new(Point::new(10.0, -4.0), 6.0, 9.0, 1.3, TAU, StrokeCap::Butt);
862        assert_eq!(
863            ring.bounds(),
864            Rect {
865                x: 1.0,
866                y: -13.0,
867                width: 18.0,
868                height: 18.0
869            }
870        );
871
872        // A hand-built square cap can project past `outer` along the tangent
873        // (its corner sits at distance `sqrt(outer² + rb²)` from the center),
874        // so a full-sweep square ring must keep the endpoint walk. The
875        // endpoint angle is chosen so the corner lands on the +x axis, where
876        // the excess is largest.
877        let square = ArcGeometry {
878            cap: StrokeCap::Square,
879            start_angle: TAU - (1.5f32 / 9.0).atan(),
880            ..ring
881        };
882        let bounds = square.bounds();
883        assert!(bounds.x + bounds.width > square.center.x + square.outer_radius);
884    }
885
886    #[test]
887    fn inflate_rect_ignores_non_positive_amounts() {
888        let rect = Rect {
889            x: 1.0,
890            y: 2.0,
891            width: 3.0,
892            height: 4.0,
893        };
894        assert_eq!(inflate_rect(rect, 0.0), rect);
895        assert_eq!(inflate_rect(rect, -1.0), rect);
896        assert_eq!(inflate_rect(rect, f32::NAN), rect);
897        assert_eq!(
898            inflate_rect(rect, 1.0),
899            Rect {
900                x: 0.0,
901                y: 1.0,
902                width: 5.0,
903                height: 6.0
904            }
905        );
906    }
907}