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
use crate::graphics::{self, GraphicsContext};
use crate::input::{self, InputContext};
use crate::platform::{self, AudioDevice, GraphicsDevice, Window};
use crate::time::{self, TimeContext, Timestep};
use crate::{Result, State};

/// A struct containing all of the 'global' state within the framework.
pub struct Context {
    pub(crate) window: Window,
    pub(crate) device: GraphicsDevice,
    pub(crate) audio: AudioDevice,
    pub(crate) graphics: GraphicsContext,
    pub(crate) input: InputContext,
    pub(crate) time: TimeContext,

    pub(crate) running: bool,
    pub(crate) quit_on_escape: bool,
}

impl Context {
    pub(crate) fn new(settings: &ContextBuilder) -> Result<Context> {
        // This needs to be initialized ASAP to avoid https://github.com/tomaka/rodio/issues/214
        let audio = AudioDevice::new();

        let (window, gl_context, window_width, window_height) = Window::new(settings)?;
        let mut device = GraphicsDevice::new(gl_context)?;

        if settings.debug_info {
            println!("OpenGL Vendor: {}", device.get_vendor());
            println!("OpenGL Renderer: {}", device.get_renderer());
            println!("OpenGL Version: {}", device.get_version());
            println!("GLSL Version: {}", device.get_shading_language_version());
        }

        let graphics = GraphicsContext::new(&mut device, window_width, window_height)?;
        let input = InputContext::new();
        let time = TimeContext::new(settings.timestep);

        Ok(Context {
            window,
            device,

            audio,
            graphics,
            input,
            time,

            running: false,
            quit_on_escape: settings.quit_on_escape,
        })
    }

    /// Runs the game.
    ///
    /// The `init` parameter takes a function or closure that creates a `State`
    /// implementation. A common pattern is to use method references to pass in
    /// your state's constructor directly - see the example below for how this
    /// works.
    ///
    /// # Errors
    ///
    /// If the `State` returns an error from `update` or `draw`, the game will stop
    /// running and this method will return the error.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use tetra::{Context, ContextBuilder, State};
    ///
    /// struct GameState;
    ///
    /// impl GameState {
    ///     fn new(ctx: &mut Context) -> tetra::Result<GameState> {
    ///         Ok(GameState)
    ///     }
    /// }
    ///
    /// impl State for GameState { }
    ///
    /// fn main() -> tetra::Result {
    ///     // Because the signature of GameState::new is
    ///     // (&mut Context) -> tetra::Result<GameState>, you can pass it
    ///     // into run directly.
    ///     ContextBuilder::new("Hello, world!", 1280, 720)
    ///         .build()?
    ///         .run(GameState::new)
    /// }
    /// ```
    ///
    pub fn run<S, F>(&mut self, init: F) -> Result
    where
        S: State,
        F: FnOnce(&mut Context) -> Result<S>,
    {
        let state = &mut init(self)?;

        time::reset(self);

        self.running = true;
        self.window.set_visible(true);

        let mut output = Ok(());

        while self.running {
            if let Err(e) = self.tick(state) {
                output = Err(e);
                break;
            }
        }

        self.window.set_visible(false);

        output
    }

    pub(crate) fn tick<S>(&mut self, state: &mut S) -> Result
    where
        S: State,
    {
        time::tick(self);

        platform::handle_events(self, state)?;

        match time::get_timestep(self) {
            Timestep::Fixed(_) => {
                while time::is_fixed_update_ready(self) {
                    state.update(self)?;
                    input::clear(self);
                }
            }
            Timestep::Variable => {
                state.update(self)?;
                input::clear(self);
            }
        }

        state.draw(self)?;

        graphics::present(self);

        std::thread::yield_now();

        Ok(())
    }
}

/// Settings that can be configured when starting up a game.
#[derive(Debug, Clone)]
pub struct ContextBuilder {
    pub(crate) title: String,
    pub(crate) window_width: i32,
    pub(crate) window_height: i32,
    pub(crate) vsync: bool,
    pub(crate) timestep: Timestep,
    pub(crate) fullscreen: bool,
    pub(crate) maximized: bool,
    pub(crate) minimized: bool,
    pub(crate) resizable: bool,
    pub(crate) borderless: bool,
    pub(crate) show_mouse: bool,
    pub(crate) quit_on_escape: bool,
    pub(crate) debug_info: bool,
}

