veloren_voxygen/hud/
change_notification.rs

1use serde::{Deserialize, Serialize};
2
3use std::time::Duration;
4
5/// Default initial alpha of a Notify
6const NOTIF_START_ALPHA: f32 = 1.0;
7
8/// Default time to live of a notify
9const NOTIF_LIFETIME: f32 = 2.0;
10/// Default fading time of a notify
11const NOTIF_FADETIME: f32 = 1.5;
12
13/// The reason this notification is being shown: the setting is being enabled or
14/// disabled, or we are reminding the player of the current state.
15#[derive(Clone, Copy, Debug, Deserialize, Serialize)]
16pub enum NotificationReason {
17    Remind = 2,
18    Enable = 1,
19    #[serde(other)]
20    Disable = 0,
21}
22/// A temporal, fading message that a setting
23/// or other state was changed (probably by direct player input)
24#[derive(Default)]
25pub struct ChangeNotification {
26    pub reason: Option<NotificationReason>,
27    pub alpha: f32,
28    lifetime: Duration,
29    fadetime: Duration,
30    initial_fadetime: Duration,
31}
32
33impl ChangeNotification {
34    pub fn new(
35        reason: Option<NotificationReason>,
36        alpha: f32,
37        lifetime: Duration,
38        fadetime: Duration,
39    ) -> Result<Self, Duration> {
40        if fadetime.is_zero() {
41            Err(fadetime)
42        } else {
43            Ok(Self {
44                reason,
45                alpha,
46                lifetime,
47                fadetime,
48                initial_fadetime: fadetime,
49            })
50        }
51    }
52
53    pub fn from_reason(reason: NotificationReason) -> Self {
54        ChangeNotification::new(
55            Some(reason),
56            NOTIF_START_ALPHA,
57            Duration::from_secs_f32(NOTIF_LIFETIME),
58            Duration::from_secs_f32(NOTIF_FADETIME),
59        )
60        .unwrap()
61    }
62
63    pub fn from_state(state: bool) -> Self {
64        ChangeNotification::from_reason(match state {
65            true => NotificationReason::Enable,
66            false => NotificationReason::Disable,
67        })
68    }
69
70    pub fn update(&mut self, dt: Duration) {
71        if self.reason.is_some() {
72            // Timer before fade
73            if !self.lifetime.is_zero() {
74                self.lifetime = self.lifetime.saturating_sub(dt);
75            // Lifetime expired, start to fade
76            } else if !self.fadetime.is_zero() {
77                self.fadetime = self.fadetime.saturating_sub(dt);
78                // alpha as elapsed duration fraction, multiply with this for nice fade curve
79                self.alpha = self.fadetime.as_secs_f32() / self.initial_fadetime.as_secs_f32();
80            // Done fading
81            } else {
82                self.reason = None;
83            }
84        }
85    }
86}