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
use crate::prelude::{GlowVertexAttribs, Graphics};
use glow::{Context, HasContext};
use glutin::{
    dpi::LogicalSize,
    event::{Event, WindowEvent},
    event_loop::{ControlFlow, EventLoop},
    platform::run_return::EventLoopExtRunReturn,
    window::{Fullscreen, Window, WindowBuilder},
    ContextBuilder, ContextWrapper, PossiblyCurrent,
};

#[allow(unused_variables)]
pub trait AppState<V: GlowVertexAttribs> {
    fn on_init(&mut self, graphics: &mut Graphics<V>) {}

    fn on_redraw(&mut self, graphics: &mut Graphics<V>) {}

    fn on_event(&mut self, event: Event<()>, window: &mut Window) -> bool {
        true
    }
}

#[derive(Debug, Clone)]
pub struct AppConfig {
    pub title: String,
    pub width: u32,
    pub height: u32,
    pub fullscreen: bool,
    pub maximized: bool,
    pub vsync: bool,
    pub decorations: bool,
    pub transparent: bool,
    pub refresh_on_event: bool,
    pub color: [f32; 3],
}

impl Default for AppConfig {
    fn default() -> Self {
        Self {
            title: "Spitfire Application".to_owned(),
            width: 1024,
            height: 576,
            fullscreen: false,
            maximized: false,
            vsync: false,
            decorations: true,
            transparent: false,
            refresh_on_event: false,
            color: [1.0, 1.0, 1.0],
        }
    }
}

impl AppConfig {
    pub fn title(mut self, v: impl ToString) -> Self {
        self.title = v.to_string();
        self
    }

    pub fn width(mut self, v: u32) -> Self {
        self.width = v;
        self
    }

    pub fn height(mut self, v: u32) -> Self {
        self.height = v;
        self
    }

    pub fn fullscreen(mut self, v: bool) -> Self {
        self.fullscreen = v;
        self
    }

    pub fn maximized(mut self, v: bool) -> Self {
        self.maximized = v;
        self
    }

    pub fn vsync(mut self, v: bool) -> Self {
        self.vsync = v;
        self
    }

    pub fn decorations(mut self, v: bool) -> Self {
        self.decorations = v;
        self
    }

    pub fn transparent(mut self, v: bool) -> Self {
        self.transparent = v;
        self
    }

    pub fn refresh_on_event(mut self, v: bool) -> Self {
        self.refresh_on_event = v;
        self
    }

    pub fn color(mut self, v: impl Into<[f32; 3]>) -> Self {
        self.color = v.into();
        self
    }
}

pub struct App<V: GlowVertexAttribs> {
    width: u32,
    height: u32,
    refresh_on_event: bool,
    event_loop: EventLoop<()>,
    context_wrapper: ContextWrapper<PossiblyCurrent, Window>,
    graphics: Graphics<V>,
}

impl<V: GlowVertexAttribs> Default for App<V> {
    fn default() -> Self {
        Self::new(Default::default())
    }
}

impl<V: GlowVertexAttribs> App<V> {
    pub fn new(config: AppConfig) -> Self {
        let AppConfig {
            title,
            width,
            height,
            fullscreen,
            maximized,
            vsync,
            decorations,
            transparent,
            refresh_on_event,
            color,
        } = config;
        let fullscreen = if fullscreen {
            Some(Fullscreen::Borderless(None))
        } else {
            None
        };
        let event_loop = EventLoop::new();
        let window_builder = WindowBuilder::new()
            .with_title(title.as_str())
            .with_inner_size(LogicalSize::new(width, height))
            .with_fullscreen(fullscreen)
            .with_maximized(maximized)
            .with_decorations(decorations)
            .with_transparent(transparent);
        let context_wrapper = unsafe {
            ContextBuilder::new()
                .with_vsync(vsync)
                .with_double_buffer(Some(true))
                .with_hardware_acceleration(Some(true))
                .build_windowed(window_builder, &event_loop)
                .expect("Could not build windowed context wrapper!")
                .make_current()
                .expect("Could not make windowed context wrapper a current one!")
        };
        let context = unsafe {
            Context::from_loader_function(|name| context_wrapper.get_proc_address(name) as *const _)
        };
        let mut graphics = Graphics::<V>::new(context);
        graphics.color = color;
        Self {
            width,
            height,
            refresh_on_event,
            event_loop,
            context_wrapper,
            graphics,
        }
    }

    pub fn run<S: AppState<V>>(self, mut state: S) -> S {
        let App {
            mut width,
            mut height,
            refresh_on_event,
            mut event_loop,
            context_wrapper,
            mut graphics,
        } = self;
        let (context, mut window) = unsafe { context_wrapper.split() };
        state.on_init(&mut graphics);
        let mut running = true;
        while running {
            event_loop.run_return(|event, _, control_flow| {
                *control_flow = if refresh_on_event {
                    ControlFlow::Wait
                } else {
                    ControlFlow::Poll
                };
                match &event {
                    Event::MainEventsCleared => {
                        unsafe {
                            graphics
                                .context()
                                .unwrap()
                                .viewport(0, 0, width as _, height as _);
                        }
                        graphics.main_camera.screen_size.x = width as _;
                        graphics.main_camera.screen_size.y = height as _;
                        graphics.prepare_frame();
                        state.on_redraw(&mut graphics);
                        let _ = graphics.draw();
                        let _ = context.swap_buffers();
                        *control_flow = ControlFlow::Exit;
                    }
                    Event::WindowEvent { event, .. } => match event {
                        WindowEvent::Resized(physical_size) => {
                            context.resize(*physical_size);
                            width = physical_size.width;
                            height = physical_size.height;
                        }
                        WindowEvent::CloseRequested => {
                            running = false;
                        }
                        _ => {}
                    },
                    _ => {}
                }
                if !state.on_event(event, &mut window) {
                    running = false;
                }
            });
        }
        drop(graphics);
        state
    }
}