Skip to main content

eldiron_shared/
screen.rs

1use rusterix::Map;
2use theframework::prelude::*;
3
4#[derive(Serialize, Deserialize, Clone, Debug)]
5pub struct Screen {
6    pub id: Uuid,
7    pub name: String,
8
9    pub map: Map,
10}
11
12impl Default for Screen {
13    fn default() -> Self {
14        Self::new()
15    }
16}
17
18impl Screen {
19    pub fn new() -> Self {
20        Self {
21            id: Uuid::new_v4(),
22            name: "New Screen".to_string(),
23
24            map: Map::default(),
25        }
26    }
27
28    /// Create a region from json.
29    pub fn from_json(json: &str) -> Self {
30        serde_json::from_str(json).unwrap_or(Screen::new())
31    }
32
33    /// Convert the region to json.
34    pub fn to_json(&self) -> String {
35        serde_json::to_string(&self).unwrap_or_default()
36    }
37}
38
39/// The aspect ratio of the screen.
40#[derive(Serialize, Deserialize, PartialEq, Clone, Copy, Debug)]
41pub enum ScreenAspectRatio {
42    _16_9,
43    _4_3,
44}
45
46impl ScreenAspectRatio {
47    pub fn to_string(self) -> &'static str {
48        match self {
49            Self::_16_9 => "16:9",
50            Self::_4_3 => "4:3",
51        }
52    }
53    pub fn ratio(self) -> f32 {
54        match self {
55            Self::_16_9 => 16.0 / 9.0,
56            Self::_4_3 => 4.0 / 3.0,
57        }
58    }
59    pub fn iterator() -> impl Iterator<Item = ScreenAspectRatio> {
60        [Self::_16_9, Self::_4_3].iter().copied()
61    }
62    pub fn width(self, height: i32) -> i32 {
63        (height as f32 * self.ratio()) as i32
64    }
65    pub fn height(self, width: i32) -> i32 {
66        (width as f32 / self.ratio()) as i32
67    }
68    pub fn from_index(index: u8) -> Option<ScreenAspectRatio> {
69        match index {
70            0 => Some(Self::_16_9),
71            1 => Some(Self::_4_3),
72            _ => None,
73        }
74    }
75}