Skip to main content

gpui_material_foundation/shape/
polygon.rs

1use std::sync::{Arc, LazyLock};
2
3use gpui::{Bounds, Pixels, Point};
4use gpui_material_theme::{CornerShape, Direction, MaterialShape, PolygonRole, PolygonSpec};
5use polymorpher::{CornerRounding, Cubic, RoundedPolygon, geometry::Point as PolygonPoint, shapes};
6
7use super::{Shape, ShapeFit};
8
9/// A reusable normalized polygon contour backed by `polymorpher`.
10///
11/// Third-party polygon types stay inside Foundation so components and applications
12/// share one shape pipeline across Expressive presets, rounded rectangles, custom
13/// polygons, and morph transitions.
14#[derive(Clone, Debug)]
15pub struct ShapePolygon {
16    kind: PolygonKind,
17}
18
19#[derive(Clone, Debug)]
20enum PolygonKind {
21    Rounded(Arc<RoundedPolygon>),
22    Cubics(Arc<[Cubic]>),
23}
24
25impl PartialEq for ShapePolygon {
26    fn eq(&self, other: &Self) -> bool {
27        match (&self.kind, &other.kind) {
28            (PolygonKind::Rounded(a), PolygonKind::Rounded(b)) => Arc::ptr_eq(a, b) || a == b,
29            (PolygonKind::Cubics(a), PolygonKind::Cubics(b)) => Arc::ptr_eq(a, b) || a == b,
30            _ => false,
31        }
32    }
33}
34
35static MATERIAL_POLYGONS: LazyLock<[Arc<RoundedPolygon>; MaterialShape::ALL.len()]> =
36    LazyLock::new(|| MaterialShape::ALL.map(|shape| Arc::new(build_material_polygon(shape))));
37
38impl ShapePolygon {
39    /// Constructs one of the 35 Material 3 Expressive shapes matching Compose `MaterialShapes`.
40    pub fn material(shape: MaterialShape) -> Self {
41        let index = MaterialShape::ALL
42            .iter()
43            .position(|candidate| *candidate == shape)
44            .unwrap_or(0);
45        Self {
46            kind: PolygonKind::Rounded(Arc::clone(&MATERIAL_POLYGONS[index])),
47        }
48    }
49
50    /// Constructs a regular rounded circle polygon with at least three vertices.
51    pub fn circle(vertices: usize) -> Option<Self> {
52        if vertices < 3 {
53            return None;
54        }
55        Some(Self::from_rounded(
56            RoundedPolygon::circle()
57                .with_vertices(vertices)
58                .build()
59                .normalized(),
60        ))
61    }
62
63    /// Constructs a regular polygon with optional corner rounding, smoothing, and rotation.
64    pub fn regular(
65        vertices: usize,
66        rounding: f32,
67        smoothing: f32,
68        rotation_degrees: f32,
69    ) -> Option<Self> {
70        if vertices < 3 || !valid_rounding(rounding, smoothing) || !rotation_degrees.is_finite() {
71            return None;
72        }
73        let polygon = RoundedPolygon::from_vertices_count(
74            vertices,
75            1.,
76            Some(CornerRounding::smoothed(rounding, smoothing)),
77            &[],
78        );
79        let polygon = if rotation_degrees != 0. {
80            rotate_polygon(polygon, rotation_degrees)
81        } else {
82            polygon
83        };
84        Some(Self::from_rounded(polygon.normalized()))
85    }
86
87    /// Constructs a star polygon with outer radius `1.0`, `inner_radius` in `(0, 1)`,
88    /// outer corner rounding, and optional inner corner rounding `(radius, smoothing)`.
89    pub fn star(
90        vertices: usize,
91        inner_radius: f32,
92        rounding: f32,
93        smoothing: f32,
94        inner_rounding: Option<(f32, f32)>,
95    ) -> Option<Self> {
96        if vertices < 3
97            || !inner_radius.is_finite()
98            || !(0. < inner_radius && inner_radius < 1.)
99            || !valid_rounding(rounding, smoothing)
100        {
101            return None;
102        }
103        let mut builder = RoundedPolygon::star(vertices)
104            .with_inner_radius(inner_radius)
105            .with_rounding(CornerRounding::smoothed(rounding, smoothing));
106        if let Some((inner_r, inner_s)) = inner_rounding {
107            if !valid_rounding(inner_r, inner_s) {
108                return None;
109            }
110            builder = builder.with_inner_rounding(CornerRounding::smoothed(inner_r, inner_s));
111        }
112        Some(Self::from_rounded(builder.build().normalized()))
113    }
114
115    /// Constructs a rounded rectangle mapped to the full unit square `[0, 1] x [0, 1]`
116    /// for use with [`ShapeFit::Stretch`] against matching `(width, height)` bounds.
117    ///
118    /// When rendered into matching bounds with [`ShapeFit::Stretch`], this reproduces
119    /// [`Shape::rounded`] and allows morphing between [`CornerShape`] and [`MaterialShape`].
120    pub fn rounded_rect(
121        width: f32,
122        height: f32,
123        corners: CornerShape,
124        direction: Direction,
125    ) -> Option<Self> {
126        let polygon = rounded_rect_polygon(width, height, corners, direction)?;
127        Some(Self::from_rounded(polygon))
128    }
129
130    /// Creates a normalized rounded polygon from perimeter vertices in either winding order.
131    /// The radius uses the same units as the vertices. Non-finite, degenerate, or
132    /// self-intersecting geometry returns `None`.
133    pub fn from_vertices(vertices: &[Point<f32>], radius: f32) -> Option<Self> {
134        if vertices.len() < 3 || !radius.is_finite() || radius < 0. {
135            return None;
136        }
137        let (mut vertices, side) = normalized_vertices(vertices)?;
138        if !simple_polygon(&vertices) {
139            return None;
140        }
141        let area: f32 = polygon_edges(&vertices)
142            .map(|(a, b)| a.x * b.y - a.y * b.x)
143            .sum();
144        if !area.is_finite() || area.abs() < 1e-5 {
145            return None;
146        }
147        if area < 0. {
148            vertices.reverse();
149        }
150        let first = vertices
151            .iter()
152            .enumerate()
153            .max_by(|(_, a), (_, b)| a.x.total_cmp(&b.x).then_with(|| b.y.total_cmp(&a.y)))?
154            .0;
155        vertices.rotate_left(first);
156        let rounding = CornerRounding::new((f64::from(radius) / side).min(1.) as f32);
157        let polygon = RoundedPolygon::from_vertices(&vertices, rounding, &[], PolygonPoint::zero());
158        (polygon.cubics.len() > 1).then(|| Self::from_rounded(polygon.normalized()))
159    }
160
161    /// Returns a copy rotated clockwise by `degrees` around its center and re-normalized.
162    pub fn rotated(&self, degrees: f32) -> Self {
163        if !degrees.is_finite() || degrees == 0. {
164            return self.clone();
165        }
166        let (sin, cos) = degrees.to_radians().sin_cos();
167        match &self.kind {
168            PolygonKind::Rounded(polygon) => {
169                let center = polygon.center;
170                Self::from_rounded(
171                    (**polygon)
172                        .clone()
173                        .transformed(|p: PolygonPoint| rotate_point_around(p, center, sin, cos))
174                        .normalized(),
175                )
176            }
177            PolygonKind::Cubics(cubics) => {
178                let center = cubic_center(cubics);
179                let rotate = |p: PolygonPoint| rotate_point_around(p, center, sin, cos);
180                let rotated: Vec<_> = cubics
181                    .iter()
182                    .map(|cubic| {
183                        Cubic::new(
184                            rotate(cubic.anchor0()),
185                            rotate(cubic.control0()),
186                            rotate(cubic.control1()),
187                            rotate(cubic.anchor1()),
188                        )
189                    })
190                    .collect();
191                Self::from_cubics(normalize_cubics(rotated))
192            }
193        }
194    }
195
196    /// Scale factor that keeps this polygon inside its unit bounds under arbitrary rotation.
197    ///
198    /// Matches Compose's `LoadingIndicator` rotation-envelope calculation, comparing the
199    /// polygon's bounds against the furthest sampled anchor or cubic midpoint from center.
200    pub fn rotation_scale(&self) -> f32 {
201        let cubics = self.cubics();
202        if cubics.is_empty() {
203            return 1.;
204        }
205        let (bounds_max, center) = match &self.kind {
206            PolygonKind::Rounded(polygon) => {
207                let bounds = polygon.aabb(true).size();
208                (bounds.width.max(bounds.height), polygon.center)
209            }
210            PolygonKind::Cubics(cubics) => {
211                let (min, max) = cubic_aabb(cubics);
212                let size = max - min;
213                (size.x.max(size.y), min + size * 0.5)
214            }
215        };
216        let radius = cubics
217            .iter()
218            .flat_map(|cubic| [cubic.anchor0(), cubic.point_on_curve(0.5)])
219            .map(|point| (point - center).length())
220            .fold(0_f32, f32::max);
221        if radius <= f32::EPSILON || bounds_max <= f32::EPSILON {
222            1.
223        } else {
224            (bounds_max / (2. * radius)).clamp(0., 1.)
225        }
226    }
227
228    /// Projects this polygon into `bounds` using [`ShapeFit::Contain`].
229    pub fn to_shape(&self, bounds: Bounds<Pixels>) -> Option<Shape> {
230        self.to_shape_with(bounds, ShapeFit::Contain, 0.)
231    }
232
233    /// Projects this polygon into `bounds` with explicit fit mode and clockwise rotation in radians.
234    pub fn to_shape_with(
235        &self,
236        bounds: Bounds<Pixels>,
237        fit: ShapeFit,
238        rotation_radians: f32,
239    ) -> Option<Shape> {
240        Shape::from_cubics(self.cubics().to_vec(), bounds, fit, rotation_radians)
241    }
242
243    /// Returns the number of cubic Bézier segments in this normalized contour.
244    pub fn cubic_count(&self) -> usize {
245        self.cubics().len()
246    }
247
248    fn from_rounded(polygon: RoundedPolygon) -> Self {
249        Self {
250            kind: PolygonKind::Rounded(Arc::new(polygon)),
251        }
252    }
253
254    pub(super) fn from_cubics(cubics: Vec<Cubic>) -> Self {
255        Self {
256            kind: PolygonKind::Cubics(Arc::from(cubics)),
257        }
258    }
259
260    pub(super) fn as_rounded(&self) -> Option<&RoundedPolygon> {
261        match &self.kind {
262            PolygonKind::Rounded(polygon) => Some(polygon.as_ref()),
263            PolygonKind::Cubics(_) => None,
264        }
265    }
266
267    pub(super) fn cubics(&self) -> &[Cubic] {
268        match &self.kind {
269            PolygonKind::Rounded(polygon) => &polygon.cubics,
270            PolygonKind::Cubics(cubics) => cubics.as_ref(),
271        }
272    }
273
274    pub(super) fn control_point_radius(&self) -> f32 {
275        self.cubics()
276            .iter()
277            .flat_map(|cubic| {
278                [
279                    cubic.anchor0(),
280                    cubic.control0(),
281                    cubic.control1(),
282                    cubic.anchor1(),
283                ]
284            })
285            .map(|point| (point - PolygonPoint::splat(0.5)).length())
286            .fold(0_f32, f32::max)
287    }
288}
289
290impl From<MaterialShape> for ShapePolygon {
291    fn from(shape: MaterialShape) -> Self {
292        Self::material(shape)
293    }
294}
295
296impl From<PolygonRole> for ShapePolygon {
297    fn from(role: PolygonRole) -> Self {
298        Self::from_rounded(role_polygon(role))
299    }
300}
301
302fn valid_rounding(radius: f32, smoothing: f32) -> bool {
303    radius.is_finite() && radius >= 0. && smoothing.is_finite() && (0.0..=1.0).contains(&smoothing)
304}
305
306fn rotate_point_around(
307    point: PolygonPoint,
308    center: PolygonPoint,
309    sin: f32,
310    cos: f32,
311) -> PolygonPoint {
312    let dx = point.x - center.x;
313    let dy = point.y - center.y;
314    PolygonPoint::new(
315        center.x + dx * cos - dy * sin,
316        center.y + dx * sin + dy * cos,
317    )
318}
319
320fn rotate_polygon(polygon: RoundedPolygon, degrees: f32) -> RoundedPolygon {
321    let (sin, cos) = degrees.to_radians().sin_cos();
322    polygon.transformed(|p: PolygonPoint| {
323        PolygonPoint::new(p.x * cos - p.y * sin, p.x * sin + p.y * cos)
324    })
325}
326
327fn rounded_rect_polygon(
328    width: f32,
329    height: f32,
330    corners: CornerShape,
331    direction: Direction,
332) -> Option<RoundedPolygon> {
333    if !width.is_finite() || !height.is_finite() || width <= 0. || height <= 0. {
334        return None;
335    }
336    let [tl, tr, br, bl] = corners.radii(width, height, direction);
337    let side = width.max(height);
338    let polygon = RoundedPolygon::rectangle()
339        .with_width(width / side)
340        .with_height(height / side)
341        .with_rounding_per_vertex([br, bl, tl, tr].map(|radius| CornerRounding::new(radius / side)))
342        .build();
343    Some(polygon.transformed(|p: PolygonPoint| {
344        PolygonPoint::new(p.x * side / width + 0.5, p.y * side / height + 0.5)
345    }))
346}
347
348pub(super) fn rounded_rect_cubics(
349    width: f32,
350    height: f32,
351    corners: CornerShape,
352    direction: Direction,
353) -> Option<Vec<Cubic>> {
354    if !width.is_finite() || !height.is_finite() || width <= 0. || height <= 0. {
355        return None;
356    }
357    let [tl, tr, br, bl] = corners.radii(width, height, direction);
358    let side = width.max(height);
359    let mut cubics = RoundedPolygon::rectangle()
360        .with_width(width / side)
361        .with_height(height / side)
362        .with_rounding_per_vertex([br, bl, tl, tr].map(|radius| CornerRounding::new(radius / side)))
363        .build()
364        .cubics;
365    for cubic in &mut cubics {
366        *cubic = cubic.transformed(&|p: PolygonPoint| {
367            PolygonPoint::new(p.x * side / width + 0.5, p.y * side / height + 0.5)
368        });
369    }
370    Some(cubics)
371}
372
373fn build_material_polygon(shape: MaterialShape) -> RoundedPolygon {
374    match shape {
375        MaterialShape::Circle => shapes::circle(None),
376        MaterialShape::Square => shapes::square(),
377        MaterialShape::Slanted => shapes::slanted(),
378        MaterialShape::Arch => shapes::arch(),
379        MaterialShape::Fan => shapes::fan(),
380        MaterialShape::Arrow => shapes::arrow(),
381        MaterialShape::SemiCircle => shapes::semi_circle(),
382        MaterialShape::Oval => shapes::oval(),
383        MaterialShape::Pill => shapes::pill(),
384        MaterialShape::Triangle => shapes::triangle(),
385        MaterialShape::Diamond => shapes::diamond(),
386        MaterialShape::ClamShell => shapes::clam_shell(),
387        MaterialShape::Pentagon => shapes::pentagon(),
388        MaterialShape::Gem => shapes::gem(),
389        MaterialShape::Sunny => shapes::sunny(),
390        MaterialShape::VerySunny => shapes::very_sunny(),
391        MaterialShape::Cookie4Sided => shapes::cookie4(),
392        MaterialShape::Cookie6Sided => shapes::cookie6(),
393        MaterialShape::Cookie7Sided => shapes::cookie7(),
394        MaterialShape::Cookie9Sided => shapes::cookie9(),
395        MaterialShape::Cookie12Sided => shapes::cookie12(),
396        MaterialShape::Ghostish => shapes::ghostish(),
397        MaterialShape::Clover4Leaf => shapes::clover4(),
398        MaterialShape::Clover8Leaf => shapes::clover8(),
399        MaterialShape::Burst => shapes::burst(),
400        MaterialShape::SoftBurst => shapes::soft_burst(),
401        MaterialShape::Boom => shapes::boom(),
402        MaterialShape::SoftBoom => shapes::soft_boom(),
403        MaterialShape::Flower => shapes::flower(),
404        MaterialShape::Puffy => shapes::puffy(),
405        MaterialShape::PuffyDiamond => shapes::puffy_diamond(),
406        MaterialShape::PixelCircle => shapes::pixel_circle(),
407        MaterialShape::PixelTriangle => shapes::pixel_triangle(),
408        MaterialShape::Bun => shapes::bun(),
409        MaterialShape::Heart => shapes::heart(),
410    }
411}
412
413pub(super) fn role_polygon(role: PolygonRole) -> RoundedPolygon {
414    match role.spec() {
415        PolygonSpec::Circle { vertices, radius } => RoundedPolygon::circle()
416            .with_vertices(usize::from(vertices))
417            .with_radius(radius)
418            .build(),
419        PolygonSpec::Rectangle {
420            width,
421            height,
422            rounding_radius,
423            smoothing,
424        } => RoundedPolygon::rectangle()
425            .with_width(width)
426            .with_height(height)
427            .with_rounding(CornerRounding::smoothed(rounding_radius, smoothing))
428            .build(),
429        PolygonSpec::Regular {
430            vertices,
431            radius,
432            rounding_radius,
433            smoothing,
434            rotation_degrees,
435        } => rotate_polygon(
436            RoundedPolygon::from_vertices_count(
437                usize::from(vertices),
438                radius,
439                Some(CornerRounding::smoothed(rounding_radius, smoothing)),
440                &[],
441            ),
442            rotation_degrees,
443        ),
444    }
445    .normalized()
446}
447
448fn normalized_vertices(vertices: &[Point<f32>]) -> Option<(Vec<PolygonPoint>, f64)> {
449    let (mut left, mut top, mut right, mut bottom) = (
450        f64::INFINITY,
451        f64::INFINITY,
452        f64::NEG_INFINITY,
453        f64::NEG_INFINITY,
454    );
455    for point in vertices {
456        if !point.x.is_finite() || !point.y.is_finite() {
457            return None;
458        }
459        let x = f64::from(point.x);
460        let y = f64::from(point.y);
461        left = left.min(x);
462        top = top.min(y);
463        right = right.max(x);
464        bottom = bottom.max(y);
465    }
466    let side = (right - left).max(bottom - top);
467    if side == 0. {
468        return None;
469    }
470    let centered = vertices.iter().map(|point| {
471        PolygonPoint::new(
472            ((f64::from(point.x) - (left + right) * 0.5) / side) as f32,
473            ((f64::from(point.y) - (top + bottom) * 0.5) / side) as f32,
474        )
475    });
476    Some((centered.collect(), side))
477}
478
479fn polygon_edges(
480    vertices: &[PolygonPoint],
481) -> impl Iterator<Item = (PolygonPoint, PolygonPoint)> + Clone + '_ {
482    vertices
483        .iter()
484        .copied()
485        .zip(vertices.iter().copied().cycle().skip(1))
486}
487
488fn simple_polygon(vertices: &[PolygonPoint]) -> bool {
489    let edges = polygon_edges(vertices);
490    for (index, (a, b)) in edges.clone().enumerate() {
491        if (b - a).length() < 1e-5 {
492            return false;
493        }
494        for (other, (c, d)) in edges.clone().enumerate().skip(index + 2) {
495            if index == 0 && other == vertices.len() - 1 {
496                continue;
497            }
498            let orient = |a: PolygonPoint, b: PolygonPoint, c: PolygonPoint| {
499                let u = b - a;
500                let v = c - a;
501                u.x * v.y - u.y * v.x
502            };
503            let overlaps =
504                |a: f32, b: f32, c: f32, d: f32| a.min(b) <= c.max(d) && c.min(d) <= a.max(b);
505            if overlaps(a.x, b.x, c.x, d.x)
506                && overlaps(a.y, b.y, c.y, d.y)
507                && orient(a, b, c) * orient(a, b, d) <= 0.
508                && orient(c, d, a) * orient(c, d, b) <= 0.
509            {
510                return false;
511            }
512        }
513    }
514    true
515}
516
517fn cubic_aabb(cubics: &[Cubic]) -> (PolygonPoint, PolygonPoint) {
518    let mut minimum = PolygonPoint::new(f32::INFINITY, f32::INFINITY);
519    let mut maximum = PolygonPoint::new(f32::NEG_INFINITY, f32::NEG_INFINITY);
520    for cubic in cubics {
521        let bounds = cubic.aabb(true);
522        minimum = minimum.min(bounds.min);
523        maximum = maximum.max(bounds.max);
524    }
525    (minimum, maximum)
526}
527
528pub(super) fn cubic_center(cubics: &[Cubic]) -> PolygonPoint {
529    let (minimum, maximum) = cubic_aabb(cubics);
530    minimum + (maximum - minimum) * 0.5
531}
532
533fn normalize_cubics(cubics: Vec<Cubic>) -> Vec<Cubic> {
534    if cubics.is_empty() {
535        return cubics;
536    }
537    let (min, max) = cubic_aabb(&cubics);
538    let size = max - min;
539    let max_side = size.x.max(size.y);
540    if !max_side.is_finite() || max_side <= f32::EPSILON {
541        return cubics;
542    }
543    let offset = (PolygonPoint::splat(max_side) - size) * 0.5 - min.to_vector();
544    let map = |p: PolygonPoint| (p + offset.to_vector()) / max_side;
545    cubics
546        .into_iter()
547        .map(|cubic| {
548            Cubic::new(
549                map(cubic.anchor0()),
550                map(cubic.control0()),
551                map(cubic.control1()),
552                map(cubic.anchor1()),
553            )
554        })
555        .collect()
556}