Skip to main content

oxide_engine/ecs/
resource.rs

1//! Engine resources
2
3use std::time::{Duration, Instant};
4
5use oxide_ecs::Resource;
6use oxide_renderer::Renderer;
7
8#[derive(Resource)]
9pub struct Time {
10    pub delta: Duration,
11    pub elapsed: Duration,
12    last_frame: Instant,
13}
14
15impl Default for Time {
16    fn default() -> Self {
17        Self {
18            delta: Duration::ZERO,
19            elapsed: Duration::ZERO,
20            last_frame: Instant::now(),
21        }
22    }
23}
24
25impl Time {
26    pub fn update(&mut self) {
27        let now = Instant::now();
28        self.delta = now - self.last_frame;
29        self.elapsed += self.delta;
30        self.last_frame = now;
31    }
32
33    pub fn delta_secs(&self) -> f32 {
34        self.delta.as_secs_f32()
35    }
36
37    pub fn elapsed_secs(&self) -> f32 {
38        self.elapsed.as_secs_f32()
39    }
40}
41
42#[derive(Resource)]
43pub struct RendererResource {
44    pub renderer: Renderer,
45}
46
47impl RendererResource {
48    pub fn new(renderer: Renderer) -> Self {
49        Self { renderer }
50    }
51}
52
53#[derive(Resource)]
54pub struct WindowResource {
55    pub width: u32,
56    pub height: u32,
57}
58
59impl WindowResource {
60    pub fn new(width: u32, height: u32) -> Self {
61        Self { width, height }
62    }
63
64    pub fn aspect_ratio(&self) -> f32 {
65        if self.height > 0 {
66            self.width as f32 / self.height as f32
67        } else {
68            1.0
69        }
70    }
71
72    pub fn update(&mut self, width: u32, height: u32) {
73        self.width = width;
74        self.height = height;
75    }
76}