/******************************************************************************* Copyright (c) 2009, Charles McGarvey All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *******************************************************************************/ #include #include // exit #include #include #include #include "fastevents.h" #include #include "Dispatcher.hh" #include "Engine.hh" #include "Event.hh" #include "Log.hh" #include "Random.hh" #include "Settings.hh" #include "Timer.hh" #include "Video.hh" namespace Mf { class Engine::Impl { public: Impl(int argc, char* argv[], const std::string& name, const std::string& iconFile, const std::string& configFile, Engine& engine) : interface(engine), timestep(0.01), printFps(false) { #if defined(_WIN32) || defined (_WIN64) || defined(__WIN32__) if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_TIMER) != 0) #else if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_EVENTTHREAD) != 0) #endif { logError("sdl is complaining: %s", SDL_GetError()); throw Exception(Exception::SDL_ERROR); } if (FE_Init() != 0) { logError("fast events error: %s", FE_GetError()); throw Exception(Exception::SDL_ERROR); } alutInit(&argc, argv); Settings& settings = Settings::getInstance(); settings.loadFromFile(configFile); settings.parseArgs(argc, argv); long randomSeed; if (settings.get("rngseed", randomSeed)) setSeed(randomSeed); else setSeed(); settings.get("timestep", timestep); long maxFps = 40; settings.get("maxfps", maxFps); drawRate = 1.0 / Scalar(maxFps); settings.get("printfps", printFps); video = Video::alloc(name, iconFile); video->makeActive(); } ~Impl() { // the video object must be destroyed before we can shutdown SDL video.reset(); alutExit(); FE_Quit(); SDL_Quit(); } /** * The main loop. This just calls dispatchEvents(), update(), and draw() * over and over again. The timing of the update and draw are decoupled. * The actual frame rate is also calculated here. This function will return * the exit code used to stop the loop. */ void run() { Scalar ticksNow = Timer::getTicks(); Scalar nextStep = ticksNow; Scalar nextDraw = ticksNow; Scalar nextFpsUpdate = ticksNow + 1.0; Scalar totalTime = 0.0; Scalar deltaTime = 0.0; Scalar accumulator = timestep; fps = 0; int frameAccum = 0; do { Scalar newTicks = Timer::getTicks(); deltaTime = newTicks - ticksNow; ticksNow = newTicks; if (deltaTime >= 0.25) deltaTime = 0.25; accumulator += deltaTime; Timer::fireIfExpired(ticksNow); while (accumulator >= timestep) { dispatchEvents(); update(totalTime, timestep); totalTime += timestep; accumulator -= timestep; nextStep += timestep; } if (ticksNow >= nextStep) { nextStep = ticksNow + timestep; } if (ticksNow >= nextDraw) { frameAccum++; if (ticksNow >= nextFpsUpdate) // determine the actual fps { fps = frameAccum; frameAccum = 0; nextFpsUpdate += 1.0; if (ticksNow >= nextFpsUpdate) { nextFpsUpdate = ticksNow + 1.0; } if (printFps) { logInfo("%d fps", fps); } } draw(accumulator / timestep); video->swap(); nextDraw += drawRate; if (ticksNow >= nextDraw) { // we missed some scheduled draws, so reset the schedule nextDraw = ticksNow + drawRate; } } // be a good citizen and give back what you don't need Timer::sleep(std::min(std::min(nextStep, nextDraw), Timer::getNextFire()), true); } while (!stack.empty()); } void dispatchEvents() { SDL_Event event; while (FE_PollEvent(&event) == 1) { switch (event.type) { case SDL_KEYDOWN: if (event.key.keysym.sym == SDLK_ESCAPE && (SDL_GetModState() & KMOD_CTRL) ) { // emergency escape exit(0); } break; case SDL_VIDEORESIZE: video->resize(event.resize.w, event.resize.h); break; } handleEvent(event); } } void update(Scalar t, Scalar dt) { for (stackIt = stack.begin(); stackIt != stack.end(); ++stackIt) { (*stackIt)->update(t, dt); } } void draw(Scalar alpha) { // FIXME - this will crash if the layer being drawn pops itself std::list::reverse_iterator it; for (it = stack.rbegin(); it != stack.rend(); ++it) { (*it)->draw(alpha); } } void handleEvent(const Event& event) { for (stackIt = stack.begin(); stackIt != stack.end(); ++stackIt) { if ((*stackIt)->handleEvent(event)) break; } } void pushLayer(LayerP layer) { ASSERT(layer && "cannot push null layer"); stack.push_front(layer); layer->pushed(interface); } void popLayer() { bool fixIt = false; if (stack.begin() == stackIt) fixIt = true; LayerP popped = stack.front(); stack.pop_front(); popped->popped(interface); if (fixIt) stackIt = --stack.begin(); } void popLayer(Layer* layer) { bool fixIt = false; std::list::iterator it; for (it = stack.begin(); it != stack.end(); ++it) { if (it == stackIt) fixIt = true; if ((*it).get() == layer) { ++it; do { LayerP popped = stack.front(); stack.pop_front(); popped->popped(interface); } while (stack.begin() != it); if (fixIt) stackIt = --stack.begin(); return; } } } void clearLayers() { stack.clear(); stackIt = stack.begin(); } Engine& interface; VideoP video; std::list stack; std::list::iterator stackIt; Scalar timestep; Scalar drawRate; long fps; bool printFps; }; static Engine* instance = 0; Engine::Engine(int argc, char* argv[], const std::string& name, const std::string& iconFile, const std::string& configFile) : impl_(new Engine::Impl(argc, argv, name, iconFile, configFile, *this)) { instance = this; } Engine& Engine::getInstance() { ASSERT(instance && "dereferencing null pointer"); return *instance; } void Engine::run() { return impl_->run(); } void Engine::setTimestep(Scalar ts) { impl_->timestep = ts; } Scalar Engine::getTimestep() const { return impl_->timestep; } void Engine::setMaxFrameRate(long maxFps) { impl_->drawRate = 1.0 / Scalar(maxFps); } long Engine::getMaxFrameRate() const { return long(1.0 / impl_->drawRate); } Video& Engine::getVideo() const { return *impl_->video; } long Engine::getFrameRate() const { return impl_->fps; } void Engine::pushLayer(LayerP layer) { // pass through impl_->pushLayer(layer); } void Engine::popLayer() { // pass through impl_->popLayer(); } void Engine::popLayer(Layer* layer) { // pass through impl_->popLayer(layer); } void Engine::clearLayers() { // pass through impl_->clearLayers(); } } // namespace Mf /** vim: set ts=4 sw=4 tw=80: *************************************************/