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


use sdl2::{self, Sdl};
use sdl2::mixer::Sdl2MixerContext;
use sdl2::render::Renderer;
use sdl2::video::Window;

use std::fmt;
use std::path;

use conf;
use filesystem::Filesystem;
use graphics;
use timer;
use util;
use GameError;
use GameResult;


/// A `Context` is an object that holds on to global resources.
/// It basically tracks hardware state such as the screen, audio
/// system, timers, and so on.  Generally this type is **not** thread-
/// safe and only one `Context` can exist at a time.  Trying to create
/// another one will fail.  In normal usage you don't have to worry
/// about this because it gets created and managed by the `Game` object,
/// and is handed to your `GameState` for use in drawing and such.
///
/// Most functions that interact with the hardware, for instance
/// drawing things, playing sounds, or loading resources (which then
/// need to be transformed into a format the hardware likes) will need
/// to access the `Context`.
pub struct Context<'a> {
    pub sdl_context: Sdl,
    pub mixer_context: Sdl2MixerContext,
    pub renderer: Renderer<'a>,
    pub filesystem: Filesystem,
    pub gfx_context: graphics::GraphicsContext,
    pub event_context: sdl2::EventSubsystem,
    pub timer_context: timer::TimeContext,
    pub dpi: (f32, f32, f32),
    _audio_context: sdl2::AudioSubsystem,
}

impl<'a> fmt::Debug for Context<'a> {
    // TODO: Make this more useful.
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "<Context: {:p}>", self)
    }
}



fn init_audio(sdl_context: &Sdl) -> GameResult<sdl2::AudioSubsystem> {
    sdl_context.audio()
        .map_err(GameError::AudioError)
}

fn init_mixer() -> GameResult<Sdl2MixerContext> {
    let frequency = 44100;
    let format = sdl2::mixer::AUDIO_S16LSB; // signed 16 bit samples, in little-endian byte order
    let channels = 2; // Stereo
    let chunk_size = 1024;
    try!(sdl2::mixer::open_audio(frequency, format, channels, chunk_size));

    let flags = sdl2::mixer::InitFlag::all();
    sdl2::mixer::init(flags).map_err(GameError::AudioError)
}

fn init_window(video: sdl2::VideoSubsystem,
               window_title: &str,
               screen_width: u32,
               screen_height: u32)
               -> GameResult<Window> {

    // Can't hurt
    let _ = sdl2::hint::set("SDL_HINT_RENDER_SCALE_QUALITY", "best");

    video.window(window_title, screen_width, screen_height)
        .position_centered()
        .opengl()
        .build()
        .map_err(|e| GameError::VideoError(format!("{}", e)))
}

/// Sets the window icon from the Conf window_icon field.
/// Assumes an empty string in the conf's window_icon
/// means to do nothing.
fn set_window_icon(context: &mut Context, conf: &conf::Conf) -> GameResult<()> {
    if !conf.window_icon.is_empty() {
        let path = path::Path::new(&conf.window_icon);
        let icon_surface = try!(util::load_surface(context, path));

        if let Some(window) = context.renderer.window_mut() {
            window.set_icon(icon_surface);
        }
    };
    Ok(())
}

impl<'a> Context<'a> {
    /// Tries to create a new Context using settings from the given config file.
    /// Usually called by the engine as part of the set-up code.
    pub fn from_conf(conf: &conf::Conf,
                     fs: Filesystem,
                     sdl_context: Sdl)
                     -> GameResult<Context<'a>> {
        let window_title = &conf.window_title;
        let screen_width = conf.window_width;
        let screen_height = conf.window_height;

        let video = try!(sdl_context.video());
        let window = try!(init_window(video, &window_title, screen_width, screen_height));
        let display_index = try!(window.display_index());
        let dpi = try!(window.subsystem().display_dpi(display_index));

        let renderer = try!(window.renderer()
            .accelerated()
            .build());

        let audio_context = try!(init_audio(&sdl_context));
        let mixer_context = try!(init_mixer());
        let event_context = try!(sdl_context.event());
        let timer_context = timer::TimeContext::new();

        let mut ctx = Context {
            sdl_context: sdl_context,
            mixer_context: mixer_context,
            renderer: renderer,
            filesystem: fs,
            gfx_context: graphics::GraphicsContext::new(),
            dpi: dpi,

            event_context: event_context,
            timer_context: timer_context,

            _audio_context: audio_context,
        };

        try!(set_window_icon(&mut ctx, conf));

        Ok(ctx)
    }


    /// Prints out information on the sound subsystem.
    pub fn print_sound_stats(&self) {
        println!("Allocated {} sound channels",
                 sdl2::mixer::allocate_channels(-1));
        let n = sdl2::mixer::get_chunk_decoders_number();
        println!("available chunk(sample) decoders: {}", n);

        for i in 0..n {
            println!("  decoder {} => {}", i, sdl2::mixer::get_chunk_decoder(i));
        }

        let n = sdl2::mixer::get_music_decoders_number();
        println!("available music decoders: {}", n);
        for i in 0..n {
            println!("  decoder {} => {}", i, sdl2::mixer::get_music_decoder(i));
        }
        println!("query spec => {:?}", sdl2::mixer::query_spec());
    }

    /// Prints out information on the resources subsystem.
    pub fn print_resource_stats(&mut self) {
        match self.filesystem.print_all() {
            Err(e) => println!("Error printing out filesystem info: {}", e),
            _ => (),
        }
    }

    /// Triggers a Quit event.
    pub fn quit(&mut self) -> GameResult<()> {
        let now_dur = timer::get_time_since_start(self);
        let now = timer::duration_to_f64(now_dur);
        let e = sdl2::event::Event::Quit { timestamp: now as u32 };
        // println!("Pushing event {:?}", e);
        self.event_context
            .push_event(e)
            .map_err(GameError::from)
    }
}