mirror of
https://github.com/zed-industries/zed.git
synced 2026-11-19 06:59:22 +01:00
gpui: Animate SVG transformations without re-rendering views (#66896)
## Summary Ref #21146, #23479, #51597 One common problem that I've been working towards fixing by adding a retained mode is Zed's high battery usage, caused by invalidating clean entities because a single ancestor is dirty. While looking closer into this problem I realized that a ton of the invalidations we run into are due to animations, which can be fixed separately from retained mode. My solution is adding a `TimedTransformation` struct and a new animation API that uses it. ```rust // A spinner: one full turn every two seconds. svg() .path("icons/load_circle.svg") .with_timed_transformation(TimedTransformation::rotation( Duration::from_secs(2), Transformation::default(), )) // A pulsing ring: grows to 1.5x while fading out, each value with its own easing. svg() .path("icons/ring.svg") .with_timed_transformation( TimedTransformation::new(Duration::from_millis(1750)) .from(Transformation::alpha(0.6)) .to(Transformation::scale(size(1.5, 1.5)).with_alpha(0.)) .with_scale_easing(Easing::EaseOutQuint), ) ``` Because most of our animations are an SVG sprite with simple matrix operations applied to it, such as rotation, alpha changes and size changes, that change based on elapsed time, we can avoid invalidating the view by extracting the before and after transformations and deriving a function that takes elapsed time and computes what the animated sprite should look like. The extracted function lives in a table on the scene, and each animated sprite points at its entry. This lets GPUI advance animations right before presenting a frame, without dirtying the view or recomputing the scene from scratch. This should save a lot of CPU usage and battery life for end users of GPUI apps that use animations. `Icon` and `Vector` in `ui` now use this for `with_rotate_animation`, so Zed's existing spinners get it with no call site changes. With reduced motion on, the SVG is drawn at its starting transformation and nothing animates. ### Results Main-thread CPU instructions for one animated frame, from a headless benchmark on macOS with the Metal renderer (not included in this PR): | | 200 animated SVGs | 60 rows of text + 5 spinners | |---|---|---| | Re-render with `with_animation` | 6.07 M | 7.34 M | | `with_timed_transformation` | 162 K | 100 K | | Improvement | 37x | 73x | The `svg_animation` example (`cargo run --release -p gpui --example svg_animation`, 200 animated SVGs in a window, Apple M4 Max), as reported by `top`: | | CPU | Energy impact | |---|---|---| | Re-render with `with_animation` | 21% | 21.5 | | `with_timed_transformation` | 6% | 7.5 | | `with_timed_transformation`, capped at 15 fps | 1.9% | 3.0 | That is about 3.5x less CPU and 3x less energy impact uncapped, and about 11x less CPU and 7x less energy impact with the cap. ### Follow ups - Allow animating more primitives, such as glyphs, instead of only SVG sprites - Lower the fixed cost of presenting a frame, which is most of what remains after this change - Retained layers, so a whole subtree can be moved or faded without re-rendering Release Notes: - Improved battery life by animating spinners without re-rendering the views that contain them - [GPUI] Added `TimedTransformation` and `Svg::with_timed_transformation` to animate SVGs without re-rendering a view
This commit is contained in:
@@ -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 <n>` 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#"<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 16 16"><circle cx="8" cy="8" r="5" fill="none" stroke="black" stroke-width="1.5"/></svg>"#;
|
||||
|
||||
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<f32>,
|
||||
render_count: Cell<u64>,
|
||||
}
|
||||
|
||||
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<Self>) -> 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();
|
||||
}
|
||||
@@ -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| {
|
||||
|
||||
+454
-20
@@ -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>,
|
||||
transformation: Option<TimedTransformation>,
|
||||
path: Option<SharedString>,
|
||||
external_path: Option<SharedString>,
|
||||
data: Option<Arc<[u8]>>,
|
||||
@@ -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<f32>,
|
||||
translate: Point<Pixels>,
|
||||
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<f32>) -> 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<Pixels>) -> 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<Radians>) -> 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<f32>) -> Self {
|
||||
self.scale = scale;
|
||||
@@ -266,7 +322,11 @@ impl Transformation {
|
||||
self
|
||||
}
|
||||
|
||||
fn into_matrix(self, center: Point<Pixels>, scale_factor: f32) -> TransformationMatrix {
|
||||
pub(crate) fn into_matrix(
|
||||
self,
|
||||
center: Point<Pixels>,
|
||||
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<Duration>,
|
||||
}
|
||||
|
||||
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<Duration> {
|
||||
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<Transformation> 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#"<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16"><rect width="8" height="16"/></svg>"#;
|
||||
|
||||
struct AnimatedSvgView {
|
||||
transformation: TimedTransformation,
|
||||
renders: Rc<Cell<usize>>,
|
||||
}
|
||||
|
||||
impl Render for AnimatedSvgView {
|
||||
fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> 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<Cell<usize>>) {
|
||||
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<Self>) -> 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)))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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.
|
||||
|
||||
+123
-6
@@ -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<SubpixelSprite>,
|
||||
pub polychrome_sprites: Vec<PolychromeSprite>,
|
||||
pub surfaces: Vec<PaintSurface>,
|
||||
animations: Vec<SpriteAnimation>,
|
||||
}
|
||||
|
||||
#[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<Duration> {
|
||||
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<Primitive>) {
|
||||
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<usize>, 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<ScaledPixels>,
|
||||
pub content_mask: ContentMask<ScaledPixels>,
|
||||
@@ -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<Pixels>,
|
||||
scale_factor: f32,
|
||||
base_color: Hsla,
|
||||
sprite_index: usize,
|
||||
}
|
||||
|
||||
impl SpriteAnimation {
|
||||
pub(crate) fn new(
|
||||
transformation: TimedTransformation,
|
||||
center: Point<Pixels>,
|
||||
scale_factor: f32,
|
||||
) -> Self {
|
||||
Self {
|
||||
transformation,
|
||||
center,
|
||||
scale_factor,
|
||||
base_color: Hsla::default(),
|
||||
sprite_index: usize::MAX,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<MonochromeSprite> for Primitive {
|
||||
fn from(sprite: MonochromeSprite) -> Self {
|
||||
Primitive::MonochromeSprite(sprite)
|
||||
|
||||
+68
-14
@@ -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<Box<dyn FnMut(WindowVisibility, &mut Window, &mut App) -> bool>>,
|
||||
hovered: Rc<Cell<bool>>,
|
||||
pub(crate) needs_present: Rc<Cell<bool>>,
|
||||
/// 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<Cell<Option<Duration>>>,
|
||||
/// 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<RefCell<InputRateTracker>>,
|
||||
@@ -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::<Duration>));
|
||||
let next_frame_callbacks: Rc<RefCell<Vec<FrameCallback>>> = 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<Pixels>,
|
||||
path: SharedString,
|
||||
data: Option<&[u8]>,
|
||||
transformation: TransformationMatrix,
|
||||
animation: Option<SpriteAnimation>,
|
||||
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(())
|
||||
}
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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| {
|
||||
|
||||
@@ -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<Color>,
|
||||
size: Rems,
|
||||
transformation: Transformation,
|
||||
rotation_period: Option<Duration>,
|
||||
}
|
||||
|
||||
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)
|
||||
|
||||
@@ -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<Rems>,
|
||||
transformation: Transformation,
|
||||
rotation_period: Option<Duration>,
|
||||
}
|
||||
|
||||
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,
|
||||
))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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<Self>
|
||||
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<ElementId>,
|
||||
duration: u64,
|
||||
) -> AnimationElement<Self>
|
||||
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<T: AnimationExt> CommonAnimationExt for T {}
|
||||
impl<T: Transformable> CommonAnimationExt for T {}
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user