/******************************************************************************* 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 "Exception.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) : mInterface(engine), mTimestep(0.01), mPrintFps(false) { #if defined(_WIN32) || defined(__WIN32__) || defined(__TOS_WIN__) || defined(__WINDOWS__) if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_TIMER) != 0) #else if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_EVENTTHREAD) != 0) #endif { const char* error = SDL_GetError(); logError("sdl is complaining: %s", error); throw Exception(ErrorCode::SDL_INIT, error); } if (FE_Init() != 0) { const char* error = FE_GetError(); logError("fast events error: %s", error); throw Exception(ErrorCode::FASTEVENTS_INIT, 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(); Scalar timestep = 80.0; settings.get("timestep", timestep); mTimestep = 1.0 / timestep; Scalar maxFps = 40.0; settings.get("maxfps", maxFps); mDrawRate = 1.0 / maxFps; settings.get("printfps", mPrintFps); mVideo = Video::alloc(name, iconFile); mVideo->makeActive(); } ~Impl() { // the video object must be destroyed before we can shutdown SDL mVideo.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 = mTimestep; mFps = 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 >= mTimestep) { dispatchEvents(); update(totalTime, mTimestep); totalTime += mTimestep; accumulator -= mTimestep; nextStep += mTimestep; } if (ticksNow >= nextStep) { nextStep = ticksNow + mTimestep; } if (ticksNow >= nextDraw) { frameAccum++; if (ticksNow >= nextFpsUpdate) // determine the actual fps { mFps = frameAccum; frameAccum = 0; nextFpsUpdate += 1.0; if (ticksNow >= nextFpsUpdate) { nextFpsUpdate = ticksNow + 1.0; } if (mPrintFps) { logInfo("%d fps", mFps); } } draw(accumulator / mTimestep); mVideo->swap(); nextDraw += mDrawRate; if (ticksNow >= nextDraw) { // we missed some scheduled draws, so reset the schedule nextDraw = ticksNow + mDrawRate; } } // be a good citizen and give back what you don't need Timer::sleep(std::min(std::min(nextStep, nextDraw), Timer::getNextFire()), true); } while (!mStack.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: mVideo->resize(event.resize.w, event.resize.h); break; } handleEvent(event); } } void update(Scalar t, Scalar dt) { for (mStackIt = mStack.begin(); mStackIt != mStack.end(); ++mStackIt) { (*mStackIt)->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 = mStack.rbegin(); it != mStack.rend(); ++it) { (*it)->draw(alpha); } } void handleEvent(const Event& event) { for (mStackIt = mStack.begin(); mStackIt != mStack.end(); ++mStackIt) { if ((*mStackIt)->handleEvent(event)) break; } } void push(LayerP layer) { ASSERT(layer && "cannot push null layer"); mStack.push_front(layer); logInfo(" push: %d", mStack.size()); layer->pushed(mInterface); } LayerP pop() { bool fixIt = false; if (mStack.begin() == mStackIt) fixIt = true; LayerP popped = mStack.front(); mStack.pop_front(); logInfo(" pop: %d", mStack.size()); popped->popped(mInterface); if (fixIt) mStackIt = --mStack.begin(); return popped; } LayerP pop(Layer* layer) { bool fixIt = false; std::list popped; std::list::iterator it; for (it = mStack.begin(); it != mStack.end(); ++it) { popped.push_back(*it); if (it == mStackIt) fixIt = true; if ((*it).get() == layer) { ++it; mStack.erase(mStack.begin(), it); for (it = popped.begin(); it != popped.end(); ++it) { (*it)->popped(mInterface); } if (fixIt) mStackIt = --mStack.begin(); return popped.back(); } } return LayerP(); } void clear() { mStack.clear(); mStackIt = mStack.begin(); logInfo("clear: %d", mStack.size()); } Engine& mInterface; VideoP mVideo; std::list mStack; std::list::iterator mStackIt; Scalar mTimestep; Scalar mDrawRate; long mFps; bool mPrintFps; }; static Engine* instance = 0; Engine::Engine(int argc, char* argv[], const std::string& name, const std::string& iconFile, const std::string& configFile) : mImpl(new Engine::Impl(argc, argv, name, iconFile, configFile, *this)) { instance = this; } Engine& Engine::getInstance() { ASSERT(instance && "dereferencing null pointer"); return *instance; // TODO this has not been completely thought out //static Engine engine; //return engine; } void Engine::run() { return mImpl->run(); } void Engine::setTimestep(Scalar ts) { mImpl->mTimestep = ts; } Scalar Engine::getTimestep() const { return mImpl->mTimestep; } void Engine::setMaxFrameRate(long maxFps) { mImpl->mDrawRate = 1.0 / Scalar(maxFps); } long Engine::getMaxFrameRate() const { return long(1.0 / mImpl->mDrawRate); } Video& Engine::getVideo() const { return *mImpl->mVideo; } long Engine::getFrameRate() const { return mImpl->mFps; } void Engine::push(LayerP layer) { // pass through mImpl->push(layer); } LayerP Engine::pop() { // pass through return mImpl->pop(); } LayerP Engine::pop(Layer* layer) { // pass through return mImpl->pop(layer); } void Engine::clear() { // pass through mImpl->clear(); } } // namespace Mf /** vim: set ts=4 sw=4 tw=80: *************************************************/