Skip to main content

gpui_material_foundation/shape/
polygon.rs

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