summaryrefslogtreecommitdiffstats
path: root/src/main.rs
blob: 68ecd5535e7cfea255d3199fbf95bda61968c856 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
mod window;
mod ui;
mod tacmap;
mod wgpuctx;
mod eguictx;
mod vertex;
mod texture;
mod solar_system;
mod fleet;
mod known_stars;
mod timeman;
mod ntree;

use std::cell::RefCell;
use std::thread;
use std::time::{Duration, Instant};

use winit::event::{KeyEvent, WindowEvent};
use winit::event_loop::{EventLoop, ActiveEventLoop, ControlFlow};
use winit::error::{EventLoopError};
use winit::application::{ApplicationHandler};
use winit::keyboard::PhysicalKey;
use winit::window::WindowId;

use solar_system::*;

use crate::fleet::FleetsManager;
use crate::timeman::TimeMan;
use crate::window::GameWindow;

const TARGET_FPS: f32 = 100.0;
const TARGET_DT: Duration = Duration::from_millis((1000.0 / TARGET_FPS) as u64);

struct SystemicApp
{
    window: Option<GameWindow>,
    wgpu_instance: wgpu::Instance,

    last_render_time: Instant,
    game_state: Option<RefCell<GameState>>
}

struct GameState
{
    timeman: TimeMan,
    solar_systems: Vec<SolarSystem>,
    fleets: FleetsManager
}

impl SystemicApp
{
    fn create_window(
        &mut self,
        event_loop: &ActiveEventLoop)
    {
        self.window = Some(GameWindow::new(
                &self.wgpu_instance,
                event_loop).unwrap());

        self.game_state = Some(RefCell::new(GameState::new()));
    }
}

impl GameState
{
    pub fn new()
    -> Self {
        let timeman = TimeMan::new(0);
        let sol_system = match SolarSystem::new_from_known_star(0, "sol")
        {
            Ok(system) => system,
            Err(e) => panic!("Unable to create sol system : {}", e)
        };

        Self {
            timeman: timeman,
            solar_systems: vec![ sol_system ],
            fleets: FleetsManager::new()
        }
    }

    pub fn solar_systems(&self) -> &[SolarSystem]
    { self.solar_systems.as_slice() }

    pub fn solar_systems_mut(&mut self) -> &mut [SolarSystem]
    { self.solar_systems.as_mut_slice() }

    pub fn fleets(&self) -> &FleetsManager
    { &self.fleets }

    pub fn fleets_mut(&mut self) -> &mut FleetsManager
    { &mut self.fleets }

    pub fn timeman(&self) -> &TimeMan
    { &self.timeman }

    pub fn timeman_mut(&mut self) -> &mut TimeMan
    { &mut self.timeman }

    fn update(
        &mut self,
        _dt: Duration)
    {
        let time_then = self.timeman.update();
        if time_then == self.timeman.seconds() { return; }

        self.fleets.tick(
            &self.solar_systems, 
            time_then, 
            self.timeman.seconds());
    }
}

impl ApplicationHandler for SystemicApp
{
    fn resumed(
        &mut self, 
        event_loop: &ActiveEventLoop
    ) {
        match self.window {
            Some(_) => {}
            None => self.create_window(event_loop)
        }
    }

    fn window_event(
            &mut self,
            event_loop: &ActiveEventLoop,
            _window_id: WindowId,
            event: winit::event::WindowEvent,
    ) {
        let window = match &mut self.window {
            Some(w) => w,
            None => return
        };

        let game_state = match &self.game_state {
            Some(state) => state,
            None => return
        };

        let event_resp = window.on_event(&event);

        match event {
            WindowEvent::CloseRequested => {
                event_loop.exit();  
            }
            WindowEvent::Resized(size) => {
                window.resize(size.width, size.height);
            }
            WindowEvent::RedrawRequested => {
                let now = Instant::now();
                let delta_time = now - self.last_render_time;
                self.last_render_time = now;

                game_state.borrow_mut().update(delta_time);
                window.update(game_state, delta_time);
                
                match window.render(game_state, event_resp) {
                    Ok(_) => {}
                    Err(wgpu::CurrentSurfaceTexture::Suboptimal(_) |
                        wgpu::CurrentSurfaceTexture::Outdated |
                        wgpu::CurrentSurfaceTexture::Lost
                    ) => {
                        let size = window.size();
                        window.resize(size.width, size.height);
                    },
                    Err(_) => {
                        log::error!("Uncaught error while trying to render!");
                    }
                }
                if delta_time < TARGET_DT {
                    thread::sleep(TARGET_DT - delta_time);
                }
            }
            WindowEvent::KeyboardInput {
                event: KeyEvent {
                    physical_key: PhysicalKey::Code(key_code),
                    state: key_state,
                    ..
                },
                ..
            } => {
                if !event_resp.consumed {
                    window.keyboard_input(key_code, key_state);
                }
            }
            _ => {}
        }
    }
} // impl ApplicationHandler for SystemicApp

fn main()
    -> Result<(), EventLoopError>
{
    env_logger::init();
    let event_loop = EventLoop::new().unwrap();

    event_loop.set_control_flow(ControlFlow::Poll);

    let mut app = SystemicApp {
        window: None,
        wgpu_instance: wgpu::Instance::default(),
        last_render_time: Instant::now(),
        game_state: None
    };

    event_loop.run_app(&mut app)
}