summaryrefslogtreecommitdiff
path: root/src/main.rs
blob: 92fe01e6b180400ee0a6985e4dd08b7b33bb58ec (plain)
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
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
mod camera;
mod config;
mod renderer;
mod sim;

use futures::executor;
use rand::random_range;
use std::{collections::VecDeque, sync::Arc, time::Instant};
use winit::{
    application::ApplicationHandler,
    event::{
        ElementState, KeyEvent, MouseButton,
        WindowEvent::{self},
    },
    event_loop::{ActiveEventLoop, ControlFlow, EventLoop},
    keyboard::{KeyCode, PhysicalKey},
    window::Window,
};

use crate::{
    camera::Camera,
    config::{SIM_FPS, WINDOW_TITLE},
    renderer::RendererState,
    sim::{cell::Cell, materials::MaterialId, sim::sim_tick, world::World},
};

pub type Error = Box<dyn std::error::Error>;
pub type Result<T> = std::result::Result<T, Error>;

struct Config {
    brush_radius: u8,
    brush_material: MaterialId,
    use_threading: bool,
}

struct Input {
    last_mouse_pos_on_screen: Option<(f64, f64)>,
    last_mouse_pos_on_board: Option<(i32, i32)>,
    is_lmb_pressed: bool,

    // keybindings
    is_up_pressed: bool,
    is_left_pressed: bool,
    is_down_pressed: bool,
    is_right_pressed: bool,
}

struct Diagnostics {
    frame_times: VecDeque<f32>,
    fps: f32,
}

struct App {
    window: Option<Arc<Window>>,
    renderer_state: Option<RendererState>,

    input: Input,

    camera: Option<Camera>,

    world: Option<World>,

    // sim state
    // the last/current (not yet completed) seqno
    sim_seqno: u64,
    sim_paused: bool,
    ignore_pause_next_tick: bool,

    // used to compute delta_time
    last_sim_tick: Instant,
    sim_ticks_due: f32,
    last_render: Instant,

    config: Config,
    diagnostics: Diagnostics,
}

impl Default for App {
    fn default() -> Self {
        Self {
            window: None,
            renderer_state: None,

            input: Input {
                last_mouse_pos_on_screen: None,
                last_mouse_pos_on_board: None,

                is_lmb_pressed: false,
                is_up_pressed: false,
                is_left_pressed: false,
                is_down_pressed: false,
                is_right_pressed: false,
            },

            camera: None,

            world: Some(World::from_default_size()),

            sim_seqno: 0,
            sim_paused: false,
            ignore_pause_next_tick: false,

            last_sim_tick: Instant::now(),
            sim_ticks_due: 0.,
            last_render: Instant::now(),

            config: Config {
                use_threading: true,
                brush_radius: 10,
                brush_material: MaterialId::Sand,
            },
            diagnostics: Diagnostics {
                fps: 0.0,
                frame_times: VecDeque::new(),
            },
        }
    }
}

impl ApplicationHandler for App {
    fn resumed(&mut self, event_loop: &ActiveEventLoop) {
        let window = Arc::new(
            event_loop
                .create_window(Window::default_attributes().with_title(WINDOW_TITLE))
                .unwrap(),
        );

        self.window = Some(window.clone());
        self.renderer_state = Some(executor::block_on(RendererState::new(window.clone())));

        let size = window.inner_size();
        self.camera = Some(Camera::new((size.width as i32, size.height as i32)));

        // let surface = SurfaceTexture::new(size.width, size.height, window_ref);

        // let mut pixels = Pixels::new(PIXEL_BUFFER_WIDTH, PIXEL_BUFFER_HEIGHT, surface).unwrap();

        // pixels.set_scaling_mode(ScalingMode::Fill);
    }