impl ContextBuilder {
    /// Create a new `ContextBuilder`, with a title and window size.
    pub fn new<S>(title: S, window_width: i32, window_height: i32) -> ContextBuilder
    where
        S: Into<String>,
    {
        ContextBuilder {
            title: title.into(),
            window_width,
            window_height,

            ..ContextBuilder::default()
        }
    }

    /// Sets the title of the window.
    ///
    /// Defaults to `"Tetra"`.
    pub fn title<S>(&mut self, title: S) -> &mut ContextBuilder
    where
        S: Into<String>,
    {
        self.title = title.into();
        self
    }

    /// Sets the size of the window.
    ///
    /// Defaults to `1280` by `720`.
    pub fn size(&mut self, width: i32, height: i32) -> &mut ContextBuilder {
        self.window_width = width;
        self.window_height = height;
        self
    }

    /// Enables or disables vsync.
    ///
    /// Defaults to `true`.
    pub fn vsync(&mut self, vsync: bool) -> &mut ContextBuilder {
        self.vsync = vsync;
        self
    }

    /// Sets the game's timestep.
    ///
    /// Defaults to `Timestep::Fixed(60.0)`.
    pub fn timestep(&mut self, timestep: Timestep) -> &mut ContextBuilder {
        self.timestep = timestep;
        self
    }

    /// Sets whether or not the window should start in fullscreen.
    ///
    /// Defaults to `false`.
    pub fn fullscreen(&mut self, fullscreen: bool) -> &mut ContextBuilder {
        self.fullscreen = fullscreen;
        self
    }

    /// Sets whether or not the window should start maximized.
    ///
    /// Defaults to `false`.
    pub fn maximized(&mut self, maximized: bool) -> &mut ContextBuilder {
        self.maximized = maximized;
        self
    }

    /// Sets whether or not the window should start minimized.
    ///
    /// Defaults to `false`.
    pub fn minimized(&mut self, minimized: bool) -> &mut ContextBuilder {
        self.minimized = minimized;
        self
    }

    /// Sets whether or not the window should be resizable.
    ///
    /// Defaults to `false`.
    pub fn resizable(&mut self, resizable: bool) -> &mut ContextBuilder {
        self.resizable = resizable;
        self
    }

    /// Sets whether or not the window should be borderless.
    ///
    /// Defaults to `false`.
    pub fn borderless(&mut self, borderless: bool) -> &mut ContextBuilder {
        self.borderless = borderless;
        self
    }

    /// Sets whether or not the mouse cursor should be visible when it is within the
    /// game window.
    ///
    /// Defaults to `false`.
    pub fn show_mouse(&mut self, show_mouse: bool) -> &mut ContextBuilder {
        self.show_mouse = show_mouse;
        self
    }

    /// Sets whether or not the game should close when the Escape key is pressed.
    ///
    /// Defaults to `false`.
    pub fn quit_on_escape(&mut self, quit_on_escape: bool) -> &mut ContextBuilder {
        self.quit_on_escape = quit_on_escape;
        self
    }

    /// Sets whether or not the game should print out debug info at startup.
    /// Please include this if you're submitting a bug report!
    pub fn debug_info(&mut self, debug_info: bool) -> &mut ContextBuilder {
        self.debug_info = debug_info;
        self
    }

    /// Builds the context.
    ///
    /// # Errors
    ///
    /// * `TetraError::PlatformError` will be returned if the context cannot be initialized.
    pub fn build(&self) -> Result<Context> {
        Context::new(self)
    }
}

impl Default for ContextBuilder {
    fn default() -> ContextBuilder {
        ContextBuilder {
            title: "Tetra".into(),
            window_width: 1280,
            window_height: 720,
            vsync: true,
            timestep: Timestep::Fixed(60.0),
            fullscreen: false,
            maximized: false,
            minimized: false,
            resizable: false,
            borderless: false,
            show_mouse: false,
            quit_on_escape: false,
            debug_info: false,
        }
    }
}