89 lines
3.1 KiB
Rust
89 lines
3.1 KiB
Rust
use winit::application::ApplicationHandler;
|
|
use winit::event::{ElementState, Modifiers, MouseScrollDelta, WindowEvent};
|
|
use winit::event_loop::ActiveEventLoop;
|
|
use winit::window::{Window, WindowId};
|
|
use crate::input::{InputEvent, InputTracker};
|
|
|
|
pub struct StateApplication<'a> {
|
|
state: Option<crate::state::State<'a>>,
|
|
modifiers: Modifiers,
|
|
update_fn: Option<Box<dyn FnMut(&mut crate::state::State<'a>) + 'a>>,
|
|
input_fn: Option<Box<dyn FnMut(&mut crate::state::State<'a>, &InputEvent) + 'a>>,
|
|
input_tracker: InputTracker
|
|
}
|
|
|
|
impl<'a> StateApplication<'a> {
|
|
pub fn new() -> Self {
|
|
Self { state: None, update_fn: None, input_fn: None, modifiers: Modifiers::default(), input_tracker: InputTracker::default() }
|
|
}
|
|
|
|
pub fn on_update<F: FnMut(&mut crate::state::State<'a>) + 'a>(mut self, func: F) -> Self {
|
|
self.update_fn = Some(Box::new(func));
|
|
self
|
|
}
|
|
|
|
pub fn on_input<F: FnMut(&mut crate::state::State<'a>, &InputEvent) + 'a>(mut self, func: F) -> Self {
|
|
self.input_fn = Some(Box::new(func));
|
|
self
|
|
}
|
|
|
|
pub fn run(mut self) {
|
|
let event_loop = winit::event_loop::EventLoop::new().unwrap();
|
|
let _ = event_loop.run_app(&mut self);
|
|
}
|
|
}
|
|
|
|
impl<'a> ApplicationHandler for StateApplication<'a> {
|
|
fn resumed(&mut self, event_loop: &ActiveEventLoop) {
|
|
let window = event_loop
|
|
.create_window(Window::default_attributes().with_title("Solar Engine"))
|
|
.unwrap();
|
|
self.state = Some(crate::state::State::new(window));
|
|
}
|
|
|
|
fn window_event(
|
|
&mut self,
|
|
event_loop: &ActiveEventLoop,
|
|
window_id: WindowId,
|
|
event: WindowEvent,
|
|
) {
|
|
let window = self.state.as_ref().unwrap().window();
|
|
|
|
if window.id() == window_id {
|
|
match event {
|
|
WindowEvent::CloseRequested => {
|
|
event_loop.exit();
|
|
}
|
|
WindowEvent::Resized(physical_size) => {
|
|
self.state.as_mut().unwrap().resize(physical_size);
|
|
}
|
|
WindowEvent::RedrawRequested => {
|
|
if let (Some(state), Some(update_fn)) = (self.state.as_mut(), self.update_fn.as_mut()) {
|
|
update_fn(state);
|
|
}
|
|
|
|
self.state.as_mut().unwrap().render().unwrap();
|
|
}
|
|
WindowEvent::ModifiersChanged(modifiers) => {
|
|
self.modifiers = modifiers;
|
|
}
|
|
_ => {
|
|
if let Some(state) = self.state.as_mut() {
|
|
if let Some(event) = self.input_tracker.handle_window_event(&event, self.modifiers) {
|
|
if let Some(input_fn) = self.input_fn.as_mut() {
|
|
input_fn(state, &event);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
fn about_to_wait(&mut self, _event_loop: &ActiveEventLoop) {
|
|
if let Some(state) = self.state.as_ref() {
|
|
state.window().request_redraw();
|
|
}
|
|
}
|
|
}
|