    fn window_event(
        &mut self,
        event_loop: &ActiveEventLoop,
        _: winit::window::WindowId,
        event: WindowEvent,
    ) {
        if let Some(window) = &self.window
            && let Some(renderer_state) = &mut self.renderer_state
            && let Some(world) = &mut self.world
            && let Some(camera) = &mut self.camera
        {
            let egui_response = renderer_state.egui_state.on_window_event(window, &event);
            // if egui consumed the event, it means we shouldn't treat any e.g., mouse clicks
            if egui_response.consumed {
                return;
            }

            match event {
                WindowEvent::KeyboardInput {
                    event:
                        KeyEvent {
                            physical_key: PhysicalKey::Code(code),
                            state,
                            ..
                        },
                    ..
                } => {
                    let pressed = state.is_pressed();
                    match code {
                        KeyCode::KeyW => self.input.is_up_pressed = pressed,
                        KeyCode::KeyA => self.input.is_left_pressed = pressed,
                        KeyCode::KeyS => self.input.is_down_pressed = pressed,
                        KeyCode::KeyD => self.input.is_right_pressed = pressed,
                        KeyCode::KeyC => self.world = Some(World::from_default_size()),
                        KeyCode::Space => {
                            if pressed {
                                self.sim_paused = !self.sim_paused
                            }
                        }
                        KeyCode::KeyX => {
                            if pressed {
                                self.ignore_pause_next_tick = true
                            }
                        }
                        _ => {}
                    }
                }
                WindowEvent::CursorMoved { position, .. } => {
                    self.input.last_mouse_pos_on_screen = Some((position.x, position.y));
                    let world_pos =
                        camera.screen_position_to_world(position.x as f32, position.y as f32);
                    self.input.last_mouse_pos_on_board =
                        Some((world_pos.0 as i32, world_pos.1 as i32))
                }
                WindowEvent::MouseInput { state, button, .. } => {
                    if button == MouseButton::Left {
                        self.input.is_lmb_pressed = state == ElementState::Pressed
                    }
                }
                WindowEvent::Resized(size) => {
                    renderer_state.resize(size.width, size.height);
                    camera.resize((size.width as i32, size.height as i32));
                }
                WindowEvent::CloseRequested => {
                    event_loop.exit();
                }
                WindowEvent::RedrawRequested => {
                    #[cfg(feature = "profiler")]
                    puffin::GlobalProfiler::lock().new_frame();

                    puffin::profile_scope!("redraw_requested");
                    // compute FPS diagnostics
                    let now = Instant::now();
                    let secs_since_last_frame = (now - self.last_render).as_secs_f32();
                    self.last_render = now;

                    let delta_time = secs_since_last_frame / (1.0 / 60.0);

                    self.diagnostics
                        .frame_times
                        .push_back(secs_since_last_frame);

                    if self.diagnostics.frame_times.len() > 30 {
                        self.diagnostics.frame_times.pop_front();
                    }

                    let average_frame_time = self.diagnostics.frame_times.iter().sum::<f32>()
                        / self.diagnostics.frame_times.len() as f32;

                    self.diagnostics.fps = 1.0 / average_frame_time;

                    // apply inputs
                    camera.handle_camera_input(&self.input, delta_time);

                    // // --TEST DRAWING--
                    if self.input.is_lmb_pressed
                        && let Some(lm) = self.input.last_mouse_pos_on_board
                    {
                        // start with the bounding box of the drawing brush circle + some margin
                        // clamp the bounding box to the board sie
                        let bb_xl = lm.0 - self.config.brush_radius as i32;
                        let bb_xu = lm.0 + self.config.brush_radius as i32;
                        let bb_yl = lm.1 - self.config.brush_radius as i32;
                        let bb_yu = lm.1 + self.config.brush_radius as i32;

                        // for each point, check if the distance is less than the brush size and write the pixel
                        for x in bb_xl..bb_xu {
                            for y in bb_yl..bb_yu {
                                let r = random_range(0.0..1.0);
                                if ((x - lm.0).pow(2) + (y - lm.1).pow(2))
                                    < (self.config.brush_radius as i32).pow(2)
                                    && r > 0.9
                                {
                                    let mut cell = Cell::from_material(self.config.brush_material);
                                    cell.flags = (self.sim_seqno as u8) & 0b1;
                                    world.set_cell_from_game_position(
                                        x, y, cell, // wake the chunk
                                        false,
                                    );
                                }
                            }
                        }
                    }

                    // SIM logic
                    let secs_since_last_tick = (now - self.last_sim_tick).as_secs_f32();
                    let expected_secs_since_last_tick = 1.0 / SIM_FPS as f32;

                    if self.sim_paused && self.ignore_pause_next_tick {
                        sim_tick(world, self.sim_seqno, self.config.use_threading);
                        self.sim_seqno += 1;
                        self.ignore_pause_next_tick = false;
                    } else if !self.sim_paused {
                        self.sim_ticks_due += secs_since_last_tick / expected_secs_since_last_tick;
                        self.last_sim_tick = now;
                        let mut ticks_done = 0;
                        // don't ever tick more than 3 times per frame, or else we can get a pseudo deadlock
                        while self.sim_ticks_due >= 1.0 && ticks_done < 3 {
                            sim_tick(world, self.sim_seqno, self.config.use_threading);
                            self.sim_seqno += 1;
                            ticks_done += 1;
                        }
                        self.sim_ticks_due -= ticks_done as f32;
                    }

                    renderer_state.render(
                        world,
                        camera,
                        &mut self.config,
                        &self.diagnostics,
                        &mut self.input,
                    );
                }
                _ => {}
            }
        }
    }

    fn about_to_wait(&mut self, _: &ActiveEventLoop) {
        if let Some(window) = &self.window {
            window.request_redraw();
        } else {
            panic!("No window!")
        }
    }
}

#[cfg(feature = "profiler")]
fn start_profiler() {
    let _server = puffin_http::Server::new("127.0.0.1:8585").unwrap();
    puffin::set_scopes_on(true);
    std::mem::forget(_server); // keep serving for the process lifetime

    std::process::Command::new("puffin_viewer")
        .args(["--url", "127.0.0.1:8585"])
        .spawn()
        .ok(); // don't die if it isn't installed
}

fn main() -> Result<()> {
    #[cfg(feature = "profiler")]
    start_profiler();

    let event_loop = EventLoop::new()?;
    event_loop.set_control_flow(ControlFlow::Poll);

    let mut app = App::default();
    event_loop.run_app(&mut app)?;

    Ok(())
}