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    /// Returns `true` when the sequence wraps from its last shape back to the first.
182    pub fn is_looping(&self) -> bool {
183        self.wrap.is_some()
184    }
185
186    /// Minimum rotation-safe scale factor across all shapes in the sequence.
187    pub fn rotation_scale(&self) -> f32 {
188        self.rotation_scale
189    }
190
191    /// Samples the open progression across `[0, 1]` from the first shape to the last.
192    pub fn sample(&self, bounds: Bounds<Pixels>, progress: f32) -> Option<Shape> {
193        let value = clamp_progress(progress);
194        let phase = value * self.steps.len() as f32;
195        let index = (phase as usize).min(self.steps.len() - 1);
196        self.sample_step(index, phase - index as f32, bounds, ShapeFit::Contain, 0.)
197    }
198
199    /// Samples a specific transition step at `progress` in `0..=1`.
200    pub fn sample_step(
201        &self,
202        step: usize,
203        progress: f32,
204        bounds: Bounds<Pixels>,
205        fit: ShapeFit,
206        rotation_radians: f32,
207    ) -> Option<Shape> {
208        let morph = self.morph_for_step(step)?;
209        morph.sample_with(bounds, progress, fit, rotation_radians)
210    }
211
212    /// Samples a specific transition step as a reusable [`ShapePolygon`].
213    pub fn sample_step_polygon(&self, step: usize, progress: f32) -> Option<ShapePolygon> {
214        let morph = self.morph_for_step(step)?;
215        Some(morph.sample_polygon(progress))
216    }
217
218    /// Samples a transition step centered on its live cubic bounding box and scaled to
219    /// fit safely inside a circular envelope of diameter `extent` under arbitrary rotation.
220    ///
221    /// Used by `LoadingIndicator` to keep rotating Material and custom morph sequences
222    /// strictly inside their active footprint without resizing shared endpoints.
223    pub fn sample_step_in_envelope(
224        &self,
225        step: usize,
226        progress: f32,
227        bounds: Bounds<Pixels>,
228        extent: Pixels,
229        rotation_radians: f32,
230    ) -> Option<Shape> {
231        if !rotation_radians.is_finite() {
232            return None;
233        }
234        let morph = self.morph_for_step(step)?;
235        let cubics = morph.as_cubics(clamp_progress(progress));
236        if cubics.is_empty() {
237            return None;
238        }
239        let pivot = cubic_center(&cubics);
240        let side = bounds.size.width.min(bounds.size.height);
241        let extent = side.min(extent);
242        if !(extent > px(0.) && extent < px(f32::INFINITY)) {
243            return None;
244        }
245        let mut target_side = extent * self.rotation_scale;
246        if let Some(radius) = self.control_radius {
247            let radius = radius + (pivot - PolygonPoint::splat(0.5)).length();
248            if radius > f32::EPSILON {
249                target_side = target_side.min(extent / (2. * radius));
250            }
251        }
252        let scale = f32::from(target_side) / f32::from(side);
253        Shape::new(Outline {
254            cubics,
255            bounds,
256            fit: ShapeFit::Contain,
257            rotation: rotation_radians,
258            pivot,
259            scale,
260        })
261    }
262
263    fn morph_for_step(&self, step: usize) -> Option<&ShapeMorph> {
264        if self.wrap.is_some() {
265            let count = self.steps.len() + 1;
266            let index = step % count;
267            self.steps.get(index).or(self.wrap.as_ref())
268        } else {
269            self.steps.get(step)
270        }
271    }
272}
273
274/// A reusable morph between two pinned Material polygon roles.
275#[derive(Clone)]
276pub struct PolygonMorph(ShapeMorph);
277
278impl PolygonMorph {
279    /// Creates a reusable morph between two Material [`PolygonRole`] endpoints.
280    pub fn new(start: PolygonRole, end: PolygonRole) -> Self {
281        Self(ShapeMorph::new(start, end))
282    }
283
284    /// Fits the sampled polygon inside the bounds while preserving aspect ratio.
285    pub fn sample(&self, bounds: Bounds<Pixels>, progress: f32) -> Option<Shape> {
286        self.0.sample(bounds, progress)
287    }
288}
289
290fn clamp_progress(progress: f32) -> f32 {
291    if progress.is_finite() {
292        progress.clamp(0., 1.)
293    } else {
294        0.
295    }
296}
297
298fn align_perimeter(start: &[Cubic], end: &[Cubic]) -> Vec<(Cubic, Cubic)> {
299    let mut starts = weighted_segments(start).into_iter();
300    let mut ends = weighted_segments(end).into_iter();
301    let (mut from, mut to) = (starts.next(), ends.next());
302    let mut position = 0.;
303    let mut pairs = Vec::new();
304    while let (Some(mut a), Some(mut b)) = (from, to) {
305        let boundary = a.0.min(b.0);
306        let first = split_until(&mut a, position, boundary);
307        let last = split_until(&mut b, position, boundary);
308        pairs.push((first, last));
309        from = if boundary == a.0 {
310            starts.next()
311        } else {
312            Some(a)
313        };
314        to = if boundary == b.0 {
315            ends.next()
316        } else {
317            Some(b)
318        };
319        position = boundary;
320    }
321    pairs
322}
323
324fn weighted_segments(cubics: &[Cubic]) -> Vec<(f64, Cubic)> {
325    let mut cumulative = 0.;
326    let mut segments: Vec<_> = cubics
327        .iter()
328        .map(|cubic| {
329            let samples = [
330                cubic.anchor0(),
331                cubic.point_on_curve(0.25),
332                cubic.point_on_curve(0.5),
333                cubic.point_on_curve(0.75),
334                cubic.anchor1(),
335            ];
336            cumulative += samples
337                .windows(2)
338                .map(|points| f64::from((points[1] - points[0]).length()))
339                .sum::<f64>();
340            (cumulative, *cubic)
341        })
342        .collect();
343    if cumulative > 0. {
344        for (end, _) in &mut segments {
345            *end /= cumulative;
346        }
347    }
348    segments
349}
350
351fn split_until(segment: &mut (f64, Cubic), from: f64, until: f64) -> Cubic {
352    if until == segment.0 {
353        return segment.1;
354    }
355    let (head, tail) = segment
356        .1
357        .split(((until - from) / (segment.0 - from)) as f32);
358    segment.1 = tail;
359    head
360}