Skip to main content

gpui_material_foundation/shape/
morph.rs

1use std::panic::{AssertUnwindSafe, catch_unwind};
2
3use gpui::{Bounds, Pixels, px};
4use gpui_material_theme::PolygonRole;
5use polymorpher::{Cubic, Morph, geometry::Point as PolygonPoint};
6
7use super::polygon::{ShapePolygon, cubic_center};
8use super::{Outline, Shape, ShapeFit};
9
10/// A reusable morph between any two [`ShapePolygon`] contours.
11///
12/// Uses `polymorpher`'s feature-matched morph when both endpoints are `RoundedPolygon`s
13/// and falls back to perimeter-length cubic alignment when an endpoint is an arbitrary
14/// cubic contour or triggers a feature-matching edge case.
15#[derive(Clone)]
16pub struct ShapeMorph {
17    kind: MorphKind,
18}
19
20#[derive(Clone)]
21enum MorphKind {
22    FeatureMatched(Morph),
23    PerimeterAligned(Vec<(Cubic, Cubic)>),
24}
25
26impl ShapeMorph {
27    /// Creates a reusable morph between any two shapes (such as
28    /// [`MaterialShape`](gpui_material_theme::MaterialShape), [`PolygonRole`], or
29    /// [`ShapePolygon`]).
30    pub fn new(start: impl Into<ShapePolygon>, end: impl Into<ShapePolygon>) -> Self {
31        let start = start.into();
32        let end = end.into();
33        let kind = match (start.as_rounded(), end.as_rounded()) {
34            (Some(from), Some(to)) => {
35                match catch_unwind(AssertUnwindSafe(|| Morph::new(from.clone(), to.clone()))) {
36                    Ok(morph) => MorphKind::FeatureMatched(morph),
37                    Err(_) => {
38                        MorphKind::PerimeterAligned(align_perimeter(&from.cubics, &to.cubics))
39                    }
40                }
41            }
42            _ => MorphKind::PerimeterAligned(align_perimeter(start.cubics(), end.cubics())),
43        };
44        Self { kind }
45    }
46
47    /// Creates a morph aligned strictly by normalized perimeter length, preserving exact
48    /// endpoint curves with bounded cubic count even for arbitrary concave polygons.
49    pub fn perimeter_aligned(start: impl Into<ShapePolygon>, end: impl Into<ShapePolygon>) -> Self {
50        let start = start.into();
51        let end = end.into();
52        Self {
53            kind: MorphKind::PerimeterAligned(align_perimeter(start.cubics(), end.cubics())),
54        }
55    }
56
57    /// Samples the interpolated normalized contour at `progress` (clamped to `0..=1`).
58    pub fn sample_polygon(&self, progress: f32) -> ShapePolygon {
59        ShapePolygon::from_cubics(self.as_cubics(clamp_progress(progress)))
60    }
61
62    /// Fits the sampled shape inside `bounds` while preserving aspect ratio.
63    pub fn sample(&self, bounds: Bounds<Pixels>, progress: f32) -> Option<Shape> {
64        self.sample_with(bounds, progress, ShapeFit::Contain, 0.)
65    }
66
67    /// Samples the morph into `bounds` with explicit fit mode and clockwise rotation in radians.
68    pub fn sample_with(
69        &self,
70        bounds: Bounds<Pixels>,
71        progress: f32,
72        fit: ShapeFit,
73        rotation_radians: f32,
74    ) -> Option<Shape> {
75        Shape::from_cubics(
76            self.as_cubics(clamp_progress(progress)),
77            bounds,
78            fit,
79            rotation_radians,
80        )
81    }
82
83    fn as_cubics(&self, progress: f32) -> Vec<Cubic> {
84        match &self.kind {
85            MorphKind::FeatureMatched(morph) => morph.as_cubics(progress),
86            MorphKind::PerimeterAligned(pairs) => pairs
87                .iter()
88                .map(|(a, b)| {
89                    Cubic::new(
90                        a.anchor0().lerp(b.anchor0(), progress),
91                        a.control0().lerp(b.control0(), progress),
92                        a.control1().lerp(b.control1(), progress),
93                        a.anchor1().lerp(b.anchor1(), progress),
94                    )
95                })
96                .collect(),
97        }
98    }
99}
100
101/// A reusable multi-step sequence of [`ShapeMorph`] transitions.
102#[derive(Clone)]
103pub struct ShapeMorphSequence {
104    steps: Vec<ShapeMorph>,
105    wrap: Option<ShapeMorph>,
106    rotation_scale: f32,
107    control_radius: Option<f32>,
108}
109
110impl ShapeMorphSequence {
111    /// Builds a feature-matched morph sequence from at least two shapes.
112    /// When `looping` is `true`, adds a wrap transition from the last shape back to the first.
113    pub fn new(
114        shapes: impl IntoIterator<Item = impl Into<ShapePolygon>>,
115        looping: bool,
116    ) -> Option<Self> {
117        Self::build(shapes, looping, false)
118    }
119
120    /// Builds a perimeter-aligned morph sequence from at least two shapes.
121    pub fn perimeter_aligned(
122        shapes: impl IntoIterator<Item = impl Into<ShapePolygon>>,
123        looping: bool,
124    ) -> Option<Self> {
125        Self::build(shapes, looping, true)
126    }
127
128    fn build(
129        shapes: impl IntoIterator<Item = impl Into<ShapePolygon>>,
130        looping: bool,
131        perimeter_aligned: bool,
132    ) -> Option<Self> {
133        let polygons: Vec<ShapePolygon> = shapes.into_iter().map(Into::into).collect();
134        if polygons.len() < 2 {
135            return None;
136        }
137        let make = |a: &ShapePolygon, b: &ShapePolygon| {
138            if perimeter_aligned {
139                ShapeMorph::perimeter_aligned(a.clone(), b.clone())
140            } else {
141                ShapeMorph::new(a.clone(), b.clone())
142            }
143        };
144        let steps = polygons
145            .windows(2)
146            .map(|pair| make(&pair[0], &pair[1]))
147            .collect();
148        let wrap = looping.then(|| make(polygons.last().unwrap(), &polygons[0]));
149        let rotation_scale = polygons
150            .iter()
151            .fold(1_f32, |scale, polygon| scale.min(polygon.rotation_scale()));
152        let control_radius = perimeter_aligned.then(|| {
153            polygons
154                .iter()
155                .map(ShapePolygon::control_point_radius)
156                .fold(0_f32, f32::max)
157        });
158        Some(Self {
159            steps,
160            wrap,
161            rotation_scale,
162            control_radius,
163        })
164    }
165
166    /// Number of endpoint shapes in this sequence.
167    pub fn len(&self) -> usize {
168        self.steps.len() + 1
169    }
170
171    /// Always `false` because valid sequences contain at least two shapes.
172    pub fn is_empty(&self) -> bool {
173        false
174    }
175
176    /// Number of morph transitions (`len() - 1` when open, `len()` when looping).
177    pub fn step_count(&self) -> usize {
178        self.steps.len() + usize::from(self.wrap.is_some())
179    }
180
181    pub fn is_looping(&self) -> bool {
182        self.wrap.is_some()
183    }
184
185    /// Minimum rotation-safe scale factor across all shapes in the sequence.
186    pub fn rotation_scale(&self) -> f32 {
187        self.rotation_scale
188    }
189
190    /// Samples the open progression across `[0, 1]` from the first shape to the last.
191    pub fn sample(&self, bounds: Bounds<Pixels>, progress: f32) -> Option<Shape> {
192        let value = clamp_progress(progress);
193        let phase = value * self.steps.len() as f32;
194        let index = (phase as usize).min(self.steps.len() - 1);
195        self.sample_step(index, phase - index as f32, bounds, ShapeFit::Contain, 0.)
196    }
197
198    /// Samples a specific transition step at `progress` in `0..=1`.
199    pub fn sample_step(
200        &self,
201        step: usize,
202        progress: f32,
203        bounds: Bounds<Pixels>,
204        fit: ShapeFit,
205        rotation_radians: f32,
206    ) -> Option<Shape> {
207        let morph = self.morph_for_step(step)?;
208        morph.sample_with(bounds, progress, fit, rotation_radians)
209    }
210
211    /// Samples a specific transition step as a reusable [`ShapePolygon`].
212    pub fn sample_step_polygon(&self, step: usize, progress: f32) -> Option<ShapePolygon> {
213        let morph = self.morph_for_step(step)?;
214        Some(morph.sample_polygon(progress))
215    }
216
217    /// Samples a transition step centered on its live cubic bounding box and scaled to
218    /// fit safely inside a circular envelope of diameter `extent` under arbitrary rotation.
219    ///
220    /// Used by `LoadingIndicator` to keep rotating Material and custom morph sequences
221    /// strictly inside their active footprint without resizing shared endpoints.
222    pub fn sample_step_in_envelope(
223        &self,
224        step: usize,
225        progress: f32,
226        bounds: Bounds<Pixels>,
227        extent: Pixels,
228        rotation_radians: f32,
229    ) -> Option<Shape> {
230        if !rotation_radians.is_finite() {
231            return None;
232        }
233        let morph = self.morph_for_step(step)?;
234        let cubics = morph.as_cubics(clamp_progress(progress));
235        if cubics.is_empty() {
236            return None;
237        }
238        let pivot = cubic_center(&cubics);
239        let side = bounds.size.width.min(bounds.size.height);
240        let extent = side.min(extent);
241        if !(extent > px(0.) && extent < px(f32::INFINITY)) {
242            return None;
243        }
244        let mut target_side = extent * self.rotation_scale;
245        if let Some(radius) = self.control_radius {
246            let radius = radius + (pivot - PolygonPoint::splat(0.5)).length();
247            if radius > f32::EPSILON {
248                target_side = target_side.min(extent / (2. * radius));
249            }
250        }
251        let scale = f32::from(target_side) / f32::from(side);
252        Shape::new(Outline {
253            cubics,
254            bounds,
255            fit: ShapeFit::Contain,
256            rotation: rotation_radians,
257            pivot,
258            scale,
259        })
260    }
261
262    fn morph_for_step(&self, step: usize) -> Option<&ShapeMorph> {
263        if self.wrap.is_some() {
264            let count = self.steps.len() + 1;
265            let index = step % count;
266            self.steps.get(index).or(self.wrap.as_ref())
267        } else {
268            self.steps.get(step)
269        }
270    }
271}
272
273/// A reusable morph between two pinned Material polygon roles.
274#[derive(Clone)]
275pub struct PolygonMorph(ShapeMorph);
276
277impl PolygonMorph {
278    pub fn new(start: PolygonRole, end: PolygonRole) -> Self {
279        Self(ShapeMorph::new(start, end))
280    }
281
282    /// Fits the sampled polygon inside the bounds while preserving aspect ratio.
283    pub fn sample(&self, bounds: Bounds<Pixels>, progress: f32) -> Option<Shape> {
284        self.0.sample(bounds, progress)
285    }
286}
287
288fn clamp_progress(progress: f32) -> f32 {
289    if progress.is_finite() {
290        progress.clamp(0., 1.)
291    } else {
292        0.
293    }
294}
295
296fn align_perimeter(start: &[Cubic], end: &[Cubic]) -> Vec<(Cubic, Cubic)> {
297    let mut starts = weighted_segments(start).into_iter();
298    let mut ends = weighted_segments(end).into_iter();
299    let (mut from, mut to) = (starts.next(), ends.next());
300    let mut position = 0.;
301    let mut pairs = Vec::new();
302    while let (Some(mut a), Some(mut b)) = (from, to) {
303        let boundary = a.0.min(b.0);
304        let first = split_until(&mut a, position, boundary);
305        let last = split_until(&mut b, position, boundary);
306        pairs.push((first, last));
307        from = if boundary == a.0 {
308            starts.next()
309        } else {
310            Some(a)
311        };
312        to = if boundary == b.0 {
313            ends.next()
314        } else {
315            Some(b)
316        };
317        position = boundary;
318    }
319    pairs
320}
321
322fn weighted_segments(cubics: &[Cubic]) -> Vec<(f64, Cubic)> {
323    let mut cumulative = 0.;
324    let mut segments: Vec<_> = cubics
325        .iter()
326        .map(|cubic| {
327            let samples = [
328                cubic.anchor0(),
329                cubic.point_on_curve(0.25),
330                cubic.point_on_curve(0.5),
331                cubic.point_on_curve(0.75),
332                cubic.anchor1(),
333            ];
334            cumulative += samples
335                .windows(2)
336                .map(|points| f64::from((points[1] - points[0]).length()))
337                .sum::<f64>();
338            (cumulative, *cubic)
339        })
340        .collect();
341    if cumulative > 0. {
342        for (end, _) in &mut segments {
343            *end /= cumulative;
344        }
345    }
346    segments
347}
348
349fn split_until(segment: &mut (f64, Cubic), from: f64, until: f64) -> Cubic {
350    if until == segment.0 {
351        return segment.1;
352    }
353    let (head, tail) = segment
354        .1
355        .split(((until - from) / (segment.0 - from)) as f32);
356    segment.1 = tail;
357    head
358}