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
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

#![cfg_attr(feature="clippy", feature(plugin))]
#![cfg_attr(feature="clippy", plugin(clippy))]

#![doc(html_root_url = "http://lukenukem.co.nz/rs_game_framework/")]
extern crate sdl2;
extern crate num_traits;
extern crate serde_json;

#[cfg(feature = "lag")]
use std::time::Duration;

///
/// The manager module contains most I/O objects and interfaces
pub mod manager;

/// The `states` module generally contains 3 states; `menu`, `play`, and `pause`
///
/// * `menu` is what a player will see upon loading the game
/// * `play` is the state which manages all gamplay, including loading assets,
///   initializing objects, managing responses to input, updaing the required
///   objects, and any other related tasks
/// * `pause` is a state which the player should see upon *pausing* a game,
///   it could just display an overlay over the top of the main game state,
///   or it could be more complex with a mini-game, menus, anything.
pub mod states;

/// This is where the main game loop and associated functions live
pub mod game;

/// All resource management structs and functions
pub mod resource;

/// The `components` module is where game entity components live
pub mod components;

/// Utility functions and struct for Vec2d type
pub mod vec2d;

/// Game initialisation and main loop
pub fn main() {
    // An SDL context is needed before we can procceed
    let mut sdl_ctx = sdl2::init().unwrap();
    let mut timer = sdl_ctx.timer().unwrap();

    // TODO: initialize a settings store here, then load settings

    let mut game = game::Game::new(&mut sdl_ctx, 1600, 1200);

    // `fps` is what limits how fast we update the game
    //
    // * 1000 / 60 = 60 frames per second
    // * setting to 0 removes the update speed limit
    let fps: f32 = 1000.0 / 60.0; //FPS 60
    let mut last_tick = timer.ticks();

    let mut lag: f32 = 0.0;
    'running : loop {
        if !game.running() {
            break 'running
        }
        game.handle_events();

        let this_tick = timer.ticks();
        lag += (this_tick - last_tick) as f32;
        last_tick = this_tick;

        while lag >= fps {
            // between 0.001 and 0.005
            game.update(lag * 0.002);
            lag -= fps;
        }
        game.render(lag);
        //println!("{:?}", lag/fps );

        #[cfg(feature = "lag")] // simulate rendering lag
        {
	        std::thread::sleep(Duration::from_millis(20));
	    }
    }
}