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
306pub(super) fn 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
327fn material_polygon(shape: MaterialShape) -> RoundedPolygon {
328    match shape {
329        MaterialShape::Circle => shapes::circle(None),
330        MaterialShape::Square => shapes::square(),
331        MaterialShape::Slanted => shapes::slanted(),
332        MaterialShape::Arch => shapes::arch(),
333        MaterialShape::Fan => shapes::fan(),
334        MaterialShape::Arrow => shapes::arrow(),
335        MaterialShape::SemiCircle => shapes::semi_circle(),
336        MaterialShape::Oval => shapes::oval(),
337        MaterialShape::Pill => shapes::pill(),
338        MaterialShape::Triangle => shapes::triangle(),
339        MaterialShape::Diamond => shapes::diamond(),
340        MaterialShape::ClamShell => shapes::clam_shell(),
341        MaterialShape::Pentagon => shapes::pentagon(),
342        MaterialShape::Gem => shapes::gem(),
343        MaterialShape::Sunny => shapes::sunny(),
344        MaterialShape::VerySunny => shapes::very_sunny(),
345        MaterialShape::Cookie4Sided => shapes::cookie4(),
346        MaterialShape::Cookie6Sided => shapes::cookie6(),
347        MaterialShape::Cookie7Sided => shapes::cookie7(),
348        MaterialShape::Cookie9Sided => shapes::cookie9(),
349        MaterialShape::Cookie12Sided => shapes::cookie12(),
350        MaterialShape::Ghostish => shapes::ghostish(),
351        MaterialShape::Clover4Leaf => shapes::clover4(),
352        MaterialShape::Clover8Leaf => shapes::clover8(),
353        MaterialShape::Burst => shapes::burst(),
354        MaterialShape::SoftBurst => shapes::soft_burst(),
355        MaterialShape::Boom => shapes::boom(),
356        MaterialShape::SoftBoom => shapes::soft_boom(),
357        MaterialShape::Flower => shapes::flower(),
358        MaterialShape::Puffy => shapes::puffy(),
359        MaterialShape::PuffyDiamond => shapes::puffy_diamond(),
360        MaterialShape::PixelCircle => shapes::pixel_circle(),
361        MaterialShape::PixelTriangle => shapes::pixel_triangle(),
362        MaterialShape::Bun => shapes::bun(),
363        MaterialShape::Heart => shapes::heart(),
364    }
365}
366
367pub(super) fn role_polygon(role: PolygonRole) -> RoundedPolygon {
368    match role.spec() {
369        PolygonSpec::Circle { vertices, radius } => RoundedPolygon::circle()
370            .with_vertices(usize::from(vertices))
371            .with_radius(radius)
372            .build(),
373        PolygonSpec::Rectangle {
374            width,
375            height,
376            rounding_radius,
377            smoothing,
378        } => RoundedPolygon::rectangle()
379            .with_width(width)
380            .with_height(height)
381            .with_rounding(CornerRounding::smoothed(rounding_radius, smoothing))
382            .build(),
383        PolygonSpec::Regular {
384            vertices,
385            radius,
386            rounding_radius,
387            smoothing,
388            rotation_degrees,
389        } => rotate_polygon(
390            RoundedPolygon::from_vertices_count(
391                usize::from(vertices),
392                radius,
393                Some(CornerRounding::smoothed(rounding_radius, smoothing)),
394                &[],
395            ),
396            rotation_degrees,
397        ),
398    }
399    .normalized()
400}
401
402fn normalized_vertices(vertices: &[Point<f32>]) -> Option<(Vec<PolygonPoint>, f64)> {
403    let (mut left, mut top, mut right, mut bottom) = (
404        f64::INFINITY,
405        f64::INFINITY,
406        f64::NEG_INFINITY,
407        f64::NEG_INFINITY,
408    );
409    for point in vertices {
410        if !point.x.is_finite() || !point.y.is_finite() {
411            return None;
412        }
413        let x = f64::from(point.x);
414        let y = f64::from(point.y);
415        left = left.min(x);
416        top = top.min(y);
417        right = right.max(x);
418        bottom = bottom.max(y);
419    }
420    let side = (right - left).max(bottom - top);
421    if side == 0. {
422        return None;
423    }
424    let centered = vertices.iter().map(|point| {
425        PolygonPoint::new(
426            ((f64::from(point.x) - (left + right) * 0.5) / side) as f32,
427            ((f64::from(point.y) - (top + bottom) * 0.5) / side) as f32,
428        )
429    });
430    Some((centered.collect(), side))
431}
432
433fn polygon_edges(
434    vertices: &[PolygonPoint],
435) -> impl Iterator<Item = (PolygonPoint, PolygonPoint)> + Clone + '_ {
436    vertices
437        .iter()
438        .copied()
439        .zip(vertices.iter().copied().cycle().skip(1))
440}
441
442fn simple_polygon(vertices: &[PolygonPoint]) -> bool {
443    let edges = polygon_edges(vertices);
444    for (index, (a, b)) in edges.clone().enumerate() {
445        if (b - a).length() < 1e-5 {
446            return false;
447        }
448        for (other, (c, d)) in edges.clone().enumerate().skip(index + 2) {
449            if index == 0 && other == vertices.len() - 1 {
450                continue;
451            }
452            let orient = |a: PolygonPoint, b: PolygonPoint, c: PolygonPoint| {
453                let u = b - a;
454                let v = c - a;
455                u.x * v.y - u.y * v.x
456            };
457            let overlaps =
458                |a: f32, b: f32, c: f32, d: f32| a.min(b) <= c.max(d) && c.min(d) <= a.max(b);
459            if overlaps(a.x, b.x, c.x, d.x)
460                && overlaps(a.y, b.y, c.y, d.y)
461                && orient(a, b, c) * orient(a, b, d) <= 0.
462                && orient(c, d, a) * orient(c, d, b) <= 0.
463            {
464                return false;
465            }
466        }
467    }
468    true
469}
470
471fn cubic_aabb(cubics: &[Cubic]) -> (PolygonPoint, PolygonPoint) {
472    let mut minimum = PolygonPoint::new(f32::INFINITY, f32::INFINITY);
473    let mut maximum = PolygonPoint::new(f32::NEG_INFINITY, f32::NEG_INFINITY);
474    for cubic in cubics {
475        let bounds = cubic.aabb(true);
476        minimum = minimum.min(bounds.min);
477        maximum = maximum.max(bounds.max);
478    }
479    (minimum, maximum)
480}
481
482pub(super) fn cubic_center(cubics: &[Cubic]) -> PolygonPoint {
483    let (minimum, maximum) = cubic_aabb(cubics);
484    minimum + (maximum - minimum) * 0.5
485}
486
487fn normalize_cubics(cubics: Vec<Cubic>) -> Vec<Cubic> {
488    if cubics.is_empty() {
489        return cubics;
490    }
491    let (min, max) = cubic_aabb(&cubics);
492    let size = max - min;
493    let max_side = size.x.max(size.y);
494    if !max_side.is_finite() || max_side <= f32::EPSILON {
495        return cubics;
496    }
497    let offset = (PolygonPoint::splat(max_side) - size) * 0.5 - min.to_vector();
498    let map = |p: PolygonPoint| (p + offset.to_vector()) / max_side;
499    cubics
500        .into_iter()
501        .map(|cubic| {
502            Cubic::new(
503                map(cubic.anchor0()),
504                map(cubic.control0()),
505                map(cubic.control1()),
506                map(cubic.anchor1()),
507            )
508        })
509        .collect()
510}