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
use crate::resource::DesktopAppEvents;
use core::app::{App, AppLifeCycle, AppParams, BackendAppRunner};
use glutin::{
    dpi::LogicalSize,
    event::{Event, WindowEvent},
    event_loop::{ControlFlow, EventLoop},
    platform::run_return::EventLoopExtRunReturn,
    window::{Fullscreen, Window, WindowBuilder},
    ContextBuilder, ContextWrapper, PossiblyCurrent,
};
use std::{
    cell::RefCell,
    collections::HashMap,
    env::{current_exe, set_current_dir, var},
    rc::Rc,
    sync::Arc,
};

pub type DesktopContextWrapper = ContextWrapper<PossiblyCurrent, Window>;

pub fn desktop_app_params() -> AppParams {
    let mut result = HashMap::default();
    let mut key = None;
    for arg in std::env::args() {
        if let Some(value) = arg.strip_prefix("--") {
            key = Some(value.to_owned());
            result.insert(value.to_owned(), Default::default());
        } else if let Some(value) = arg.strip_prefix('-') {
            key = Some(value.to_owned());
            result.insert(value.to_owned(), Default::default());
        } else if let Some(value) = arg.strip_prefix('/') {
            key = Some(value.to_owned());
            result.insert(value.to_owned(), Default::default());
        } else if let Some(key) = key.take() {
            result.insert(key, arg.to_owned());
        }
    }
    AppParams::new(result)
}

pub struct DesktopAppConfig {
    pub title: String,
    pub width: u32,
    pub height: u32,
    pub fullscreen: bool,
    pub vsync: bool,
    pub depth: bool,
    pub stencil: bool,
}

impl Default for DesktopAppConfig {
    fn default() -> Self {
        Self {
            title: "Oxygengine Game".to_owned(),
            width: 1024,
            height: 576,
            fullscreen: false,
            vsync: false,
            depth: false,
            stencil: false,
        }
    }
}

pub struct DesktopAppRunner {
    event_loop: EventLoop<()>,
    context_wrapper: Arc<DesktopContextWrapper>,
}

impl DesktopAppRunner {
    pub fn new(config: DesktopAppConfig) -> Self {
        if let Ok(path) = var("OXY_ROOT_PATH") {
            let _ = set_current_dir(path);
        } else if let Ok(mut dir) = current_exe() {
            dir.pop();
            let _ = set_current_dir(dir);
        }
        let DesktopAppConfig {
            title,
            width,
            height,
            fullscreen,
            vsync,
            depth,
            stencil,
        } = 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);
        let context_wrapper = Arc::new(unsafe {
            let mut builder = ContextBuilder::new()
                .with_vsync(vsync)
                .with_double_buffer(Some(true))
                .with_hardware_acceleration(Some(true));
            if depth {
                builder = builder.with_depth_buffer(24);
            }
            if stencil {
                builder = builder.with_stencil_buffer(8);
            }
            builder
                .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!")
        });
        Self {
            event_loop,
            context_wrapper,
        }
    }

    pub fn context_wrapper(&self) -> Arc<DesktopContextWrapper> {
        self.context_wrapper.clone()
    }
}

impl BackendAppRunner<()> for DesktopAppRunner {
    fn run(&mut self, app: Rc<RefCell<App>>) -> Result<(), ()> {
        let mut running = true;
        while running {
            self.event_loop.run_return(|event, _, control_flow| {
                *control_flow = ControlFlow::Poll;
                match event {
                    Event::MainEventsCleared => {
                        let mut app = app.borrow_mut();
                        app.process();
                        app.multiverse
                            .default_universe_mut()
                            .unwrap()
                            .expect_resource_mut::<DesktopAppEvents>()
                            .clear();
                        let _ = self.context_wrapper.swap_buffers();
                        if !app.multiverse.is_running() {
                            running = false;
                        }
                        *control_flow = ControlFlow::Exit;
                    }
                    Event::WindowEvent { event, .. } => match event {
                        WindowEvent::Resized(physical_size) => {
                            self.context_wrapper.resize(physical_size);
                            app.borrow_mut()
                                .multiverse
                                .default_universe_mut()
                                .unwrap()
                                .expect_resource_mut::<DesktopAppEvents>()
                                .push(event.to_static().unwrap());
                        }
                        WindowEvent::CloseRequested => {
                            for universe in app.borrow_mut().multiverse.universes_mut() {
                                universe.expect_resource_mut::<AppLifeCycle>().running = false;
                            }
                        }
                        event => {
                            if let Some(event) = event.to_static() {
                                app.borrow_mut()
                                    .multiverse
                                    .default_universe_mut()
                                    .unwrap()
                                    .expect_resource_mut::<DesktopAppEvents>()
                                    .push(event);
                            }
                        }
                    },
                    _ => {}
                }
            });
        }
        Ok(())
    }
}