Skip to main content

gpui_material_foundation/
shape.rs

1mod clip;
2mod morph;
3mod polygon;
4#[cfg(test)]
5mod tests;
6
7use gpui::{
8    Bounds, FillOptions, FillRule, Hsla, Path, PathBuilder, PathStyle, Pixels, Point, Window,
9    point, px, size,
10};
11use gpui_material_theme::{CornerShape, Direction, MaterialShape};
12use polymorpher::{Cubic, geometry::Point as PolygonPoint};
13
14use clip::{
15    FillMesh, bounds_overlap, clip_convex_polygon_fill, clip_mesh_fill, clip_polygon_to_rect,
16    clip_rect_fill, clipped_ripple, contains_fill, cross, flatten_cubic, polygon_area,
17    rect_is_valid, segment_distance_sq, triangle_disjoint_from_rect,
18};
19use polygon::rounded_rect_cubics;
20
21pub use morph::{PolygonMorph, ShapeMorph, ShapeMorphSequence};
22pub use polygon::ShapePolygon;
23
24/// How a normalized polygon contour maps into layout bounds.
25#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
26pub enum ShapeFit {
27    /// Fits the centered unit square inside the shorter side while preserving aspect ratio.
28    #[default]
29    Contain,
30    /// Scales independently to fill the width and height of the bounds.
31    Stretch,
32}
33
34/// A prepared shape with a curve path for painting and a lazily built mesh for clipping and hit testing.
35#[derive(Clone)]
36pub struct Shape {
37    outline: Outline,
38    fill: Path,
39    mesh: std::sync::OnceLock<FillMesh>,
40    stroke_cache: std::sync::OnceLock<(u32, Path)>,
41}
42
43#[derive(Clone)]
44struct Outline {
45    cubics: Vec<Cubic>,
46    bounds: Bounds<Pixels>,
47    fit: ShapeFit,
48    rotation: f32,
49    pivot: PolygonPoint,
50    scale: f32,
51}
52
53impl Outline {
54    fn projection_params(&self) -> Option<(Point<Pixels>, Pixels, Pixels, f32, f32)> {
55        let size = self.bounds.size;
56        let side = size.width.min(size.height);
57        if !(side > px(0.) && side < px(f32::INFINITY))
58            || !self.rotation.is_finite()
59            || !self.scale.is_finite()
60            || self.scale <= 0.
61            || self.cubics.is_empty()
62        {
63            return None;
64        }
65        let center = self.bounds.center();
66        let (width, height) = match self.fit {
67            ShapeFit::Contain => (side, side),
68            ShapeFit::Stretch => (size.width, size.height),
69        };
70        let (sin, cos) = self.rotation.sin_cos();
71        Some((center, width, height, sin, cos))
72    }
73
74    fn project_point(
75        &self,
76        p: PolygonPoint,
77        center: Point<Pixels>,
78        width: Pixels,
79        height: Pixels,
80        sin: f32,
81        cos: f32,
82    ) -> Point<Pixels> {
83        let dx = p.x - self.pivot.x;
84        let dy = p.y - self.pivot.y;
85        let (rx, ry) = if self.rotation == 0. {
86            (dx, dy)
87        } else {
88            (cos * dx - sin * dy, sin * dx + cos * dy)
89        };
90        center + point(width * (self.scale * rx), height * (self.scale * ry))
91    }
92
93    fn add_to_builder(&self, builder: &mut PathBuilder) -> bool {
94        let Some((center, width, height, sin, cos)) = self.projection_params() else {
95            return false;
96        };
97        let project = |p| self.project_point(p, center, width, height, sin, cos);
98        builder.move_to(project(self.cubics[0].anchor0()));
99        for cubic in &self.cubics {
100            builder.cubic_bezier_to(
101                project(cubic.anchor1()),
102                project(cubic.control0()),
103                project(cubic.control1()),
104            );
105        }
106        builder.close();
107        true
108    }
109
110    fn flatten_mesh(&self) -> FillMesh {
111        let Some((center, width, height, sin, cos)) = self.projection_params() else {
112            return FillMesh::empty(self.bounds.origin);
113        };
114        let project = |p| self.project_point(p, center, width, height, sin, cos);
115        let mut contour = Vec::with_capacity(self.cubics.len() * 4);
116        let start = project(self.cubics[0].anchor0());
117        contour.push(start);
118        for cubic in &self.cubics {
119            flatten_cubic(
120                project(cubic.anchor0()),
121                project(cubic.control0()),
122                project(cubic.control1()),
123                project(cubic.anchor1()),
124                &mut contour,
125            );
126        }
127        FillMesh::from_contour(&contour)
128    }
129
130    fn path(&self, mut builder: PathBuilder) -> Option<Path> {
131        if !self.add_to_builder(&mut builder) {
132            return None;
133        }
134        builder.build().ok()
135    }
136}
137
138impl Shape {
139    /// Resolves Material corner radii against the actual bounds and direction.
140    pub fn rounded(
141        bounds: Bounds<Pixels>,
142        corners: CornerShape,
143        direction: Direction,
144    ) -> Option<Self> {
145        let width = f32::from(bounds.size.width);
146        let height = f32::from(bounds.size.height);
147        let cubics = rounded_rect_cubics(width, height, corners, direction)?;
148        Self::new(Outline {
149            cubics,
150            bounds,
151            fit: ShapeFit::Stretch,
152            rotation: 0.,
153            pivot: PolygonPoint::splat(0.5),
154            scale: 1.,
155        })
156    }
157
158    /// Prepares one of the 35 Material 3 Expressive shapes fitted inside `bounds`.
159    pub fn material(bounds: Bounds<Pixels>, shape: MaterialShape) -> Option<Self> {
160        ShapePolygon::material(shape).to_shape(bounds)
161    }
162
163    /// Prepares any reusable [`ShapePolygon`] inside `bounds`.
164    pub fn polygon(bounds: Bounds<Pixels>, polygon: &ShapePolygon, fit: ShapeFit) -> Option<Self> {
165        polygon.to_shape_with(bounds, fit, 0.)
166    }
167
168    fn from_cubics(
169        cubics: Vec<Cubic>,
170        bounds: Bounds<Pixels>,
171        fit: ShapeFit,
172        rotation_radians: f32,
173    ) -> Option<Self> {
174        if !rotation_radians.is_finite() {
175            return None;
176        }
177        Self::new(Outline {
178            cubics,
179            bounds,
180            fit,
181            rotation: rotation_radians,
182            pivot: PolygonPoint::splat(0.5),
183            scale: 1.,
184        })
185    }
186
187    fn new(outline: Outline) -> Option<Self> {
188        let fill = outline.path(PathBuilder::fill())?;
189        Some(Self {
190            outline,
191            fill,
192            mesh: std::sync::OnceLock::new(),
193            stroke_cache: std::sync::OnceLock::new(),
194        })
195    }
196
197    fn mesh(&self) -> &FillMesh {
198        self.mesh.get_or_init(|| self.outline.flatten_mesh())
199    }
200
201    /// Returns the laid-out bounds that this shape was fitted into.
202    pub fn bounds(&self) -> Bounds<Pixels> {
203        self.outline.bounds
204    }
205
206    /// Returns the tight bounding box of this shape's flattened fill contour.
207    pub fn fill_bounds(&self) -> Bounds<Pixels> {
208        self.mesh().bounds
209    }
210
211    /// Returns the prepared GPUI fill [`Path`] for this shape.
212    pub fn fill_path(&self) -> &Path {
213        &self.fill
214    }
215
216    /// Builds a stroked outline path for this shape at the requested logical pixel width.
217    pub fn stroke_path(&self, width: Pixels) -> Option<Path> {
218        let raw = f32::from(width);
219        if !raw.is_finite() || raw <= 0. {
220            return None;
221        }
222        let bits = raw.to_bits();
223        if let Some((cached_bits, cached_path)) = self.stroke_cache.get()
224            && *cached_bits == bits
225        {
226            return Some(cached_path.clone());
227        }
228        let path = self.outline.path(PathBuilder::stroke(width))?;
229        let _ = self.stroke_cache.set((bits, path.clone()));
230        Some(path)
231    }
232
233    /// Returns whether `position` lies inside this shape's fill mesh.
234    pub fn contains(&self, position: Point<Pixels>) -> bool {
235        contains_fill(self.mesh(), position)
236    }
237
238    /// Shape-aware hit test against the fill mesh with an optional outward `slop`
239    /// tolerance in logical pixels. Non-finite coordinates return `false`.
240    pub fn hit_test(&self, position: Point<Pixels>, slop: Pixels) -> bool {
241        if !f32::from(position.x).is_finite() || !f32::from(position.y).is_finite() {
242            return false;
243        }
244        if self.contains(position) {
245            return true;
246        }
247        let slop = f32::from(slop);
248        if !slop.is_finite() || slop <= 0. {
249            return false;
250        }
251        let mesh = self.mesh();
252        let min_x = f32::from(mesh.bounds.left()) - slop;
253        let max_x = f32::from(mesh.bounds.right()) + slop;
254        let min_y = f32::from(mesh.bounds.top()) - slop;
255        let max_y = f32::from(mesh.bounds.bottom()) + slop;
256        let px_x = f32::from(position.x);
257        let px_y = f32::from(position.y);
258        if px_x < min_x || px_x > max_x || px_y < min_y || px_y > max_y {
259            return false;
260        }
261        let limit_sq = slop * slop;
262        mesh.triangles.iter().any(|&[a, b, c]| {
263            if cross(b - a, c - a).abs() <= f32::EPSILON {
264                return false;
265            }
266            segment_distance_sq(position, a, b) <= limit_sq
267                || segment_distance_sq(position, b, c) <= limit_sq
268                || segment_distance_sq(position, c, a) <= limit_sq
269        })
270    }
271
272    /// Returns whether this shape's fill mesh intersects the axis-aligned rectangle `rect`.
273    pub fn intersects_bounds(&self, rect: Bounds<Pixels>) -> bool {
274        let mesh = self.mesh();
275        if !rect_is_valid(rect) || !bounds_overlap(mesh.bounds, rect) {
276            return false;
277        }
278        let mut polygon = Vec::with_capacity(8);
279        let mut scratch = Vec::with_capacity(8);
280        for &[a, b, c] in &mesh.triangles {
281            if triangle_disjoint_from_rect([a, b, c], rect)
282                || cross(b - a, c - a).abs() <= f32::EPSILON
283            {
284                continue;
285            }
286            polygon.clear();
287            polygon.extend([a, b, c]);
288            clip_polygon_to_rect(&mut polygon, &mut scratch, rect);
289            if polygon.len() >= 3 && polygon_area(&polygon).abs() > f32::EPSILON {
290                return true;
291            }
292        }
293        false
294    }
295
296    /// Clips an axis-aligned rectangle against this shape's fill mesh.
297    pub fn clip_rect(&self, rect: Bounds<Pixels>) -> Option<Path> {
298        clip_rect_fill(self.mesh(), rect).to_path()
299    }
300
301    /// Clips a disc centered at `origin` with logical `radius` against this shape's fill mesh.
302    pub fn clip_disc(&self, origin: Point<Pixels>, radius: Pixels) -> Option<Path> {
303        clipped_ripple(self.mesh(), origin, radius).to_path()
304    }
305
306    /// Clips a convex polygon (in either winding order) against this shape's fill mesh.
307    pub fn clip_convex_polygon(&self, vertices: &[Point<Pixels>]) -> Option<Path> {
308        clip_convex_polygon_fill(self.mesh(), vertices).to_path()
309    }
310
311    /// Clips another [`Shape`] (convex or concave) against this shape's fill mesh,
312    /// returning the exact geometric intersection.
313    pub fn clip_shape(&self, source: &Shape) -> Option<Path> {
314        clip_mesh_fill(self.mesh(), source.mesh()).to_path()
315    }
316
317    /// Builds an EvenOdd exterior mask representing `outer \ self` within `outer`.
318    ///
319    /// Because GPUI's native `ContentMask` is rectangular, painting this exterior mask
320    /// in a uniform parent backdrop color visually clips arbitrary child elements to the
321    /// exact non-rectangular shape contour.
322    pub fn exterior_mask(&self, outer: Bounds<Pixels>) -> Option<Path> {
323        if !rect_is_valid(outer) {
324            return None;
325        }
326        let mesh = self.mesh();
327        let contained = mesh.bounds.left() >= outer.left()
328            && mesh.bounds.right() <= outer.right()
329            && mesh.bounds.top() >= outer.top()
330            && mesh.bounds.bottom() <= outer.bottom();
331        let mut builder = PathBuilder::fill().with_style(PathStyle::Fill(FillOptions {
332            fill_rule: FillRule::EvenOdd,
333        }));
334        builder.move_to(outer.origin);
335        builder.line_to(outer.top_right());
336        builder.line_to(outer.bottom_right());
337        builder.line_to(outer.bottom_left());
338        builder.close();
339        if contained {
340            if !self.outline.add_to_builder(&mut builder) {
341                return None;
342            }
343        } else {
344            let interior = clip_rect_fill(mesh, outer);
345            for &[a, b, c] in &interior.triangles {
346                if cross(b - a, c - a).abs() <= f32::EPSILON {
347                    continue;
348                }
349                builder.move_to(a);
350                builder.line_to(b);
351                builder.line_to(c);
352                builder.close();
353            }
354        }
355        builder.build().ok()
356    }
357
358    /// Paints the fill path with `color`.
359    pub fn paint(&self, color: Hsla, window: &mut Window) {
360        window.paint_path(self.fill.clone(), color);
361    }
362
363    /// Paints a stroked outline around this shape.
364    pub fn paint_stroke(&self, width: Pixels, color: Hsla, window: &mut Window) {
365        if let Some(path) = self.stroke_path(width) {
366            window.paint_path(path, color);
367        }
368    }
369
370    /// Paints `source` clipped to this shape's fill mesh.
371    pub fn paint_clipped_shape(&self, source: &Shape, color: Hsla, window: &mut Window) {
372        if let Some(clipped) = self.clip_shape(source) {
373            window.paint_path(clipped, color);
374        }
375    }
376
377    /// Paints `rect` clipped to this shape's fill mesh.
378    pub fn paint_clipped_rect(&self, rect: Bounds<Pixels>, color: Hsla, window: &mut Window) {
379        if let Some(clipped) = self.clip_rect(rect) {
380            window.paint_path(clipped, color);
381        }
382    }
383
384    /// Paints a disc clipped to this shape's fill mesh.
385    pub fn paint_clipped_disc(
386        &self,
387        origin: Point<Pixels>,
388        radius: Pixels,
389        color: Hsla,
390        window: &mut Window,
391    ) {
392        self.paint_ripple(origin, radius, color, window);
393    }
394
395    /// Paints the EvenOdd exterior mask `outer \ self` in `backdrop` to visually clip
396    /// overflowing children to this shape on a uniform background.
397    pub fn paint_backdrop_mask(&self, outer: Bounds<Pixels>, backdrop: Hsla, window: &mut Window) {
398        if let Some(mask) = self.exterior_mask(outer) {
399            window.paint_path(mask, backdrop);
400        }
401    }
402
403    /// Approximates a shape-matched elevation shadow with three translucent fills.
404    pub fn paint_shadow(&self, elevation: f32, scale: f32, shadow: Hsla, window: &mut Window) {
405        let dp = elevation * scale;
406        if !dp.is_finite() || dp <= 0. || !scale.is_finite() || scale <= 0. {
407            return;
408        }
409        for (offset_y, spread, alpha) in [
410            (dp * 0.45, dp * 0.35, 0.08),
411            (dp * 0.25, dp * 0.18, 0.10),
412            (scale.min(dp * 0.5), dp * 0.06, 0.12),
413        ] {
414            let expanded = Bounds::new(
415                self.outline.bounds.origin + point(px(-spread), px(offset_y - spread)),
416                size(
417                    self.outline.bounds.size.width + px(spread * 2.),
418                    self.outline.bounds.size.height + px(spread * 2.),
419                ),
420            );
421            let layer = Outline {
422                bounds: expanded,
423                ..self.outline.clone()
424            };
425            if let Some(path) = layer.path(PathBuilder::fill()) {
426                window.paint_path(path, shadow.opacity(alpha));
427            }
428        }
429    }
430
431    pub(crate) fn paint_ring(&self, width: Pixels, color: Hsla, window: &mut Window) {
432        self.paint_stroke(width, color, window);
433    }
434
435    pub(crate) fn paint_ripple(
436        &self,
437        origin: Point<Pixels>,
438        radius: Pixels,
439        color: Hsla,
440        window: &mut Window,
441    ) {
442        if let Some(path) = self.clip_disc(origin, radius) {
443            window.paint_path(path, color);
444        }
445    }
446}