/*] Copyright (c) 2009-2011, Charles McGarvey [***************************** **] All rights reserved. * * Distributable under the terms and conditions of the 2-clause BSD license; * see the file COPYING for a complete text of the license. * *****************************************************************************/ #include // exit, srand #include #include "application.hh" #include "fastevents.h" #include "log.hh" #include "settings.hh" #include "video.hh" namespace moof { application::application(settings& settings) : last_update_(timer::ticks()), accum_(SCALAR(0.0)) { unsigned random_seed; if (settings.get("rngseed", random_seed)) srand(random_seed); else srand(time(0)); scalar timestep = SCALAR(80.0); settings.get("timestep", timestep); timestep_ = SCALAR(1.0) / timestep; inverse_timestep_ = timestep; scalar framerate = SCALAR(40.0); settings.get("framerate", framerate); framerate = SCALAR(1.0) / framerate; //update_timer_.init(boost::bind(&application::dispatch_update, //this, _1, _2), timestep_, timer::repeat); //add_timer(update_timer_); game_time_.reset(timestep_); //game_time_.scale(SCALAR(0.5)); draw_timer_.init(boost::bind(&application::dispatch_draw, this, _1, _2), framerate, timer::repeat); add_timer(draw_timer_); //timer::default_source().scale(SCALAR(0.2)); } void application::dispatch_update(timer& timer, scalar t) { event event; while (FE_PollEvent(&event) == 1) { switch (event.type) { case SDL_KEYDOWN: if (event.key.keysym.sym == SDLK_ESCAPE && (SDL_GetModState() & KMOD_CTRL)) { log_warning("escape forced"); exit(1); } break; case SDL_VIDEORESIZE: video::current()->resize(event.resize.w, event.resize.h); break; } handle_event(event); } const int MAX_CONSECUTIVE_UPDATES = 15; log_debug("updating", timer.expiration(), "/", t); scalar deltaTime = t - last_update_; accum_ += deltaTime; int i = 0; while (timestep_ <= accum_ && i < MAX_CONSECUTIVE_UPDATES) { scalar dt = game_time_.step(); update(game_time_.ticks(), dt); accum_ -= timestep_; } last_update_ = t; } void application::dispatch_draw(timer& timer, scalar t) { log_debug("draw", timer.expiration(), "/", t); // XXX temporary thread::main_runloop().run_once(); dispatch_update(timer, t); scalar alpha = accum_ * inverse_timestep_; //alpha = cml::clamp(alpha, SCALAR(-1.0), SCALAR(2.0)); if (alpha < SCALAR(0.0)) log_warning("alpha:", alpha); else if (alpha > SCALAR(1.0)) log_warning("alpha:", alpha); else log_debug("alpha:", alpha); draw(alpha); scalar begin = timer::ticks(); video::current()->swap(t); scalar duration = timer::ticks() - begin; log_debug("flip duration:", duration, begin, timer::ticks()); log_info("draw difference:", t - last_draw_); last_draw_ = t; } } // namespace moof