forge
Explore
Log in

Don't you dare go Hollow

Implement spring animations

Browse files at this commit

ae89b2e514fd4c22a38c2dce258707c369ca944aIvan MolodetskikhParent: 732f7f6
niri-config/src/lib.rsmodified+310 -21
@@ -527,50 +527,95 @@ impl Default for Animations {
527 }527 }
528 }528 }
529 529
530-#[derive(knuffel::Decode, Debug, Clone, Copy, PartialEq)]530+#[derive(Debug, Clone, Copy, PartialEq)]
531 pub struct Animation {531 pub struct Animation {
532- #[knuffel(child)]
533 pub off: bool,532 pub off: bool,
534- #[knuffel(child, unwrap(argument))]533+ pub kind: AnimationKind,
535- pub duration_ms: Option<u32>,
536- #[knuffel(child, unwrap(argument))]
537- pub curve: Option<AnimationCurve>,
538 }534 }
539 535
540 impl Animation {536 impl Animation {
541 pub const fn unfilled() -> Self {537 pub const fn unfilled() -> Self {
542 Self {538 Self {
543 off: false,539 off: false,
544- duration_ms: None,540+ kind: AnimationKind::Easing(EasingParams::unfilled()),
545- curve: None,
546 }541 }
547 }542 }
548 543
549 pub const fn default() -> Self {544 pub const fn default() -> Self {
550 Self {545 Self {
551 off: false,546 off: false,
552- duration_ms: Some(250),547+ kind: AnimationKind::Easing(EasingParams::default()),
553- curve: Some(AnimationCurve::EaseOutCubic),
554 }548 }
555 }549 }
556 550
557 pub const fn default_workspace_switch() -> Self {551 pub const fn default_workspace_switch() -> Self {
558- Self::default()552+ Self {
553+ off: false,
554+ kind: AnimationKind::Spring(SpringParams {
555+ damping_ratio: 1.,
556+ stiffness: 1000,
557+ epsilon: 0.0001,
558+ }),
559+ }
559 }560 }
560 561
561 pub const fn default_horizontal_view_movement() -> Self {562 pub const fn default_horizontal_view_movement() -> Self {
562- Self::default()563+ Self {
564+ off: false,
565+ kind: AnimationKind::Spring(SpringParams {
566+ damping_ratio: 1.,
567+ stiffness: 800,
568+ epsilon: 0.0001,
569+ }),
570+ }
563 }571 }
564 572
565 pub const fn default_config_notification_open_close() -> Self {573 pub const fn default_config_notification_open_close() -> Self {
566- Self::default()574+ Self {
575+ off: false,
576+ kind: AnimationKind::Spring(SpringParams {
577+ damping_ratio: 0.6,
578+ stiffness: 1000,
579+ epsilon: 0.001,
580+ }),
581+ }
567 }582 }
568 583
569 pub const fn default_window_open() -> Self {584 pub const fn default_window_open() -> Self {
570 Self {585 Self {
571- duration_ms: Some(150),586+ off: false,
572- curve: Some(AnimationCurve::EaseOutExpo),587+ kind: AnimationKind::Easing(EasingParams {
573- ..Self::default()588+ duration_ms: Some(150),
589+ curve: Some(AnimationCurve::EaseOutExpo),
590+ }),
591+ }
592+ }
593+}
594+
595+#[derive(Debug, Clone, Copy, PartialEq)]
596+pub enum AnimationKind {
597+ Easing(EasingParams),
598+ Spring(SpringParams),
599+}
600+
601+#[derive(Debug, Clone, Copy, PartialEq)]
602+pub struct EasingParams {
603+ pub duration_ms: Option<u32>,
604+ pub curve: Option<AnimationCurve>,
605+}
606+
607+impl EasingParams {
608+ pub const fn unfilled() -> Self {
609+ Self {
610+ duration_ms: None,
611+ curve: None,
612+ }
613+ }
614+
615+ pub const fn default() -> Self {
616+ Self {
617+ duration_ms: Some(250),
618+ curve: Some(AnimationCurve::EaseOutCubic),
574 }619 }
575 }620 }
576 }621 }
@@ -581,6 +626,13 @@ pub enum AnimationCurve {
581 EaseOutExpo,626 EaseOutExpo,
582 }627 }
583 628
629+#[derive(Debug, Clone, Copy, PartialEq)]
630+pub struct SpringParams {
631+ pub damping_ratio: f64,
632+ pub stiffness: u32,
633+ pub epsilon: f64,
634+}
635+
584 #[derive(knuffel::Decode, Debug, Default, Clone, PartialEq, Eq)]636 #[derive(knuffel::Decode, Debug, Default, Clone, PartialEq, Eq)]
585 pub struct Environment(#[knuffel(children)] pub Vec<EnvironmentVariable>);637 pub struct Environment(#[knuffel(children)] pub Vec<EnvironmentVariable>);
586 638
@@ -1012,6 +1064,229 @@ where
1012 }1064 }
1013 }1065 }
1014 1066
1067+fn parse_arg_node<S: knuffel::traits::ErrorSpan, T: knuffel::traits::DecodeScalar<S>>(
1068+ name: &str,
1069+ node: &knuffel::ast::SpannedNode<S>,
1070+ ctx: &mut knuffel::decode::Context<S>,
1071+) -> Result<T, DecodeError<S>> {
1072+ let mut iter_args = node.arguments.iter();
1073+ let val = iter_args.next().ok_or_else(|| {
1074+ DecodeError::missing(node, format!("additional argument `{name}` is required"))
1075+ })?;
1076+
1077+ let value = knuffel::traits::DecodeScalar::decode(val, ctx)?;
1078+
1079+ if let Some(val) = iter_args.next() {
1080+ ctx.emit_error(DecodeError::unexpected(
1081+ &val.literal,
1082+ "argument",
1083+ "unexpected argument",
1084+ ));
1085+ }
1086+ for name in node.properties.keys() {
1087+ ctx.emit_error(DecodeError::unexpected(
1088+ name,
1089+ "property",
1090+ format!("unexpected property `{}`", name.escape_default()),
1091+ ));
1092+ }
1093+ for child in node.children() {
1094+ ctx.emit_error(DecodeError::unexpected(
1095+ child,
1096+ "node",
1097+ format!("unexpected node `{}`", child.node_name.escape_default()),
1098+ ));
1099+ }
1100+
1101+ Ok(value)
1102+}
1103+
1104+impl<S> knuffel::Decode<S> for Animation
1105+where
1106+ S: knuffel::traits::ErrorSpan,
1107+{
1108+ fn decode_node(
1109+ node: &knuffel::ast::SpannedNode<S>,
1110+ ctx: &mut knuffel::decode::Context<S>,
1111+ ) -> Result<Self, DecodeError<S>> {
1112+ expect_only_children(node, ctx);
1113+
1114+ let mut off = false;
1115+ let mut easing_params = EasingParams::unfilled();
1116+ let mut spring_params = None;
1117+
1118+ for child in node.children() {
1119+ match &**child.node_name {
1120+ "off" => {
1121+ knuffel::decode::check_flag_node(child, ctx);
1122+ if off {
1123+ ctx.emit_error(DecodeError::unexpected(
1124+ &child.node_name,
1125+ "node",
1126+ "duplicate node `off`, single node expected",
1127+ ));
1128+ } else {
1129+ off = true;
1130+ }
1131+ }
1132+ "spring" => {
1133+ if easing_params != EasingParams::unfilled() {
1134+ ctx.emit_error(DecodeError::unexpected(
1135+ child,
1136+ "node",
1137+ "cannot set both spring and easing parameters at once",
1138+ ));
1139+ }
1140+ if spring_params.is_some() {
1141+ ctx.emit_error(DecodeError::unexpected(
1142+ &child.node_name,
1143+ "node",
1144+ "duplicate node `spring`, single node expected",
1145+ ));
1146+ }
1147+
1148+ spring_params = Some(SpringParams::decode_node(child, ctx)?);
1149+ }
1150+ "duration-ms" => {
1151+ if spring_params.is_some() {
1152+ ctx.emit_error(DecodeError::unexpected(
1153+ child,
1154+ "node",
1155+ "cannot set both spring and easing parameters at once",
1156+ ));
1157+ }
1158+ if easing_params.duration_ms.is_some() {
1159+ ctx.emit_error(DecodeError::unexpected(
1160+ &child.node_name,
1161+ "node",
1162+ "duplicate node `duration-ms`, single node expected",
1163+ ));
1164+ }
1165+
1166+ easing_params.duration_ms = Some(parse_arg_node("duration-ms", child, ctx)?);
1167+ }
1168+ "curve" => {
1169+ if spring_params.is_some() {
1170+ ctx.emit_error(DecodeError::unexpected(
1171+ child,
1172+ "node",
1173+ "cannot set both spring and easing parameters at once",
1174+ ));
1175+ }
1176+ if easing_params.curve.is_some() {
1177+ ctx.emit_error(DecodeError::unexpected(
1178+ &child.node_name,
1179+ "node",
1180+ "duplicate node `curve`, single node expected",
1181+ ));
1182+ }
1183+
1184+ easing_params.curve = Some(parse_arg_node("curve", child, ctx)?);
1185+ }
1186+ name_str => {
1187+ ctx.emit_error(DecodeError::unexpected(
1188+ child,
1189+ "node",
1190+ format!("unexpected node `{}`", name_str.escape_default()),
1191+ ));
1192+ }
1193+ }
1194+ }
1195+
1196+ let kind = if let Some(spring_params) = spring_params {
1197+ AnimationKind::Spring(spring_params)
1198+ } else {
1199+ AnimationKind::Easing(easing_params)
1200+ };
1201+
1202+ Ok(Self { off, kind })
1203+ }
1204+}
1205+
1206+impl<S> knuffel::Decode<S> for SpringParams
1207+where
1208+ S: knuffel::traits::ErrorSpan,
1209+{
1210+ fn decode_node(
1211+ node: &knuffel::ast::SpannedNode<S>,
1212+ ctx: &mut knuffel::decode::Context<S>,
1213+ ) -> Result<Self, DecodeError<S>> {
1214+ if let Some(type_name) = &node.type_name {
1215+ ctx.emit_error(DecodeError::unexpected(
1216+ type_name,
1217+ "type name",
1218+ "no type name expected for this node",
1219+ ));
1220+ }
1221+ if let Some(val) = node.arguments.first() {
1222+ ctx.emit_error(DecodeError::unexpected(
1223+ &val.literal,
1224+ "argument",
1225+ "unexpected argument",
1226+ ));
1227+ }
1228+ for child in node.children() {
1229+ ctx.emit_error(DecodeError::unexpected(
1230+ child,
1231+ "node",
1232+ format!("unexpected node `{}`", child.node_name.escape_default()),
1233+ ));
1234+ }
1235+
1236+ let mut damping_ratio = None;
1237+ let mut stiffness = None;
1238+ let mut epsilon = None;
1239+ for (name, val) in &node.properties {
1240+ match &***name {
1241+ "damping-ratio" => {
1242+ damping_ratio = Some(knuffel::traits::DecodeScalar::decode(val, ctx)?);
1243+ }
1244+ "stiffness" => {
1245+ stiffness = Some(knuffel::traits::DecodeScalar::decode(val, ctx)?);
1246+ }
1247+ "epsilon" => {
1248+ epsilon = Some(knuffel::traits::DecodeScalar::decode(val, ctx)?);
1249+ }
1250+ name_str => {
1251+ ctx.emit_error(DecodeError::unexpected(
1252+ name,
1253+ "property",
1254+ format!("unexpected property `{}`", name_str.escape_default()),
1255+ ));
1256+ }
1257+ }
1258+ }
1259+ let damping_ratio = damping_ratio
1260+ .ok_or_else(|| DecodeError::missing(node, "property `damping-ratio` is required"))?;
1261+ let stiffness = stiffness
1262+ .ok_or_else(|| DecodeError::missing(node, "property `stiffness` is required"))?;
1263+ let epsilon =
1264+ epsilon.ok_or_else(|| DecodeError::missing(node, "property `epsilon` is required"))?;
1265+
1266+ if !(0.1..=10.).contains(&damping_ratio) {
1267+ ctx.emit_error(DecodeError::conversion(
1268+ node,
1269+ "damping-ratio must be between 0.1 and 10.0",
1270+ ));
1271+ }
1272+ if stiffness < 1 {
1273+ ctx.emit_error(DecodeError::conversion(node, "stiffness must be >= 1"));
1274+ }
1275+ if !(0.00001..=0.1).contains(&epsilon) {
1276+ ctx.emit_error(DecodeError::conversion(
1277+ node,
1278+ "epsilon must be between 0.00001 and 0.1",
1279+ ));
1280+ }
1281+
1282+ Ok(SpringParams {
1283+ damping_ratio,
1284+ stiffness,
1285+ epsilon,
1286+ })
1287+ }
1288+}
1289+
1015 impl<S> knuffel::Decode<S> for Binds1290 impl<S> knuffel::Decode<S> for Binds
1016 where1291 where
1017 S: knuffel::traits::ErrorSpan,1292 S: knuffel::traits::ErrorSpan,
@@ -1345,12 +1620,16 @@ mod tests {
1345 animations {1620 animations {
1346 slowdown 2.01621 slowdown 2.0
1347 1622
1348- workspace-switch { off; }1623+ workspace-switch {
1624+ spring damping-ratio=1.0 stiffness=1000 epsilon=0.0001
1625+ }
1349 1626
1350 horizontal-view-movement {1627 horizontal-view-movement {
1351 duration-ms 1001628 duration-ms 100
1352 curve "ease-out-expo"1629 curve "ease-out-expo"
1353 }1630 }
1631+
1632+ window-open { off; }
1354 }1633 }
1355 1634
1356 environment {1635 environment {
@@ -1507,12 +1786,22 @@ mod tests {
1507 animations: Animations {1786 animations: Animations {
1508 slowdown: 2.,1787 slowdown: 2.,
1509 workspace_switch: Animation {1788 workspace_switch: Animation {
1510- off: true,1789+ off: false,
1511- ..Animation::unfilled()1790+ kind: AnimationKind::Spring(SpringParams {
1791+ damping_ratio: 1.,
1792+ stiffness: 1000,
1793+ epsilon: 0.0001,
1794+ }),
1512 },1795 },
1513 horizontal_view_movement: Animation {1796 horizontal_view_movement: Animation {
1514- duration_ms: Some(100),1797+ off: false,
1515- curve: Some(AnimationCurve::EaseOutExpo),1798+ kind: AnimationKind::Easing(EasingParams {
1799+ duration_ms: Some(100),
1800+ curve: Some(AnimationCurve::EaseOutExpo),
1801+ }),
1802+ },
1803+ window_open: Animation {
1804+ off: true,
1516 ..Animation::unfilled()1805 ..Animation::unfilled()
1517 },1806 },
1518 ..Default::default()1807 ..Default::default()
resources/default-config.kdlmodified+35 -7
@@ -254,18 +254,48 @@ animations {
254 // slowdown 3.0254 // slowdown 3.0
255 255
256 // You can configure all individual animations.256 // You can configure all individual animations.
257- // Available settings are the same for all of them:257+ // Available settings are the same for all of them.
258 // - off disables the animation.258 // - off disables the animation.
259+ //
260+ // Niri supports two animation types: easing and spring.
261+ //
262+ // Easing has the following settings:
259 // - duration-ms sets the duration of the animation in milliseconds.263 // - duration-ms sets the duration of the animation in milliseconds.
260 // - curve sets the easing curve. Currently, available curves264 // - curve sets the easing curve. Currently, available curves
261 // are "ease-out-cubic" and "ease-out-expo".265 // are "ease-out-cubic" and "ease-out-expo".
266+ //
267+ // Spring animations work better with touchpad gestures, because they
268+ // take into account the velocity of your fingers as you release the swipe.
269+ // The parameters are less obvious and generally should be tuned
270+ // with trial and error. Notably, you cannot directly set the duration.
271+ // You can use this app to help visualize how the spring parameters
272+ // change the animation: https://flathub.org/apps/app.drey.Elastic
273+ //
274+ // A spring animation is configured like this:
275+ // - spring damping-ratio=1.0 stiffness=1000 epsilon=0.0001
276+ //
277+ // The damping ratio goes from 0.1 to 10.0 and has the following properties:
278+ // - below 1.0: underdamped spring, will oscillate in the end.
279+ // - above 1.0: overdamped spring, won't oscillate.
280+ // - 1.0: critically damped spring, comes to rest in minimum possible time
281+ // without oscillations.
282+ //
283+ // However, even with damping ratio = 1.0 the spring animation may oscillate
284+ // if "launched" with enough velocity from a touchpad swipe.
285+ //
286+ // Lower stiffness will result in a slower animation more prone to oscillation.
287+ //
288+ // Set epsilon to a lower value if the animation "jumps" in the end.
289+ //
290+ // The spring mass is hardcoded to 1.0 and cannot be changed. Instead, change
291+ // stiffness proportionally. E.g. increasing mass by 2x is the same as
292+ // decreasing stiffness by 2x.
262 293
263 // Animation when switching workspaces up and down,294 // Animation when switching workspaces up and down,
264 // including after the touchpad gesture.295 // including after the touchpad gesture.
265 workspace-switch {296 workspace-switch {
266 // off297 // off
267- // duration-ms 250298+ // spring damping-ratio=1.0 stiffness=1000 epsilon=0.0001
268- // curve "ease-out-cubic"
269 }299 }
270 300
271 // All horizontal camera view movement:301 // All horizontal camera view movement:
@@ -275,8 +305,7 @@ animations {
275 // - And so on.305 // - And so on.
276 horizontal-view-movement {306 horizontal-view-movement {
277 // off307 // off
278- // duration-ms 250308+ // spring damping-ratio=1.0 stiffness=800 epsilon=0.0001
279- // curve "ease-out-cubic"
280 }309 }
281 310
282 // Window opening animation. Note that this one has different defaults.311 // Window opening animation. Note that this one has different defaults.
@@ -290,8 +319,7 @@ animations {
290 // open/close animation.319 // open/close animation.
291 config-notification-open-close {320 config-notification-open-close {
292 // off321 // off
293- // duration-ms 250322+ // spring damping-ratio=0.6 stiffness=1000 epsilon=0.001
294- // curve "ease-out-cubic"
295 }323 }
296 }324 }
297 325
src/animation/mod.rsmodified+140 -11
@@ -6,6 +6,9 @@ use portable_atomic::{AtomicF64, Ordering};
6 6
7 use crate::utils::get_monotonic_time;7 use crate::utils::get_monotonic_time;
8 8
9+mod spring;
10+pub use spring::{Spring, SpringParams};
11+
9 pub static ANIMATION_SLOWDOWN: AtomicF64 = AtomicF64::new(1.);12 pub static ANIMATION_SLOWDOWN: AtomicF64 = AtomicF64::new(1.);
10 13
11 #[derive(Debug)]14 #[derive(Debug)]
@@ -15,7 +18,19 @@ pub struct Animation {
15 duration: Duration,18 duration: Duration,
16 start_time: Duration,19 start_time: Duration,
17 current_time: Duration,20 current_time: Duration,
18- curve: Curve,21+ kind: Kind,
22+}
23+
24+#[derive(Debug, Clone, Copy)]
25+enum Kind {
26+ Easing {
27+ curve: Curve,
28+ },
29+ Spring(Spring),
30+ Deceleration {
31+ initial_velocity: f64,
32+ deceleration_rate: f64,
33+ },
19 }34 }
20 35
21 #[derive(Debug, Clone, Copy)]36 #[derive(Debug, Clone, Copy)]
@@ -28,21 +43,116 @@ impl Animation {
28 pub fn new(43 pub fn new(
29 from: f64,44 from: f64,
30 to: f64,45 to: f64,
46+ initial_velocity: f64,
31 config: niri_config::Animation,47 config: niri_config::Animation,
32 default: niri_config::Animation,48 default: niri_config::Animation,
49+ ) -> Self {
50+ if config.off {
51+ return Self::ease(from, to, 0, Curve::EaseOutCubic);
52+ }
53+
54+ // Resolve defaults.
55+ let (kind, easing_defaults) = match (config.kind, default.kind) {
56+ // Configured spring.
57+ (configured @ niri_config::AnimationKind::Spring(_), _) => (configured, None),
58+ // Configured nothing, defaults spring.
59+ (
60+ niri_config::AnimationKind::Easing(easing),
61+ defaults @ niri_config::AnimationKind::Spring(_),
62+ ) if easing == niri_config::EasingParams::unfilled() => (defaults, None),
63+ // Configured easing or nothing, defaults easing.
64+ (
65+ configured @ niri_config::AnimationKind::Easing(_),
66+ niri_config::AnimationKind::Easing(defaults),
67+ ) => (configured, Some(defaults)),
68+ // Configured easing, defaults spring.
69+ (
70+ configured @ niri_config::AnimationKind::Easing(_),
71+ niri_config::AnimationKind::Spring(_),
72+ ) => (configured, None),
73+ };
74+
75+ match kind {
76+ niri_config::AnimationKind::Spring(p) => {
77+ let params = SpringParams::new(p.damping_ratio, f64::from(p.stiffness), p.epsilon);
78+
79+ let spring = Spring {
80+ from,
81+ to,
82+ initial_velocity,
83+ params,
84+ };
85+ Self::spring(spring)
86+ }
87+ niri_config::AnimationKind::Easing(p) => {
88+ let defaults = easing_defaults.unwrap_or(niri_config::EasingParams::default());
89+ let duration_ms = p.duration_ms.or(defaults.duration_ms).unwrap();
90+ let curve = Curve::from(p.curve.or(defaults.curve).unwrap());
91+ Self::ease(from, to, u64::from(duration_ms), curve)
92+ }
93+ }
94+ }
95+
96+ pub fn ease(from: f64, to: f64, duration_ms: u64, curve: Curve) -> Self {
97+ // FIXME: ideally we shouldn't use current time here because animations started within the
98+ // same frame cycle should have the same start time to be synchronized.
99+ let now = get_monotonic_time();
100+
101+ let duration = Duration::from_millis(duration_ms);
102+ let kind = Kind::Easing { curve };
103+
104+ Self {
105+ from,
106+ to,
107+ duration,
108+ start_time: now,
109+ current_time: now,
110+ kind,
111+ }
112+ }
113+
114+ pub fn spring(spring: Spring) -> Self {
115+ // FIXME: ideally we shouldn't use current time here because animations started within the
116+ // same frame cycle should have the same start time to be synchronized.
117+ let now = get_monotonic_time();
118+
119+ let duration = spring.duration();
120+ let kind = Kind::Spring(spring);
121+
122+ Self {
123+ from: spring.from,
124+ to: spring.to,
125+ duration,
126+ start_time: now,
127+ current_time: now,
128+ kind,
129+ }
130+ }
131+
132+ pub fn decelerate(
133+ from: f64,
134+ initial_velocity: f64,
135+ deceleration_rate: f64,
136+ threshold: f64,
33 ) -> Self {137 ) -> Self {
34 // FIXME: ideally we shouldn't use current time here because animations started within the138 // FIXME: ideally we shouldn't use current time here because animations started within the
35 // same frame cycle should have the same start time to be synchronized.139 // same frame cycle should have the same start time to be synchronized.
36 let now = get_monotonic_time();140 let now = get_monotonic_time();
37 141
38- let duration_ms = if config.off {142+ let duration_s = if initial_velocity == 0. {
39- 0143+ 0.
40 } else {144 } else {
41- config.duration_ms.unwrap_or(default.duration_ms.unwrap())145+ let coeff = 1000. * deceleration_rate.ln();
146+ (-coeff * threshold / initial_velocity.abs()).ln() / coeff
42 };147 };
43- let duration = Duration::from_millis(u64::from(duration_ms));148+ let duration = Duration::from_secs_f64(duration_s);
149+
150+ let to = from - initial_velocity / (1000. * deceleration_rate.ln());
44 151
45- let curve = Curve::from(config.curve.unwrap_or(default.curve.unwrap()));152+ let kind = Kind::Deceleration {
153+ initial_velocity,
154+ deceleration_rate,
155+ };
46 156
47 Self {157 Self {
48 from,158 from,
@@ -50,7 +160,7 @@ impl Animation {
50 duration,160 duration,
51 start_time: now,161 start_time: now,
52 current_time: now,162 current_time: now,
53- curve,163+ kind,
54 }164 }
55 }165 }
56 166
@@ -118,10 +228,29 @@ impl Animation {
118 }228 }
119 229
120 pub fn value(&self) -> f64 {230 pub fn value(&self) -> f64 {
121- let passed = (self.current_time - self.start_time).as_secs_f64();231+ if self.is_done() {
122- let total = self.duration.as_secs_f64();232+ return self.to;
123- let x = (passed / total).clamp(0., 1.);233+ }
124- self.curve.y(x) * (self.to - self.from) + self.from234+
235+ let passed = self.current_time - self.start_time;
236+
237+ match self.kind {
238+ Kind::Easing { curve } => {
239+ let passed = passed.as_secs_f64();
240+ let total = self.duration.as_secs_f64();
241+ let x = (passed / total).clamp(0., 1.);
242+ curve.y(x) * (self.to - self.from) + self.from
243+ }
244+ Kind::Spring(spring) => spring.value_at(passed),
245+ Kind::Deceleration {
246+ initial_velocity,
247+ deceleration_rate,
248+ } => {
249+ let passed = passed.as_secs_f64();
250+ let coeff = 1000. * deceleration_rate.ln();
251+ self.from + (deceleration_rate.powf(1000. * passed) - 1.) / coeff * initial_velocity
252+ }
253+ }
125 }254 }
126 255
127 pub fn to(&self) -> f64 {256 pub fn to(&self) -> f64 {
src/animation/spring.rsadded+137 -0
@@ -0,0 +1,137 @@
1+use std::time::Duration;
2+
3+#[derive(Debug, Clone, Copy)]
4+pub struct SpringParams {
5+ pub damping: f64,
6+ pub mass: f64,
7+ pub stiffness: f64,
8+ pub epsilon: f64,
9+}
10+
11+#[derive(Debug, Clone, Copy)]
12+pub struct Spring {
13+ pub from: f64,
14+ pub to: f64,
15+ pub initial_velocity: f64,
16+ pub params: SpringParams,
17+}
18+
19+impl SpringParams {
20+ pub fn new(damping_ratio: f64, stiffness: f64, epsilon: f64) -> Self {
21+ let damping_ratio = damping_ratio.max(0.);
22+ let stiffness = stiffness.max(0.);
23+ let epsilon = epsilon.max(0.);
24+
25+ let mass = 1.;
26+ let critical_damping = 2. * (mass * stiffness).sqrt();
27+ let damping = damping_ratio * critical_damping;
28+
29+ Self {
30+ damping,
31+ mass,
32+ stiffness,
33+ epsilon,
34+ }
35+ }
36+}
37+
38+impl Spring {
39+ pub fn value_at(&self, t: Duration) -> f64 {
40+ self.oscillate(t.as_secs_f64())
41+ }
42+
43+ // Based on libadwaita (LGPL-2.1-or-later):
44+ // https://gitlab.gnome.org/GNOME/libadwaita/-/blob/1.4.4/src/adw-spring-animation.c,
45+ // which itself is based on (MIT):
46+ // https://github.com/robb/RBBAnimation/blob/master/RBBAnimation/RBBSpringAnimation.m
47+ /// Computes and returns the duration until the spring is at rest.
48+ pub fn duration(&self) -> Duration {
49+ const DELTA: f64 = 0.001;
50+
51+ let beta = self.params.damping / (2. * self.params.mass);
52+
53+ if beta.abs() <= f64::EPSILON || beta < 0. {
54+ return Duration::MAX;
55+ }
56+
57+ let omega0 = (self.params.stiffness / self.params.mass).sqrt();
58+
59+ // As first ansatz for the overdamped solution,
60+ // and general estimation for the oscillating ones
61+ // we take the value of the envelope when it's < epsilon.
62+ let mut x0 = -self.params.epsilon.ln() / beta;
63+
64+ // f64::EPSILON is too small for this specific comparison, so we use
65+ // f32::EPSILON even though it's doubles.
66+ if (beta - omega0).abs() <= f64::from(f32::EPSILON) || beta < omega0 {
67+ return Duration::from_secs_f64(x0);
68+ }
69+
70+ // Since the overdamped solution decays way slower than the envelope
71+ // we need to use the value of the oscillation itself.
72+ // Newton's root finding method is a good candidate in this particular case:
73+ // https://en.wikipedia.org/wiki/Newton%27s_method
74+ let mut y0 = self.oscillate(x0);
75+ let m = (self.oscillate(x0 + DELTA) - y0) / DELTA;
76+
77+ let mut x1 = (self.to - y0 + m * x0) / m;
78+ let mut y1 = self.oscillate(x1);
79+
80+ let mut i = 0;
81+ while (self.to - y1).abs() > self.params.epsilon {
82+ if i > 1000 {
83+ return Duration::ZERO;
84+ }
85+
86+ x0 = x1;
87+ y0 = y1;
88+
89+ let m = (self.oscillate(x0 + DELTA) - y0) / DELTA;
90+
91+ x1 = (self.to - y0 + m * x0) / m;
92+ y1 = self.oscillate(x1);
93+ i += 1;
94+ }
95+
96+ Duration::from_secs_f64(x1)
97+ }
98+
99+ /// Returns the spring position at a given time in seconds.
100+ fn oscillate(&self, t: f64) -> f64 {
101+ let b = self.params.damping;
102+ let m = self.params.mass;
103+ let k = self.params.stiffness;
104+ let v0 = self.initial_velocity;
105+
106+ let beta = b / (2. * m);
107+ let omega0 = (k / m).sqrt();
108+
109+ let x0 = self.from - self.to;
110+
111+ let envelope = (-beta * t).exp();
112+
113+ // Solutions of the form C1*e^(lambda1*x) + C2*e^(lambda2*x)
114+ // for the differential equation m*ẍ+b*ẋ+kx = 0
115+
116+ // f64::EPSILON is too small for this specific comparison, so we use
117+ // f32::EPSILON even though it's doubles.
118+ if (beta - omega0).abs() <= f64::from(f32::EPSILON) {
119+ // Critically damped.
120+ self.to + envelope * (x0 + (beta * x0 + v0) * t)
121+ } else if beta < omega0 {
122+ // Underdamped.
123+ let omega1 = ((omega0 * omega0) - (beta * beta)).sqrt();
124+
125+ self.to
126+ + envelope
127+ * (x0 * (omega1 * t).cos() + ((beta * x0 + v0) / omega1) * (omega1 * t).sin())
128+ } else {
129+ // Overdamped.
130+ let omega2 = ((beta * beta) - (omega0 * omega0)).sqrt();
131+
132+ self.to
133+ + envelope
134+ * (x0 * (omega2 * t).cosh() + ((beta * x0 + v0) / omega2) * (omega2 * t).sinh())
135+ }
136+ }
137+}
src/layout/monitor.rsmodified+4 -0
@@ -94,6 +94,7 @@ impl<W: LayoutElement> Monitor<W> {
94 return;94 return;
95 }95 }
96 96
97+ // FIXME: also compute and use current velocity.
97 let current_idx = self98 let current_idx = self
98 .workspace_switch99 .workspace_switch
99 .as_ref()100 .as_ref()
@@ -105,6 +106,7 @@ impl<W: LayoutElement> Monitor<W> {
105 self.workspace_switch = Some(WorkspaceSwitch::Animation(Animation::new(106 self.workspace_switch = Some(WorkspaceSwitch::Animation(Animation::new(
106 current_idx,107 current_idx,
107 idx as f64,108 idx as f64,
109+ 0.,
108 self.options.animations.workspace_switch,110 self.options.animations.workspace_switch,
109 niri_config::Animation::default_workspace_switch(),111 niri_config::Animation::default_workspace_switch(),
110 )));112 )));
@@ -781,6 +783,7 @@ impl<W: LayoutElement> Monitor<W> {
781 return true;783 return true;
782 }784 }
783 785
786+ let velocity = gesture.tracker.velocity() / WORKSPACE_GESTURE_MOVEMENT;
784 let pos = gesture.tracker.projected_end_pos() / WORKSPACE_GESTURE_MOVEMENT;787 let pos = gesture.tracker.projected_end_pos() / WORKSPACE_GESTURE_MOVEMENT;
785 788
786 let min = gesture.center_idx.saturating_sub(1) as f64;789 let min = gesture.center_idx.saturating_sub(1) as f64;
@@ -792,6 +795,7 @@ impl<W: LayoutElement> Monitor<W> {
792 self.workspace_switch = Some(WorkspaceSwitch::Animation(Animation::new(795 self.workspace_switch = Some(WorkspaceSwitch::Animation(Animation::new(
793 gesture.current_idx,796 gesture.current_idx,
794 new_idx as f64,797 new_idx as f64,
798+ velocity,
795 self.options.animations.workspace_switch,799 self.options.animations.workspace_switch,
796 niri_config::Animation::default_workspace_switch(),800 niri_config::Animation::default_workspace_switch(),
797 )));801 )));
src/layout/tile.rsmodified+1 -0
@@ -111,6 +111,7 @@ impl<W: LayoutElement> Tile<W> {
111 self.open_animation = Some(Animation::new(111 self.open_animation = Some(Animation::new(
112 0.,112 0.,
113 1.,113 1.,
114+ 0.,
114 self.options.animations.window_open,115 self.options.animations.window_open,
115 niri_config::Animation::default_window_open(),116 niri_config::Animation::default_window_open(),
116 ));117 ));
src/layout/workspace.rsmodified+4 -0
@@ -436,9 +436,11 @@ impl<W: LayoutElement> Workspace<W> {
436 return;436 return;
437 }437 }
438 438
439+ // FIXME: also compute and use current velocity.
439 self.view_offset_adj = Some(ViewOffsetAdjustment::Animation(Animation::new(440 self.view_offset_adj = Some(ViewOffsetAdjustment::Animation(Animation::new(
440 self.view_offset as f64,441 self.view_offset as f64,
441 new_view_offset as f64,442 new_view_offset as f64,
443+ 0.,
442 self.options.animations.horizontal_view_movement,444 self.options.animations.horizontal_view_movement,
443 niri_config::Animation::default_horizontal_view_movement(),445 niri_config::Animation::default_horizontal_view_movement(),
444 )));446 )));
@@ -1272,6 +1274,7 @@ impl<W: LayoutElement> Workspace<W> {
1272 // effort and bug potential.1274 // effort and bug potential.
1273 1275
1274 let norm_factor = self.working_area.size.w as f64 / VIEW_GESTURE_WORKING_AREA_MOVEMENT;1276 let norm_factor = self.working_area.size.w as f64 / VIEW_GESTURE_WORKING_AREA_MOVEMENT;
1277+ let velocity = gesture.tracker.velocity() * norm_factor;
1275 let pos = gesture.tracker.pos() * norm_factor;1278 let pos = gesture.tracker.pos() * norm_factor;
1276 let current_view_offset = pos + gesture.delta_from_tracker;1279 let current_view_offset = pos + gesture.delta_from_tracker;
1277 1280
@@ -1420,6 +1423,7 @@ impl<W: LayoutElement> Workspace<W> {
1420 self.view_offset_adj = Some(ViewOffsetAdjustment::Animation(Animation::new(1423 self.view_offset_adj = Some(ViewOffsetAdjustment::Animation(Animation::new(
1421 current_view_offset + delta,1424 current_view_offset + delta,
1422 target_view_offset as f64,1425 target_view_offset as f64,
1426+ velocity,
1423 self.options.animations.horizontal_view_movement,1427 self.options.animations.horizontal_view_movement,
1424 niri_config::Animation::default_horizontal_view_movement(),1428 niri_config::Animation::default_horizontal_view_movement(),
1425 )));1429 )));
src/ui/config_error_notification.rsmodified+4 -1
@@ -62,6 +62,7 @@ impl ConfigErrorNotification {
62 Animation::new(62 Animation::new(
63 from,63 from,
64 to,64 to,
65+ 0.,
65 c.animations.config_notification_open_close,66 c.animations.config_notification_open_close,
66 niri_config::Animation::default_config_notification_open_close(),67 niri_config::Animation::default_config_notification_open_close(),
67 )68 )
@@ -118,7 +119,9 @@ impl ConfigErrorNotification {
118 }119 }
119 State::Hiding(anim) => {120 State::Hiding(anim) => {
120 anim.set_current_time(target_presentation_time);121 anim.set_current_time(target_presentation_time);
121- if anim.is_done() {122+ // HACK: prevent bounciness on hiding. This is better done with a clamp property on
123+ // the spring animation.
124+ if anim.is_done() || anim.value() <= 0. {
122 self.state = State::Hidden;125 self.state = State::Hidden;
123 }126 }
124 }127 }