diff --git a/crates/gpui/examples/svg_animation.rs b/crates/gpui/examples/svg_animation.rs new file mode 100644 index 00000000000..db915065dbb --- /dev/null +++ b/crates/gpui/examples/svg_animation.rs @@ -0,0 +1,222 @@ +#![cfg_attr(target_family = "wasm", no_main)] + +//! Compares SVGs animated with [`Svg::with_timed_transformation`], which +//! moves them in the already painted scene, against the same SVGs animated by +//! re-rendering with `with_animation`. It shows spinners and pulsing rings. +//! +//! The header counts how many times the view has rendered. With the retained +//! scene the count stays put while the SVGs keep animating; when re-rendering +//! it climbs once per frame. Pass `--rerender` to start in that mode, and +//! `--max-fps ` to cap how often the retained scene is presented. + +#[path = "example_support/fonts.rs"] +mod example_support; + +use std::{cell::Cell, time::Duration}; + +use gpui::{ + Animation, AnimationExt as _, App, Bounds, Context, Easing, TimedTransformation, + Transformation, Window, WindowBounds, WindowOptions, div, ease_out_quint, percentage, + prelude::*, px, rgb, size, svg, +}; +use gpui_platform::application; + +const ARROW_CIRCLE_SVG: &str = concat!( + env!("CARGO_MANIFEST_DIR"), + "/examples/image/arrow_circle.svg" +); + +const RING_SVG: &[u8] = br#""#; + +const SPINNER_COUNT: usize = 100; +const PULSE_COUNT: usize = 100; +const SPIN_PERIOD: Duration = Duration::from_secs(2); +const PULSE_PERIOD: Duration = Duration::from_millis(1750); + +#[derive(Clone, Copy, PartialEq)] +enum Mode { + RetainedScene, + Rerender, +} + +struct SvgAnimationExample { + mode: Mode, + max_fps: Option, + render_count: Cell, +} + +impl SvgAnimationExample { + fn timed(&self, transformation: TimedTransformation) -> TimedTransformation { + match self.max_fps { + Some(max_fps) => transformation.with_max_fps(max_fps), + None => transformation, + } + } + + fn pulse(&self, index: usize) -> impl IntoElement { + let ring = svg().size_4().data(RING_SVG).text_color(rgb(0x16a34a)); + let ring = match self.mode { + Mode::RetainedScene => ring + .with_timed_transformation( + self.timed( + TimedTransformation::new(PULSE_PERIOD) + .from(Transformation::alpha(0.6)) + .to(Transformation::scale(size(1.5, 1.5)).with_alpha(0.)) + .with_scale_easing(Easing::EaseOutQuint), + ), + ) + .into_any_element(), + Mode::Rerender => ring + .with_animation( + ("pulse", index), + Animation::new(PULSE_PERIOD).repeat_synced(), + |svg, delta| { + let scale = 1. + 0.5 * ease_out_quint()(delta); + svg.with_transformation( + Transformation::scale(size(scale, scale)) + .with_alpha(0.6 * (1. - delta)), + ) + }, + ) + .into_any_element(), + }; + div() + .size_6() + .flex() + .items_center() + .justify_center() + .child(div().absolute().size_1p5().rounded_full().bg(rgb(0x16a34a))) + .child(ring) + } + + fn spinner(&self, index: usize) -> impl IntoElement { + let spinner = svg() + .size_6() + .external_path(ARROW_CIRCLE_SVG) + .text_color(rgb(0x3b82f6)); + match self.mode { + Mode::RetainedScene => spinner + .with_timed_transformation(self.timed(TimedTransformation::rotation( + SPIN_PERIOD, + Transformation::default(), + ))) + .into_any_element(), + Mode::Rerender => spinner + .with_animation( + ("spinner", index), + Animation::new(SPIN_PERIOD).repeat_synced(), + |svg, delta| svg.with_transformation(Transformation::rotate(percentage(delta))), + ) + .into_any_element(), + } + } +} + +impl Render for SvgAnimationExample { + fn render(&mut self, _window: &mut Window, cx: &mut Context) -> impl IntoElement { + self.render_count.set(self.render_count.get() + 1); + let mode = self.mode; + let mode_label = match mode { + Mode::RetainedScene => "retained scene (with_timed_transformation)", + Mode::Rerender => "re-render (with_animation)", + }; + + div() + .flex() + .flex_col() + .size_full() + .bg(gpui::white()) + .text_color(gpui::black()) + .p_4() + .gap_3() + .child( + div() + .flex() + .flex_row() + .items_center() + .gap_4() + .child( + div() + .id("toggle-mode") + .px_3() + .py_1() + .rounded_md() + .bg(rgb(0xe5e7eb)) + .cursor_pointer() + .child(format!("Mode: {mode_label}")) + .on_click(cx.listener(|this, _, _, cx| { + this.mode = match this.mode { + Mode::RetainedScene => Mode::Rerender, + Mode::Rerender => Mode::RetainedScene, + }; + cx.notify(); + })), + ) + .child(format!("Renders: {}", self.render_count.get())), + ) + .child( + div() + .flex() + .flex_row() + .flex_wrap() + .gap_2() + .children((0..SPINNER_COUNT).map(|index| self.spinner(index))), + ) + .child( + div() + .flex() + .flex_row() + .flex_wrap() + .gap_2() + .children((0..PULSE_COUNT).map(|index| self.pulse(index))), + ) + } +} + +fn run_example() { + application().run(|cx: &mut App| { + if !example_support::load_fonts(cx) { + return; + } + let options = WindowOptions { + window_bounds: Some(WindowBounds::Windowed(Bounds::centered( + None, + size(px(720.), px(480.)), + cx, + ))), + ..Default::default() + }; + cx.open_window(options, |_, cx| { + cx.activate(false); + let mode = if std::env::args().any(|arg| arg == "--rerender") { + Mode::Rerender + } else { + Mode::RetainedScene + }; + let mut arguments = std::env::args(); + let max_fps = arguments + .by_ref() + .find(|argument| argument == "--max-fps") + .and_then(|_| arguments.next()) + .and_then(|max_fps| max_fps.parse().ok()); + cx.new(|_| SvgAnimationExample { + mode, + max_fps, + render_count: Cell::new(0), + }) + }) + .expect("failed to open window"); + }); +} + +#[cfg(not(target_family = "wasm"))] +fn main() { + run_example(); +} + +#[cfg(target_family = "wasm")] +#[wasm_bindgen::prelude::wasm_bindgen(start)] +pub fn start() { + gpui_platform::web_init(); + run_example(); +} diff --git a/crates/gpui/src/elements/animation.rs b/crates/gpui/src/elements/animation.rs index 33f7bc19fd6..ddb0b19e931 100644 --- a/crates/gpui/src/elements/animation.rs +++ b/crates/gpui/src/elements/animation.rs @@ -511,6 +511,15 @@ mod easing { move |delta| 1.0 - (1.0 - delta).powi(5) } + /// A heartbeat: a strong beat, a weaker one, then a rest. Starts and ends at 0 and peaks at 1. + pub fn heartbeat(delta: f32) -> f32 { + let beat = |center: f32, width: f32, height: f32| { + let x = (delta - center) / width; + height * (-x * x).exp() + }; + beat(0.2, 0.06, 1.0) + beat(0.4, 0.05, 0.58) + } + /// Apply the given easing function, first in the forward direction and then in the reverse direction pub fn bounce(easing: impl Fn(f32) -> f32) -> impl Fn(f32) -> f32 { move |delta| { diff --git a/crates/gpui/src/elements/svg.rs b/crates/gpui/src/elements/svg.rs index e87f0da63ca..8183abe4dd6 100644 --- a/crates/gpui/src/elements/svg.rs +++ b/crates/gpui/src/elements/svg.rs @@ -1,21 +1,24 @@ use std::{ + f32::consts::TAU, fs, hash::{Hash, Hasher}, path::Path, sync::Arc, + time::Duration, }; use crate::{ App, Asset, Bounds, Element, GlobalElementId, Hitbox, InspectorElementId, InteractiveElement, - Interactivity, LayoutId, Pixels, Point, Radians, SharedString, Size, StyleRefinement, Styled, - TransformationMatrix, Window, point, px, radians, size, + Interactivity, LayoutId, Pixels, Point, Radians, SharedString, Size, SpriteAnimation, + StyleRefinement, Styled, TransformationMatrix, Window, ease_in_out, ease_out_quint, heartbeat, + linear, point, px, quadratic, radians, size, }; use gpui_util::ResultExt; /// An SVG element. pub struct Svg { interactivity: Interactivity, - transformation: Option, + transformation: Option, path: Option, external_path: Option, data: Option>, @@ -64,6 +67,20 @@ impl Svg { /// Transform the SVG element with the given transformation. /// Note that this won't effect the hitbox or layout of the element, only the rendering. pub fn with_transformation(mut self, transformation: Transformation) -> Self { + self.transformation = Some(transformation.into()); + self + } + + /// Continuously animate the SVG between two transformations, phase-locked to the + /// app's shared animation clock like [`crate::Animation::repeat_synced`]. + /// + /// The SVG is painted once. On later frames the window moves it in the scene it + /// already has and presents that again, instead of re-rendering this view. + /// + /// This replaces [`Self::with_transformation`], and like it doesn't affect layout + /// or hit testing. The SVG is still clipped and ordered by the bounds of its + /// starting transformation, so keep its motion close to them. + pub fn with_timed_transformation(mut self, transformation: TimedTransformation) -> Self { self.transformation = Some(transformation); self } @@ -138,23 +155,35 @@ impl Element for Svg { window, cx, |style, window, cx| { - let transformation = self + let center = bounds.center(); + let scale_factor = window.scale_factor(); + let animation = self .transformation - .as_ref() - .map(|transformation| { - transformation.into_matrix(bounds.center(), window.scale_factor()) - }) + .filter(|timed| timed.is_animated() && !cx.reduce_motion()) + .map(|timed| SpriteAnimation::new(timed, center, scale_factor)); + // Without an animation, such as with reduced motion, the SVG is + // drawn at its starting transformation. + let pose = self.transformation.map(|timed| timed.from); + let transformation = pose + .map(|pose| pose.into_matrix(center, scale_factor)) .unwrap_or_default(); + // The scene applies an animated sprite's alpha before each present, + // on top of the color it is inserted with. + let alpha = match animation { + Some(_) => 1., + None => pose.map_or(1., |pose| pose.alpha_factor()), + }; if let Some((data, path)) = self.data.as_ref().zip(self.data_path.as_ref()) { if let Some(color) = style.text.color { window - .paint_svg( + .paint_animated_svg( bounds, path.clone(), Some(&**data), transformation, - color, + animation, + color.opacity(alpha), cx, ) .log_err(); @@ -170,18 +199,27 @@ impl Element for Svg { }; window - .paint_svg( + .paint_animated_svg( bounds, path.clone(), Some(&bytes), transformation, - color, + animation, + color.opacity(alpha), cx, ) .log_err(); } else if let Some((path, color)) = self.path.as_ref().zip(style.text.color) { window - .paint_svg(bounds, path.clone(), None, transformation, color, cx) + .paint_animated_svg( + bounds, + path.clone(), + None, + transformation, + animation, + color.opacity(alpha), + cx, + ) .log_err(); } }, @@ -207,6 +245,7 @@ pub struct Transformation { scale: Size, translate: Point, rotate: Radians, + alpha: f32, } impl Default for Transformation { @@ -215,6 +254,7 @@ impl Default for Transformation { scale: size(1.0, 1.0), translate: point(px(0.0), px(0.0)), rotate: radians(0.0), + alpha: 1.0, } } } @@ -224,17 +264,15 @@ impl Transformation { pub fn scale(scale: Size) -> Self { Self { scale, - translate: point(px(0.0), px(0.0)), - rotate: radians(0.0), + ..Self::default() } } /// Create a new Transformation with the specified translation. pub fn translate(translate: Point) -> Self { Self { - scale: size(1.0, 1.0), translate, - rotate: radians(0.0), + ..Self::default() } } @@ -242,12 +280,30 @@ impl Transformation { pub fn rotate(rotate: impl Into) -> Self { let rotate = rotate.into(); Self { - scale: size(1.0, 1.0), - translate: point(px(0.0), px(0.0)), rotate, + ..Self::default() } } + /// Create a new Transformation that multiplies the SVG's alpha by `alpha`. + pub fn alpha(alpha: f32) -> Self { + Self { + alpha, + ..Self::default() + } + } + + /// Update the alpha factor of this transformation. Unlike an element's + /// opacity, this only applies to the SVG itself. + pub fn with_alpha(mut self, alpha: f32) -> Self { + self.alpha = alpha; + self + } + + pub(crate) fn alpha_factor(&self) -> f32 { + self.alpha + } + /// Update the scaling factor of this transformation. pub fn with_scaling(mut self, scale: Size) -> Self { self.scale = scale; @@ -266,7 +322,11 @@ impl Transformation { self } - fn into_matrix(self, center: Point, scale_factor: f32) -> TransformationMatrix { + pub(crate) fn into_matrix( + self, + center: Point, + scale_factor: f32, + ) -> TransformationMatrix { //Note: if you read this as a sequence of matrix multiplications, start from the bottom TransformationMatrix::unit() .translate(center.scale(scale_factor) + self.translate.scale(scale_factor)) @@ -276,6 +336,201 @@ impl Transformation { } } +/// How a value's rate of change varies over one pass of a [`TimedTransformation`]. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum Easing { + /// A constant rate. + #[default] + Linear, + /// Starts slowly and accelerates. + Quadratic, + /// Starts and ends slowly, and speeds up in the middle. + EaseInOut, + /// Starts quickly and decelerates to a stop. + EaseOutQuint, + /// Two quick beats, a strong one then a weaker one, followed by a rest. + /// Unlike the other easings it ends where it started, so the value + /// reaches `to` at the first beat and is back at `from` by the end. + Heartbeat, +} + +impl Easing { + fn apply(self, delta: f32) -> f32 { + match self { + Easing::Linear => linear(delta), + Easing::Quadratic => quadratic(delta), + Easing::EaseInOut => ease_in_out(delta), + Easing::EaseOutQuint => ease_out_quint()(delta), + Easing::Heartbeat => heartbeat(delta), + } + } +} + +/// A [`Transformation`] that repeatedly moves from one pose to another over a +/// period, for [`Svg::with_timed_transformation`]. +/// +/// Each value of the transformation has its own [`Easing`], so for example an +/// SVG can grow quickly at first while fading at a constant rate. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct TimedTransformation { + period: Duration, + from: Transformation, + to: Transformation, + scale_easing: Easing, + translation_easing: Easing, + rotation_easing: Easing, + alpha_easing: Easing, + alternate: bool, + min_frame_interval: Option, +} + +impl TimedTransformation { + /// Create a timed transformation that repeats every `period`. It animates + /// nothing until [`Self::from`] and [`Self::to`] differ. + pub fn new(period: Duration) -> Self { + Self { + period, + from: Transformation::default(), + to: Transformation::default(), + scale_easing: Easing::Linear, + translation_easing: Easing::Linear, + rotation_easing: Easing::Linear, + alpha_easing: Easing::Linear, + alternate: false, + min_frame_interval: None, + } + } + + /// Create a timed transformation that turns `from` clockwise, one full + /// turn per `period`. + pub fn rotation(period: Duration, from: Transformation) -> Self { + Self::new(period) + .from(from) + .to(from.with_rotation(radians(from.rotate.0 + TAU))) + } + + fn is_animated(&self) -> bool { + !self.period.is_zero() && self.from != self.to + } + + /// Set the transformation at the start of each period. + pub fn from(mut self, transformation: Transformation) -> Self { + self.from = transformation; + self + } + + /// Set the transformation reached at the end of each period. + pub fn to(mut self, transformation: Transformation) -> Self { + self.to = transformation; + self + } + + /// Set the easing of every value. + pub fn with_easing(mut self, easing: Easing) -> Self { + self.scale_easing = easing; + self.translation_easing = easing; + self.rotation_easing = easing; + self.alpha_easing = easing; + self + } + + /// Set the easing of the scale. + pub fn with_scale_easing(mut self, easing: Easing) -> Self { + self.scale_easing = easing; + self + } + + /// Set the easing of the translation. + pub fn with_translation_easing(mut self, easing: Easing) -> Self { + self.translation_easing = easing; + self + } + + /// Set the easing of the rotation. + pub fn with_rotation_easing(mut self, easing: Easing) -> Self { + self.rotation_easing = easing; + self + } + + /// Set the easing of the alpha. + pub fn with_alpha_easing(mut self, easing: Easing) -> Self { + self.alpha_easing = easing; + self + } + + /// Move from the start to the end and back again within each period, + /// instead of jumping back to the start. + pub fn alternate(mut self) -> Self { + self.alternate = true; + self + } + + /// Present at most `max_fps` frames per second while nothing but timed + /// transformations needs a frame. The least restrictive limit in a window + /// wins. Values that are not finite and positive are ignored. + pub fn with_max_fps(mut self, max_fps: f32) -> Self { + if max_fps.is_finite() && max_fps > 0.0 { + self.min_frame_interval = Some(Duration::from_secs_f64(1.0 / max_fps as f64)); + } + self + } + + pub(crate) fn min_frame_interval(&self) -> Option { + self.min_frame_interval + } + + /// The transformation `elapsed` time after the animation clock started. + pub(crate) fn at(&self, elapsed: Duration) -> Transformation { + let period_nanos = self.period.as_nanos(); + if period_nanos == 0 { + return self.from; + } + let mut delta = Duration::from_nanos((elapsed.as_nanos() % period_nanos) as u64) + .as_secs_f32() + / self.period.as_secs_f32(); + if self.alternate { + delta = 1.0 - (2.0 * delta - 1.0).abs(); + } + + let interpolate = + |from: f32, to: f32, easing: Easing| from + (to - from) * easing.apply(delta); + let (from, to) = (self.from, self.to); + Transformation { + scale: size( + interpolate(from.scale.width, to.scale.width, self.scale_easing), + interpolate(from.scale.height, to.scale.height, self.scale_easing), + ), + translate: point( + px(interpolate( + from.translate.x.0, + to.translate.x.0, + self.translation_easing, + )), + px(interpolate( + from.translate.y.0, + to.translate.y.0, + self.translation_easing, + )), + ), + rotate: radians(interpolate( + from.rotate.0, + to.rotate.0, + self.rotation_easing, + )), + alpha: interpolate(from.alpha, to.alpha, self.alpha_easing), + } + } +} + +impl From for TimedTransformation { + /// A timed transformation that stays at `transformation`. + fn from(transformation: Transformation) -> Self { + Self::new(Duration::ZERO) + .from(transformation) + .to(transformation) + } +} + enum SvgAsset {} impl Asset for SvgAsset { @@ -293,3 +548,182 @@ impl Asset for SvgAsset { } } } + +#[cfg(test)] +mod tests { + use std::{cell::Cell, f32::consts::FRAC_PI_2, rc::Rc, time::Duration}; + + use crate::{ + Context, Easing, IntoElement, Render, SpriteAnimationId, Styled, TestAppContext, + TimedTransformation, Transformation, VisualTestContext, Window, div, prelude::*, px, red, + size, svg, + }; + + const SQUARE_SVG: &[u8] = + br#""#; + + struct AnimatedSvgView { + transformation: TimedTransformation, + renders: Rc>, + } + + impl Render for AnimatedSvgView { + fn render(&mut self, _window: &mut Window, _cx: &mut Context) -> impl IntoElement { + self.renders.set(self.renders.get() + 1); + div().child( + svg() + .data(SQUARE_SVG) + .size(px(16.)) + .text_color(red()) + .with_timed_transformation(self.transformation), + ) + } + } + + struct Pose { + rotation_scale: [[f32; 2]; 2], + center_offset: [f32; 2], + alpha: f32, + } + + /// Opens a window showing `transformation` and returns a function that + /// delivers a frame `advance` later and reports the animated sprite's pose, + /// along with the number of times the view has rendered. + fn animate( + transformation: TimedTransformation, + cx: &mut TestAppContext, + ) -> (impl FnMut(Duration) -> Pose, Rc>) { + let renders = Rc::new(Cell::new(0)); + let (_, cx) = cx.add_window_view({ + let renders = renders.clone(); + move |_, _| AnimatedSvgView { + transformation, + renders, + } + }); + cx.run_until_parked(); + let cx: &mut VisualTestContext = cx; + let pose_after = move |advance: Duration| { + cx.executor().advance_clock(advance); + cx.update(|window, cx| { + window.simulate_next_frame(cx); + window.advance_scene_animations(cx); + let sprite = window + .rendered_frame + .scene + .monochrome_sprites + .iter() + .find(|sprite| sprite.animation != SpriteAnimationId::NONE) + .expect("the SVG should be painted as an animated sprite"); + let center = sprite.bounds.center(); + let [[a, b], [c, d]] = sprite.transformation.rotation_scale; + let [x, y] = sprite.transformation.translation; + Pose { + rotation_scale: sprite.transformation.rotation_scale, + center_offset: [ + a * center.x.0 + b * center.y.0 + x - center.x.0, + c * center.x.0 + d * center.y.0 + y - center.y.0, + ], + alpha: sprite.color.a, + } + }) + }; + (pose_after, renders) + } + + #[crate::test] + fn test_rotation_advances_without_rerendering(cx: &mut TestAppContext) { + let (mut pose_after, renders) = animate( + TimedTransformation::rotation(Duration::from_secs(1), Transformation::default()), + cx, + ); + let renders_before_frames = renders.get(); + + for quarter in 0..4 { + let pose = pose_after(if quarter == 0 { + Duration::ZERO + } else { + Duration::from_millis(250) + }); + let (sin, cos) = (quarter as f32 * FRAC_PI_2).sin_cos(); + let expected = [[cos, -sin], [sin, cos]]; + for (actual, expected) in pose + .rotation_scale + .as_flattened() + .iter() + .zip(expected.as_flattened()) + { + assert!((actual - expected).abs() < 1e-5, "quarter {quarter}"); + } + assert!(pose.center_offset.iter().all(|offset| offset.abs() < 1e-3)); + } + assert_eq!(renders.get(), renders_before_frames); + } + + #[crate::test] + fn test_timed_transformation_eases_each_value_separately(cx: &mut TestAppContext) { + let (mut pose_after, renders) = animate( + TimedTransformation::new(Duration::from_secs(1)) + .from(Transformation::alpha(0.4)) + .to(Transformation::scale(size(1.5, 1.5)).with_alpha(0.)) + .with_scale_easing(Easing::EaseOutQuint), + cx, + ); + let renders_before_frames = renders.get(); + + let pose = pose_after(Duration::ZERO); + assert!((pose.rotation_scale[0][0] - 1.).abs() < 1e-5); + assert!((pose.alpha - 0.4).abs() < 1e-5); + + // Halfway through, the scale has eased most of the way out while the + // alpha has faded exactly half. + let pose = pose_after(Duration::from_millis(500)); + assert!((pose.rotation_scale[0][0] - (1. + 0.5 * (1. - 0.5f32.powi(5)))).abs() < 1e-5); + assert!((pose.alpha - 0.2).abs() < 1e-5); + assert_eq!(renders.get(), renders_before_frames); + } + + #[crate::test] + fn test_heartbeat_returns_to_its_start(cx: &mut TestAppContext) { + let (mut pose_after, _) = animate( + TimedTransformation::new(Duration::from_secs(1)) + .to(Transformation::scale(size(1.12, 1.12))) + .with_scale_easing(Easing::Heartbeat), + cx, + ); + + assert!((pose_after(Duration::ZERO).rotation_scale[0][0] - 1.).abs() < 1e-3); + assert!((pose_after(Duration::from_millis(200)).rotation_scale[0][0] - 1.12).abs() < 1e-3); + // Each call advances the clock further, to 400ms and then 999ms. + let second_beat = pose_after(Duration::from_millis(200)).rotation_scale[0][0]; + assert!(second_beat > 1.05 && second_beat < 1.09); + assert!((pose_after(Duration::from_millis(599)).rotation_scale[0][0] - 1.).abs() < 1e-3); + } + + #[crate::test] + fn test_scene_presents_as_often_as_its_least_capped_animation(cx: &mut TestAppContext) { + let spin = TimedTransformation::rotation(Duration::from_secs(1), Transformation::default()); + let (_, cx) = cx.add_window_view(move |_, _| CappedView { spin }); + cx.run_until_parked(); + cx.update(|window, _| { + assert_eq!( + window.rendered_frame.scene.animation_frame_interval(), + Some(Duration::from_millis(50)) + ); + }); + } + + struct CappedView { + spin: TimedTransformation, + } + + impl Render for CappedView { + fn render(&mut self, _window: &mut Window, _cx: &mut Context) -> impl IntoElement { + let icon = || svg().data(SQUARE_SVG).size(px(16.)).text_color(red()); + div() + .child(icon().with_timed_transformation(self.spin.with_max_fps(10.))) + .child(icon().with_timed_transformation(self.spin.with_max_fps(20.))) + .child(icon().with_transformation(Transformation::alpha(0.5))) + } + } +} diff --git a/crates/gpui/src/profiler/journal.rs b/crates/gpui/src/profiler/journal.rs index e5e8bc706b8..4c810f86b32 100644 --- a/crates/gpui/src/profiler/journal.rs +++ b/crates/gpui/src/profiler/journal.rs @@ -167,6 +167,8 @@ pub enum FrameSkipReason { ThermalFrameRateLimit, /// Low power mode deferred drawing. LowPowerFrameRateLimit, + /// A scene animation's frame rate cap deferred presenting. + AnimationFrameRateLimit, } /// A completed frame request that returned without drawing a new frame. diff --git a/crates/gpui/src/scene.rs b/crates/gpui/src/scene.rs index b28e25b7881..b2104e5402a 100644 --- a/crates/gpui/src/scene.rs +++ b/crates/gpui/src/scene.rs @@ -6,10 +6,13 @@ use serde::{Deserialize, Serialize}; use crate::{ AtlasTextureId, AtlasTile, Background, Bounds, ContentMask, Corners, Edges, Hsla, Path, - PathTiles, Pixels, Point, Radians, ScaledPixels, Size, bounds_tree::BoundsTree, + PathTiles, Pixels, Point, Radians, ScaledPixels, Size, TimedTransformation, + bounds_tree::BoundsTree, }; use smallvec::SmallVec; -use std::{collections::VecDeque, fmt::Debug, iter::Peekable, ops::Range, rc::Rc, slice}; +use std::{ + collections::VecDeque, fmt::Debug, iter::Peekable, ops::Range, rc::Rc, slice, time::Duration, +}; #[expect(missing_docs)] pub type DrawOrder = u32; @@ -57,6 +60,7 @@ pub struct Scene { pub subpixel_sprites: Vec, pub polychrome_sprites: Vec, pub surfaces: Vec, + animations: Vec, } #[expect(missing_docs)] @@ -74,6 +78,49 @@ impl Scene { self.subpixel_sprites.clear(); self.polychrome_sprites.clear(); self.surfaces.clear(); + self.animations.clear(); + } + + /// Inserts a sprite that [`Self::advance_animations`] keeps moving. The + /// sprite's color is taken as its color before the animation's alpha. + pub(crate) fn insert_animated_sprite( + &mut self, + mut sprite: MonochromeSprite, + mut animation: SpriteAnimation, + ) { + sprite.animation = SpriteAnimationId(self.animations.len() as u32); + animation.base_color = sprite.color; + if self.try_insert_primitive(sprite.into()) { + self.animations.push(animation); + } + } + + /// How long the window may wait between presents of this scene while only + /// its animations need a frame: `None` when nothing in it animates, and + /// zero when an animation wants every frame. + pub(crate) fn animation_frame_interval(&self) -> Option { + self.animations + .iter() + .map(|animation| { + animation + .transformation + .min_frame_interval() + .unwrap_or_default() + }) + .min() + } + + /// Moves every animated sprite to its pose at `elapsed` time on the app's + /// synced animation clock, without the scene being rebuilt. + pub(crate) fn advance_animations(&mut self, elapsed: Duration) { + for animation in &self.animations { + let Some(sprite) = self.monochrome_sprites.get_mut(animation.sprite_index) else { + continue; + }; + let pose = animation.transformation.at(elapsed); + sprite.transformation = pose.into_matrix(animation.center, animation.scale_factor); + sprite.color = animation.base_color.opacity(pose.alpha_factor()); + } } pub fn len(&self) -> usize { @@ -117,10 +164,14 @@ impl Scene { } pub fn insert_primitive(&mut self, primitive: impl Into) { - let primitive = primitive.into(); + self.try_insert_primitive(primitive.into()); + } + + /// Returns whether the primitive was kept, rather than clipped away. + fn try_insert_primitive(&mut self, primitive: Primitive) -> bool { let clipped_bounds = primitive.clipped_bounds(); if clipped_bounds.is_empty() { - return; + return false; } let kind = primitive.kind(); @@ -143,6 +194,7 @@ impl Scene { } self.paint_operations .push(PaintOperation::Primitive(primitive)); + true } fn push_primitive(&mut self, primitive: Primitive, order: DrawOrder) { @@ -175,7 +227,17 @@ impl Scene { pub fn replay(&mut self, range: Range, prev_scene: &Scene) { for operation in &prev_scene.paint_operations[range] { match operation { - PaintOperation::Primitive(primitive) => self.insert_primitive(primitive.clone()), + PaintOperation::Primitive(primitive) => { + // Animation ids index the scene they were inserted into. + if let Primitive::MonochromeSprite(sprite) = primitive + && let Some(animation) = + prev_scene.animations.get(sprite.animation.0 as usize) + { + self.insert_animated_sprite(*sprite, *animation); + } else { + self.insert_primitive(primitive.clone()); + } + } PaintOperation::StartLayer => self.push_layer(), PaintOperation::EndLayer => self.pop_layer(), } @@ -199,6 +261,15 @@ impl Scene { (sprite.order, sprite.tile.texture_id.index) }); self.surfaces.sort_by_key(|surface| surface.order); + + // Sorting moved the sprites, so animations learn where theirs ended up. + if !self.animations.is_empty() { + for (index, sprite) in self.monochrome_sprites.iter().enumerate() { + if let Some(animation) = self.animations.get_mut(sprite.animation.0 as usize) { + animation.sprite_index = index; + } + } + } } #[cfg_attr( @@ -871,7 +942,7 @@ impl Default for TransformationMatrix { #[expect(missing_docs)] pub struct MonochromeSprite { pub order: DrawOrder, - pub pad: u32, + pub animation: SpriteAnimationId, pub tile: AtlasTile, pub bounds: Bounds, pub content_mask: ContentMask, @@ -879,6 +950,52 @@ pub struct MonochromeSprite { pub transformation: TransformationMatrix, } +/// Refers to an animation of the scene a sprite is inserted into. +/// +/// A single `u32` so it fits the sprite's existing padding and leaves the +/// instance layout unchanged on every backend; renderers ignore it. +#[derive(Copy, Clone, Debug, PartialEq, Eq)] +#[repr(transparent)] +pub struct SpriteAnimationId(u32); + +impl SpriteAnimationId { + /// No animation. + pub const NONE: Self = Self(u32::MAX); +} + +impl Default for SpriteAnimationId { + fn default() -> Self { + Self::NONE + } +} + +/// A [`TimedTransformation`] the window applies to a sprite right before +/// every present, so the scene can be presented again without being redrawn. +#[derive(Copy, Clone, Debug)] +pub(crate) struct SpriteAnimation { + transformation: TimedTransformation, + center: Point, + scale_factor: f32, + base_color: Hsla, + sprite_index: usize, +} + +impl SpriteAnimation { + pub(crate) fn new( + transformation: TimedTransformation, + center: Point, + scale_factor: f32, + ) -> Self { + Self { + transformation, + center, + scale_factor, + base_color: Hsla::default(), + sprite_index: usize::MAX, + } + } +} + impl From for Primitive { fn from(sprite: MonochromeSprite) -> Self { Primitive::MonochromeSprite(sprite) diff --git a/crates/gpui/src/window.rs b/crates/gpui/src/window.rs index 12fd517f362..9432b5db092 100644 --- a/crates/gpui/src/window.rs +++ b/crates/gpui/src/window.rs @@ -19,12 +19,12 @@ use crate::{ Point, PolychromeSprite, Priority, PromptButton, PromptLevel, Quad, Render, RenderGlyphParams, RenderImage, RenderImageParams, RenderSvgParams, Replay, ResizeEdge, SMOOTH_SVG_SCALE_FACTOR, SUBPIXEL_VARIANTS_X, SUBPIXEL_VARIANTS_Y, ScaledPixels, Scene, Shadow, SharedString, Size, - StrikethroughStyle, Style, SubpixelSprite, Subscription, SystemWindowTab, - SystemWindowTabController, TabStopMap, Task, TextInputConfiguration, TextInputStateChange, - TextRenderingMode, TextStyle, TextStyleRefinement, ThermalState, TransformationMatrix, - Underline, UnderlineStyle, WindowAppearance, WindowBackgroundAppearance, WindowBounds, - WindowControls, WindowDecorations, WindowInsets, WindowOptions, WindowParams, WindowTextSystem, - WindowVisibility, point, prelude::*, px, rems, size, transparent_black, + SpriteAnimation, SpriteAnimationId, StrikethroughStyle, Style, SubpixelSprite, Subscription, + SystemWindowTab, SystemWindowTabController, TabStopMap, Task, TextInputConfiguration, + TextInputStateChange, TextRenderingMode, TextStyle, TextStyleRefinement, ThermalState, + TransformationMatrix, Underline, UnderlineStyle, WindowAppearance, WindowBackgroundAppearance, + WindowBounds, WindowControls, WindowDecorations, WindowInsets, WindowOptions, WindowParams, + WindowTextSystem, WindowVisibility, point, prelude::*, px, rems, size, transparent_black, }; use crate::gestures::{GestureTuning, RecognizedTouchGesture, TouchGestureRecognizer}; @@ -1287,6 +1287,9 @@ pub struct Window { SingleSubscriberSet bool>>, hovered: Rc>, pub(crate) needs_present: Rc>, + /// The rendered scene's [`Scene::animation_frame_interval`]. While it is + /// `Some`, the scene must keep being presented even when nothing is redrawn. + scene_animation_interval: Rc>>, /// Tracks recent input event timestamps to determine if input is arriving at a high rate. /// Used to selectively enable VRR optimization only when input rate exceeds 60fps. pub(crate) input_rate_tracker: Rc>, @@ -1736,6 +1739,7 @@ impl Window { profiler::journal::record_window_visibility(handle.window_id(), visibility); let hovered = Rc::new(Cell::new(platform_window.is_hovered())); let needs_present = Rc::new(Cell::new(false)); + let scene_animation_interval = Rc::new(Cell::new(None::)); let next_frame_callbacks: Rc>> = Default::default(); let input_rate_tracker = Rc::new(RefCell::new(InputRateTracker::default())); @@ -1901,6 +1905,7 @@ impl Window { let invalidator = invalidator.clone(); let active = active.clone(); let needs_present = needs_present.clone(); + let scene_animation_interval = scene_animation_interval.clone(); let next_frame_callbacks = next_frame_callbacks.clone(); let input_rate_tracker = input_rate_tracker.clone(); let mut deferred_force_render = false; @@ -1960,12 +1965,14 @@ impl Window { // underclocking, but subject to the same power limits as redraws. let high_rate_input = input_rate_tracker.borrow_mut().is_high_rate(); let has_next_frame_callbacks = !next_frame_callbacks.borrow().is_empty(); - let has_frame_demand = invalidator.is_dirty() + let has_demand_besides_animation = invalidator.is_dirty() || force_render || has_next_frame_callbacks || request_frame_options.require_presentation || needs_present.get() || high_rate_input; + let has_frame_demand = + has_demand_besides_animation || scene_animation_interval.get().is_some(); let should_throttle = !request_frame_options.require_presentation; let inactive_without_high_rate_input = @@ -1981,6 +1988,10 @@ impl Window { thermal_state, power_mode, ); + let animation_frame_interval = scene_animation_interval + .get() + .filter(|interval| !has_demand_besides_animation && !interval.is_zero()); + let min_frame_interval = min_frame_interval.max(animation_frame_interval); let now = Instant::now(); // Idle display-link ticks must neither consume a frame slot nor @@ -2007,7 +2018,11 @@ impl Window { profiler::journal::record_frame_skipped( window_id, Instant::now(), - if inactive_without_high_rate_input + if animation_frame_interval.is_some() + && animation_frame_interval == min_frame_interval + { + profiler::journal::FrameSkipReason::AnimationFrameRateLimit + } else if inactive_without_high_rate_input && inactive_frame_interval == min_frame_interval { profiler::journal::FrameSkipReason::InactiveFrameRateLimit @@ -2042,6 +2057,7 @@ impl Window { let should_draw = invalidator.is_dirty() || force_render; let needs_present = request_frame_options.require_presentation || needs_present.get() + || scene_animation_interval.get().is_some() || high_rate_input; if should_draw { measure("frame duration", || { @@ -2057,6 +2073,7 @@ impl Window { window.refresh(); } let arena_clear_needed = window.draw(cx); + window.advance_scene_animations(cx); window.present(); arena_clear_needed.clear(cx); }) @@ -2070,7 +2087,10 @@ impl Window { }) } else if needs_present { handle - .update(&mut cx, |_, window, _| window.present()) + .update(&mut cx, |_, window, cx| { + window.advance_scene_animations(cx); + window.present(); + }) .with_context(|| { format!("presenting frame for window {:?}", handle.window_id()) }) @@ -2081,6 +2101,7 @@ impl Window { .update(&mut cx, |_, window, _| { if window.invalidator.is_dirty() || !window.next_frame_callbacks.borrow().is_empty() + || window.scene_animation_interval.get().is_some() { window.platform_window.schedule_frame(); } @@ -2098,7 +2119,10 @@ impl Window { // after this frame (the window was re-invalidated mid-draw, or // animations scheduled next-frame callbacks), re-arm the frame // source explicitly. - if invalidator.is_dirty() || !next_frame_callbacks.borrow().is_empty() { + if invalidator.is_dirty() + || !next_frame_callbacks.borrow().is_empty() + || scene_animation_interval.get().is_some() + { invalidator.wake_platform(); } #[cfg(feature = "profiler")] @@ -2417,6 +2441,7 @@ impl Window { visibility_observers: SingleSubscriberSet::new(), hovered, needs_present, + scene_animation_interval, input_rate_tracker, #[cfg(feature = "profiler")] window_profiler: profiler::WindowProfiler::new(handle.window_id())?, @@ -3029,6 +3054,11 @@ impl Window { self.on_next_frame(move |_, cx| cx.notify(entity)); } + pub(crate) fn advance_scene_animations(&mut self, cx: &App) { + let elapsed = cx.background_executor().now() - cx.synced_animation_epoch; + self.rendered_frame.scene.advance_animations(elapsed); + } + /// Runs all callbacks scheduled via [`Self::on_next_frame`], returning how many ran. /// /// Tests have no platform frame loop, so this simulates the delivery of the @@ -3841,6 +3871,8 @@ impl Window { let previous_focus_path = self.rendered_frame.focus_path(); let previous_window_active = self.rendered_frame.window_active; mem::swap(&mut self.rendered_frame, &mut self.next_frame); + self.scene_animation_interval + .set(self.rendered_frame.scene.animation_frame_interval()); self.next_frame.clear(); let current_focus_path = self.rendered_frame.focus_path(); let current_window_active = self.rendered_frame.window_active; @@ -5268,7 +5300,7 @@ impl Window { } else { self.next_frame.scene.insert_primitive(MonochromeSprite { order: 0, - pad: 0, + animation: SpriteAnimationId::NONE, bounds, content_mask, color: color.opacity(element_opacity), @@ -5374,6 +5406,21 @@ impl Window { transformation: TransformationMatrix, color: Hsla, cx: &App, + ) -> Result<()> { + self.paint_animated_svg(bounds, path, data, transformation, None, color, cx) + } + + /// Like [`Self::paint_svg`], with an `animation` the window applies before every + /// present, so the view isn't re-rendered to advance it. + pub(crate) fn paint_animated_svg( + &mut self, + bounds: Bounds, + path: SharedString, + data: Option<&[u8]>, + transformation: TransformationMatrix, + animation: Option, + color: Hsla, + cx: &App, ) -> Result<()> { self.invalidator.debug_assert_paint(); @@ -5415,15 +5462,22 @@ impl Window { .map_origin(|value| ScaledPixels(round_half_toward_zero(value.0))) .map_size(|size| size.ceil()); - self.next_frame.scene.insert_primitive(MonochromeSprite { + let sprite = MonochromeSprite { order: 0, - pad: 0, + animation: SpriteAnimationId::NONE, bounds: final_bounds, content_mask, color: color.opacity(element_opacity), tile, transformation, - }); + }; + match animation { + Some(animation) => self + .next_frame + .scene + .insert_animated_sprite(sprite, animation), + None => self.next_frame.scene.insert_primitive(sprite), + } Ok(()) } diff --git a/crates/gpui_platform/benches/atlas_upload.rs b/crates/gpui_platform/benches/atlas_upload.rs index 8ede1a5bd5c..9ad76e2b041 100644 --- a/crates/gpui_platform/benches/atlas_upload.rs +++ b/crates/gpui_platform/benches/atlas_upload.rs @@ -224,7 +224,7 @@ fn tile_scene(tile: AtlasTile) -> Scene { match tile.texture_id.kind { AtlasTextureKind::Monochrome => scene.insert_primitive(MonochromeSprite { order: 0, - pad: 0, + animation: gpui::SpriteAnimationId::NONE, tile, bounds, content_mask, diff --git a/crates/gpui_platform/benches/primitives.rs b/crates/gpui_platform/benches/primitives.rs index f86866dd5f6..422dbd4bd71 100644 --- a/crates/gpui_platform/benches/primitives.rs +++ b/crates/gpui_platform/benches/primitives.rs @@ -345,7 +345,7 @@ fn insert_primitives(scene: &mut Scene, rectangles: &[Rectangle]) { + point(glyph_size * (glyph as f32 * 0.6), gpui::ScaledPixels(0.)); scene.insert_primitive(gpui::MonochromeSprite { order: 0, - pad: 0, + animation: gpui::SpriteAnimationId::NONE, tile: glyph_tile(index + glyph), bounds: Bounds::new(origin, size(glyph_size * 0.6, glyph_size)), content_mask, diff --git a/crates/ui/src/components/button/button.rs b/crates/ui/src/components/button/button.rs index ac324cdc310..f1da86caa22 100644 --- a/crates/ui/src/components/button/button.rs +++ b/crates/ui/src/components/button/button.rs @@ -472,7 +472,6 @@ impl RenderOnce for Button { } else { self.label_color.unwrap_or_default() }; - let loading_icon_id = (self.base.id().clone(), "loading"); let wrapped_key_binding = if wrap_key_binding { self.key_binding.take() } else { @@ -489,7 +488,7 @@ impl RenderOnce for Button { Icon::new(IconName::LoadCircle) .size(IconSize::Small) .color(Color::Muted) - .with_keyed_rotate_animation(loading_icon_id, 2), + .with_rotate_animation(2), ) }, |this| { diff --git a/crates/ui/src/components/icon.rs b/crates/ui/src/components/icon.rs index bc4c134b117..a4c3085cc53 100644 --- a/crates/ui/src/components/icon.rs +++ b/crates/ui/src/components/icon.rs @@ -3,11 +3,12 @@ mod icon_decoration; use std::path::{Path, PathBuf}; use std::sync::Arc; +use std::time::Duration; pub use decorated_icon::*; use gpui::{ AnimationElement, AnyElement, Hsla, ImgResourceLoader, IntoElement, Rems, Resource, - Transformation, img, svg, + TimedTransformation, Transformation, img, svg, }; pub use icon_decoration::*; pub use icons::*; @@ -151,6 +152,7 @@ pub struct Icon { group_hover_color: Option, size: Rems, transformation: Transformation, + rotation_period: Option, } impl Icon { @@ -161,6 +163,7 @@ impl Icon { group_hover_color: None, size: IconSize::default().rems(), transformation: Transformation::default(), + rotation_period: None, } } @@ -180,6 +183,7 @@ impl Icon { group_hover_color: None, size: IconSize::default().rems(), transformation: Transformation::default(), + rotation_period: None, } } @@ -190,6 +194,7 @@ impl Icon { group_hover_color: None, size: IconSize::default().rems(), transformation: Transformation::default(), + rotation_period: None, } } @@ -232,6 +237,12 @@ impl Transformable for Icon { self.transformation = transformation; self } + + /// Has no effect on icons loaded from raster image files. + fn animate_rotation(mut self, period: Duration) -> Self { + self.rotation_period = Some(period); + self + } } impl RenderOnce for Icon { @@ -251,6 +262,12 @@ impl RenderOnce for Icon { let group_hover_color = self.group_hover_color.map(|color| color.color(cx)); svg.with_transformation(self.transformation) + .when_some(self.rotation_period, |svg, period| { + svg.with_timed_transformation(TimedTransformation::rotation( + period, + self.transformation, + )) + }) .size(self.size) .flex_none() .text_color(color) diff --git a/crates/ui/src/components/image.rs b/crates/ui/src/components/image.rs index 8143e0ace58..684b6454999 100644 --- a/crates/ui/src/components/image.rs +++ b/crates/ui/src/components/image.rs @@ -1,7 +1,8 @@ use std::sync::Arc; +use std::time::Duration; -use gpui::Transformation; use gpui::{App, IntoElement, Rems, RenderOnce, Size, Styled, Window, svg}; +use gpui::{TimedTransformation, Transformation}; use serde::{Deserialize, Serialize}; use strum::{EnumIter, EnumString, IntoStaticStr}; @@ -42,6 +43,7 @@ pub struct Vector { color: Color, size: Size, transformation: Transformation, + rotation_period: Option, } impl Vector { @@ -52,6 +54,7 @@ impl Vector { color: Color::default(), size: Size { width, height }, transformation: Transformation::default(), + rotation_period: None, } } @@ -79,6 +82,11 @@ impl Transformable for Vector { self.transformation = transformation; self } + + fn animate_rotation(mut self, period: Duration) -> Self { + self.rotation_period = Some(period); + self + } } impl RenderOnce for Vector { @@ -95,6 +103,12 @@ impl RenderOnce for Vector { .path(self.path) .text_color(self.color.color(cx)) .with_transformation(self.transformation) + .when_some(self.rotation_period, |svg, period| { + svg.with_timed_transformation(TimedTransformation::rotation( + period, + self.transformation, + )) + }) } } diff --git a/crates/ui/src/traits/animation_ext.rs b/crates/ui/src/traits/animation_ext.rs index 64cdd4f9c9a..900cb018bcd 100644 --- a/crates/ui/src/traits/animation_ext.rs +++ b/crates/ui/src/traits/animation_ext.rs @@ -1,42 +1,15 @@ use std::time::Duration; -use gpui::{Animation, AnimationElement, AnimationExt, Transformation, percentage}; - -use crate::{prelude::*, traits::transformable::Transformable}; +use crate::traits::transformable::Transformable; /// An extension trait for adding common animations to animatable components. -pub trait CommonAnimationExt: AnimationExt { - /// Render this component as rotating over the given duration. +pub trait CommonAnimationExt: Transformable + Sized { + /// Render this component as rotating, one full turn every `period` seconds. /// - /// NOTE: This method uses the location of the caller to generate an ID for this state. - /// If this is not sufficient to identify your state (e.g. you're rendering a list item), - /// you can provide a custom ElementID using the `use_keyed_rotate_animation` method. - #[track_caller] - fn with_rotate_animation(self, duration: u64) -> AnimationElement - where - Self: Transformable + Sized, - { - self.with_keyed_rotate_animation( - ElementId::CodeLocation(*std::panic::Location::caller()), - duration, - ) - } - - /// Render this component as rotating with the given element ID over the given duration. - fn with_keyed_rotate_animation( - self, - id: impl Into, - duration: u64, - ) -> AnimationElement - where - Self: Transformable + Sized, - { - self.with_animation( - id, - Animation::new(Duration::from_secs(duration)).repeat_synced(), - |component, delta| component.transform(Transformation::rotate(percentage(delta))), - ) + /// The view isn't re-rendered to advance the rotation. All spinners share one phase. + fn with_rotate_animation(self, period: u64) -> Self { + self.animate_rotation(Duration::from_secs(period)) } } -impl CommonAnimationExt for T {} +impl CommonAnimationExt for T {} diff --git a/crates/ui/src/traits/transformable.rs b/crates/ui/src/traits/transformable.rs index f52141f304d..262931e7006 100644 --- a/crates/ui/src/traits/transformable.rs +++ b/crates/ui/src/traits/transformable.rs @@ -1,7 +1,13 @@ +use std::time::Duration; + use gpui::Transformation; /// A trait for components that can be transformed. pub trait Transformable { /// Sets the transformation for the element. fn transform(self, transformation: Transformation) -> Self; + + /// Rotates the element continuously, one full turn per `period`, using + /// [`gpui::TimedTransformation::rotation`]. + fn animate_rotation(self, period: Duration) -> Self; }