From: Charles McGarvey Date: Thu, 19 Nov 2009 03:01:06 +0000 (-0700) Subject: minor refactoring and state progress X-Git-Url: https://git.dogcows.com/gitweb?p=chaz%2Fyoink;a=commitdiff_plain;h=a31d65a998121df0651c57bfb68782e2a07d2e2f;hp=31d52677b38d935297d132bdbd956c655cd3feee minor refactoring and state progress --- diff --git a/src/Animation.cc b/src/Animation.cc index b449a0f..aa754ce 100644 --- a/src/Animation.cc +++ b/src/Animation.cc @@ -66,10 +66,12 @@ class Animation::Impl * and the duration that is how long the slide will be shown. */ - struct Frame + class Frame { - unsigned index; ///< Frame index. - Mf::Scalar duration; ///< Frame duration. + friend class Impl; + + unsigned mIndex; ///< Frame index. + Mf::Scalar mDuration; ///< Frame duration. /** * Construction is initialization. The frame data is loaded from a @@ -77,15 +79,15 @@ class Animation::Impl */ Frame(Mf::Script& script, Mf::Script::Value table) : - index(0), - duration(1.0) + mIndex(0), + mDuration(1.0) { table.pushField("index"); - script[-1].get(index); + script[-1].get(mIndex); script.pop(); table.pushField("duration"); - script[-1].get(duration); + script[-1].get(mDuration); script.pop(); } }; @@ -98,10 +100,12 @@ class Animation::Impl struct Sequence { - std::vector frames; ///< List of frames. - Mf::Scalar delay; ///< Scale frame durations. - bool loop; ///< Does the sequence repeat? - std::string next; ///< Next sequence name. + friend class Impl; + + std::vector mFrames; ///< List of frames. + Mf::Scalar mDelay; ///< Scale frame durations. + bool mLoop; ///< Does the sequence repeat? + std::string mNext; ///< Next sequence name. /** * Construction is initialization. The constructor loads sequence @@ -111,19 +115,19 @@ class Animation::Impl */ Sequence(Mf::Script& script, Mf::Script::Value table) : - delay(0.0), - loop(true) + mDelay(0.0), + mLoop(true) { table.pushField("delay"); - script[-1].get(delay); + script[-1].get(mDelay); script.pop(); table.pushField("loop"); - script[-1].get(loop); + script[-1].get(mLoop); script.pop(); table.pushField("next"); - script[-1].get(next); + script[-1].get(mNext); script.pop(); // TODO - sequence class/type not yet implemented @@ -140,7 +144,7 @@ class Animation::Impl script.push(index); frameTable.pushField(); - if (top.isTable()) frames.push_back(Frame(script, top)); + if (top.isTable()) mFrames.push_back(Frame(script, top)); else break; ++index; @@ -224,12 +228,12 @@ class Animation::Impl */ Impl(const std::string& name) : - data(Data::getInstance(name)), - currentSequence(0), - frameCounter(0), - frameIndex(0), - timeAccum(0), - frameDuration(0) {} + mData(Data::getInstance(name)), + mCurrentSequence(0), + mFrameCounter(0), + mFrameIndex(0), + mTimeAccum(0), + mFrameDuration(0) {} /** @@ -242,16 +246,16 @@ class Animation::Impl { std::map::iterator it; - it = data->sequences.find(name); + it = mData->sequences.find(name); - if (it != data->sequences.end()) + if (it != mData->sequences.end()) { - currentSequence = &(*it).second; - frameCounter = 0; - frameIndex = currentSequence->frames[0].index; - timeAccum = 0.0; - frameDuration = currentSequence->delay * - currentSequence->frames[0].duration; + mCurrentSequence = &(*it).second; + mFrameCounter = 0; + mFrameIndex = mCurrentSequence->mFrames[0].mIndex; + mTimeAccum = 0.0; + mFrameDuration = mCurrentSequence->mDelay * + mCurrentSequence->mFrames[0].mDuration; } } @@ -267,62 +271,62 @@ class Animation::Impl void update(Mf::Scalar t, Mf::Scalar dt) { - if (currentSequence) + if (mCurrentSequence) { - timeAccum += dt; + mTimeAccum += dt; - if (timeAccum >= frameDuration) + if (mTimeAccum >= mFrameDuration) { - if (++frameCounter >= currentSequence->frames.size()) + if (++mFrameCounter >= mCurrentSequence->mFrames.size()) { - if (!currentSequence->next.empty()) + if (!mCurrentSequence->mNext.empty()) { - startSequence(currentSequence->next); + startSequence(mCurrentSequence->mNext); } - else if (currentSequence->loop) + else if (mCurrentSequence->mLoop) { - frameCounter = 0; + mFrameCounter = 0; } else { - frameCounter--; - currentSequence = 0; + mFrameCounter--; + mCurrentSequence = 0; } } - frameIndex = currentSequence->frames[frameCounter].index; - timeAccum = frameDuration - timeAccum; - frameDuration = currentSequence->delay * - currentSequence->frames[frameCounter].duration; + mFrameIndex = mCurrentSequence->mFrames[mFrameCounter].mIndex; + mTimeAccum = mFrameDuration - mTimeAccum; + mFrameDuration = mCurrentSequence->mDelay * + mCurrentSequence->mFrames[mFrameCounter].mDuration; } } } - boost::shared_ptr data; ///< Internal data. + boost::shared_ptr mData; ///< Internal data. - Data::Sequence* currentSequence; ///< Active sequence. - unsigned frameCounter; ///< Current frame. - unsigned frameIndex; ///< Index of current frame. - Mf::Scalar timeAccum; ///< Time accumulation. - Mf::Scalar frameDuration; ///< Scaled frame duration. + Data::Sequence* mCurrentSequence; ///< Active sequence. + unsigned mFrameCounter; ///< Current frame. + unsigned mFrameIndex; ///< Index of current frame. + Mf::Scalar mTimeAccum; ///< Time accumulation. + Mf::Scalar mFrameDuration; ///< Scaled frame duration. }; Animation::Animation(const std::string& name) : // pass through - impl_(new Animation::Impl(name)) {} + mImpl(new Animation::Impl(name)) {} void Animation::startSequence(const std::string& name) { // pass through - impl_->startSequence(name); + mImpl->startSequence(name); } void Animation::update(Mf::Scalar t, Mf::Scalar dt) { // pass through - impl_->update(t, dt); + mImpl->update(t, dt); } @@ -333,7 +337,7 @@ void Animation::update(Mf::Scalar t, Mf::Scalar dt) unsigned Animation::getFrame() const { - return impl_->frameIndex; + return mImpl->mFrameIndex; } diff --git a/src/Animation.hh b/src/Animation.hh index 30f0348..5cfd260 100644 --- a/src/Animation.hh +++ b/src/Animation.hh @@ -56,7 +56,7 @@ typedef boost::shared_ptr AnimationP; class Animation : public Mf::Resource { class Impl; - boost::shared_ptr impl_; + boost::shared_ptr mImpl; public: diff --git a/src/Character.cc b/src/Character.cc index e0ce1c0..f12ed5f 100644 --- a/src/Character.cc +++ b/src/Character.cc @@ -44,8 +44,8 @@ struct SpringForce Mf::Scalar d = 50.0; // spring: - //current.force += -15.0 * x - 1.5 * current.velocity; - force = -20.0 * (mag - d) * (x / mag) - 2.0 * state.velocity; + //mState.force += -15.0 * x - 1.5 * mState.velocity; + force = SCALAR(-10.0) * (mag - d) * (x / mag) - 2.0 * state.velocity; return force; } @@ -78,61 +78,46 @@ Character::Character(const std::string& name) : tilemap(name), animation(name) { - current.init(); + mState.init(); - current.mass = 1.0; - current.inverseMass = 1.0 / current.mass; + mState.mass = 1.0; + mState.inverseMass = 1.0 / mState.mass; // forces - current.force = Mf::Vector2(0.0, 0.0); - current.forces.push_back(SpringForce(Mf::Vector2(500.0, 200.0))); - current.forces.push_back(ResistanceForce(2.0)); - current.forces.push_back(Mf::LinearState<2>::GravityForce(-1000.0)); + mState.force = Mf::Vector2(0.0, 0.0); + //mState.forces.push_back(SpringForce(Mf::Vector2(500.0, 200.0))); + mState.forces.push_back(ResistanceForce(2.0)); + //mState.forces.push_back(Mf::LinearState<2>::GravityForce(-100.0)); // starting position - current.position = Mf::Vector2(64.0, 64.0); - current.momentum = Mf::Vector2(0.0, 0.0); - current.recalculate(); + mState.position = Mf::Vector2(64.0, 64.0); + mState.momentum = Mf::Vector2(0.0, 0.0); + mState.recalculate(); - previous = current; + mPrevState = mState; } void Character::update(Mf::Scalar t, Mf::Scalar dt) { - previous = current; + Mf::RigidBody2::update(t, dt); // update physics - //Mf::Vector2 x = current.position - Mf::Vector2(500.0, 200.0); - //Mf::Scalar mag = x.length(); - //Mf::Scalar d = 50.0; - - //// gravity: - //current.force = Mf::Vector2(0.0, -2000.0); - //// spring: - ////current.force += -15.0 * x - 1.5 * current.velocity; - //current.force += -20.0 * (mag - d) * (x / mag) - 2.0 * current.velocity; - //// internal: - //current.force += userForce; - //current.recalculate(); - //std::cout << "force: " << current.momentum << std::endl; - - //Mf::euler(current, t, dt); - - current.integrate(t, dt); animation.update(t, dt); - Mf::Vector3 center(current.position[0], current.position[1], z); - Mf::Vector3 a(current.position[0] - 16.0, current.position[1] - 16.0, z); - Mf::Vector3 b(current.position[0] + 16.0, current.position[1] + 16.0, z); + Mf::Vector3 center(mState.position[0], mState.position[1], z); + Mf::Vector3 a(mState.position[0] - 16.0, mState.position[1] - 16.0, z); + Mf::Vector3 b(mState.position[0] + 16.0, mState.position[1] + 16.0, z); - aabb_.init(a, b); - sphere_.init(center, a); + mAabb.init(a, b); + mSphere.init(center, a); } void Character::draw(Mf::Scalar alpha) const { - Mf::Vector2 position = cml::lerp(previous.position, current.position, alpha); + //Mf::Vector2 position = cml::lerp(mPrevState.position, mState.position, alpha); + Mf::State2 state = getState(alpha); + Mf::Vector2 position = state.position; //glColor3f(1.0f, 1.0f, 1.0f); tilemap.bind(); @@ -141,7 +126,7 @@ void Character::draw(Mf::Scalar alpha) const Tilemap::Orientation orientation = Tilemap::NORMAL; - if (current.velocity[0] < 0.0) orientation = Tilemap::REVERSE; + if (mState.velocity[0] < 0.0) orientation = Tilemap::REVERSE; Mf::Scalar coords[8]; tilemap.getTileCoords(frame, coords, orientation); @@ -172,22 +157,6 @@ void Character::draw(Mf::Scalar alpha) const } -bool Character::isInsideAabb(const Mf::Aabb& aabb) const -{ - // make sure the entity is fully inside the volume - if (!(aabb_.max[0] < aabb.max[0] && - aabb_.min[0] > aabb.min[0] && - aabb_.max[1] < aabb.max[1] && - aabb_.min[1] > aabb.min[1] && - aabb_.max[2] < aabb.max[2] && - aabb_.min[2] > aabb.min[2])) - { - return false; - } - - return true; -} - int Character::getOctant(const Mf::Aabb& aabb) const { int octantNum = -1; @@ -195,28 +164,28 @@ int Character::getOctant(const Mf::Aabb& aabb) const Mf::Plane::Halfspace halfspace; Mf::Plane xy = aabb.getPlaneXY(); - halfspace = xy.intersects(sphere_); + halfspace = xy.intersects(mSphere); if (halfspace == Mf::Plane::INTERSECT) { - halfspace = xy.intersects(aabb_); + halfspace = xy.intersects(mAabb); } if (halfspace == Mf::Plane::POSITIVE) { Mf::Plane xz = aabb.getPlaneXZ(); - halfspace = xz.intersects(sphere_); + halfspace = xz.intersects(mSphere); if (halfspace == Mf::Plane::INTERSECT) { - halfspace = xz.intersects(aabb_); + halfspace = xz.intersects(mAabb); } if (halfspace == Mf::Plane::POSITIVE) { Mf::Plane yz = aabb.getPlaneYZ(); - halfspace = yz.intersects(sphere_); + halfspace = yz.intersects(mSphere); if (halfspace == Mf::Plane::INTERSECT) { - halfspace = yz.intersects(aabb_); + halfspace = yz.intersects(mAabb); } if (halfspace == Mf::Plane::POSITIVE) @@ -231,10 +200,10 @@ int Character::getOctant(const Mf::Aabb& aabb) const else if (halfspace == Mf::Plane::NEGATIVE) { Mf::Plane yz = aabb.getPlaneYZ(); - halfspace = yz.intersects(sphere_); + halfspace = yz.intersects(mSphere); if (halfspace == Mf::Plane::INTERSECT) { - halfspace = yz.intersects(aabb_); + halfspace = yz.intersects(mAabb); } if (halfspace == Mf::Plane::POSITIVE) @@ -250,19 +219,19 @@ int Character::getOctant(const Mf::Aabb& aabb) const else if (halfspace == Mf::Plane::NEGATIVE) { Mf::Plane xz = aabb.getPlaneXZ(); - halfspace = xz.intersects(sphere_); + halfspace = xz.intersects(mSphere); if (halfspace == Mf::Plane::INTERSECT) { - halfspace = xz.intersects(aabb_); + halfspace = xz.intersects(mAabb); } if (halfspace == Mf::Plane::POSITIVE) { Mf::Plane yz = aabb.getPlaneYZ(); - halfspace = yz.intersects(sphere_); + halfspace = yz.intersects(mSphere); if (halfspace == Mf::Plane::INTERSECT) { - halfspace = yz.intersects(aabb_); + halfspace = yz.intersects(mAabb); } if (halfspace == Mf::Plane::POSITIVE) @@ -277,10 +246,10 @@ int Character::getOctant(const Mf::Aabb& aabb) const else if (halfspace == Mf::Plane::NEGATIVE) { Mf::Plane yz = aabb.getPlaneYZ(); - halfspace = yz.intersects(sphere_); + halfspace = yz.intersects(mSphere); if (halfspace == Mf::Plane::INTERSECT) { - halfspace = yz.intersects(aabb_); + halfspace = yz.intersects(mAabb); } if (halfspace == Mf::Plane::POSITIVE) diff --git a/src/Character.hh b/src/Character.hh index 50c3da5..5dfde01 100644 --- a/src/Character.hh +++ b/src/Character.hh @@ -35,7 +35,7 @@ #include #include #include -#include +#include #include #include "Animation.hh" @@ -52,12 +52,8 @@ typedef boost::shared_ptr CharacterP; * includes the heroine herself and the bad guys. */ -struct Character : public Mf::Entity, public Mf::OctreeInsertable +class Character : public Mf::RigidBody2, public Mf::OctreeInsertable { -protected: - - Mf::Vector2 userForce; - public: Character(const std::string& name); @@ -66,17 +62,10 @@ public: virtual void update(Mf::Scalar t, Mf::Scalar dt); virtual void draw(Mf::Scalar alpha) const; - virtual bool isInsideAabb(const Mf::Aabb& aabb) const; virtual int getOctant(const Mf::Aabb& aabb) const; - Mf::State2 previous; - Mf::State2 current; - - Tilemap tilemap; - Animation animation; - - Mf::Aabb aabb_; - Mf::Sphere sphere_; + Tilemap tilemap; + Animation animation; private: diff --git a/src/GameLayer.cc b/src/GameLayer.cc index e7ab9e8..a80946f 100644 --- a/src/GameLayer.cc +++ b/src/GameLayer.cc @@ -40,56 +40,56 @@ GameLayer::GameLayer() : - music("BeatTheCube"), - punchSound("Thump") + mMusic("BeatTheCube"), + mPunchSound("Thump") { - music.setLooping(true); - music.enqueue("NightFusionLoop"); - music.stream(); + mMusic.setLooping(true); + mMusic.enqueue("NightFusionLoop"); + mMusic.stream(); - heroine = Heroine::alloc(); - heroine->animation.startSequence("FlyDiagonallyUp"); + mHeroine = Heroine::alloc(); + mHeroine->animation.startSequence("FlyDiagonallyUp"); Mf::Scalar a[6] = {0.0, 1.5, -0.5, 3.0, -2.0, 1.0}; - interp.init(a, 2.0, Mf::Interpolator::OSCILLATE); + mInterp.init(a, 2.0, Mf::Interpolator::OSCILLATE); - scene = Scene::alloc("Classic"); + mScene = Scene::alloc("Classic"); setProjection(); - hud = Hud::alloc(); + mHud = Hud::alloc(); } void GameLayer::pushed(Mf::Engine& engine) { - engine.push(hud); + engine.push(mHud); } void GameLayer::update(Mf::Scalar t, Mf::Scalar dt) { - camera.update(t, dt); - heroine->update(t, dt); + mCamera.update(t, dt); + mHeroine->update(t, dt); - scene->checkForCollision(*heroine); + mScene->checkForCollision(*mHeroine); - //camera.lookAt(heroine->getSphere().point); - camera.setPosition(Mf::Vector3(-heroine->current.position[0], - -heroine->current.position[1], -256)); + mCamera.setPosition(Mf::Vector3(-mHeroine->getState().position[0], + -mHeroine->getState().position[1], -256)); + //mCamera.lookAt(Mf::promote(mHeroine->getState().position)); - //Mf::Vector3 heroinePosition = Mf::promote(heroine->current.position); + //Mf::Vector3 heroinePosition = Mf::promote(mHeroine->getState().position); //Mf::Sound::setListenerPosition(heroinePosition); - interp.update(t, dt); - hud->setBar1Progress(interp.getState(dt)); - hud->setBar2Progress(1.0 - interp.getState(dt)); + mInterp.update(t, dt); + mHud->setBar1Progress(mInterp.getState(dt)); + mHud->setBar2Progress(1.0 - mInterp.getState(dt)); } void GameLayer::draw(Mf::Scalar alpha) const { - camera.uploadToGL(); + mCamera.uploadToGL(alpha); // DRAW THE SCENE Mf::Texture::resetBind(); @@ -97,9 +97,9 @@ void GameLayer::draw(Mf::Scalar alpha) const glEnableClientState(GL_VERTEX_ARRAY); glEnableClientState(GL_TEXTURE_COORD_ARRAY); - scene->drawIfVisible(alpha, camera.getFrustum()); + mScene->drawIfVisible(alpha, mCamera.getFrustum()); - heroine->draw(alpha); + mHeroine->draw(alpha); } bool GameLayer::handleEvent(const Mf::Event& event) @@ -109,14 +109,14 @@ bool GameLayer::handleEvent(const Mf::Event& event) case SDL_KEYDOWN: if (event.key.keysym.sym == SDLK_SPACE) { - heroine->animation.startSequence("Flattened"); + mHeroine->animation.startSequence("Flattened"); Mf::logInfo("thump!"); - punchSound.play(); + mPunchSound.play(); return true; } else if (event.key.keysym.sym == SDLK_p) { - music.toggle(); + mMusic.toggle(); return true; } else if (event.key.keysym.sym == SDLK_y) @@ -126,11 +126,11 @@ bool GameLayer::handleEvent(const Mf::Event& event) } case SDL_KEYUP: - return heroine->handleEvent(event); + return mHeroine->handleEvent(event); case SDL_MOUSEMOTION: case SDL_MOUSEBUTTONDOWN: - camera.handleEvent(event); + mCamera.handleEvent(event); return true; case SDL_VIDEORESIZE: @@ -150,7 +150,7 @@ void GameLayer::setProjection() void GameLayer::setProjection(Mf::Scalar width, Mf::Scalar height) { - camera.setProjection(cml::rad(60.0), width / height, 32.0, 2500.0); + mCamera.setProjection(cml::rad(60.0), width / height, 32.0, 2500.0); } diff --git a/src/GameLayer.hh b/src/GameLayer.hh index c4c5420..a1b5d6d 100644 --- a/src/GameLayer.hh +++ b/src/GameLayer.hh @@ -75,17 +75,18 @@ private: void setProjection(); void setProjection(Mf::Scalar width, Mf::Scalar height); - Mf::Sound music; - HeroineP heroine; - SceneP scene; - Mf::Sound punchSound; + Mf::Sound mMusic; - Mf::PolynomialInterpolator<5> interp; + HeroineP mHeroine; + SceneP mScene; + Mf::Sound mPunchSound; - Mf::Camera camera; + Mf::PolynomialInterpolator<5> mInterp; - HudP hud; + Mf::Camera mCamera; + + HudP mHud; }; diff --git a/src/Heroine.cc b/src/Heroine.cc index 7a751a0..2071a7b 100644 --- a/src/Heroine.cc +++ b/src/Heroine.cc @@ -43,44 +43,44 @@ bool Heroine::handleEvent(const Mf::Event& event) case SDL_KEYDOWN: if (event.key.keysym.sym == SDLK_a) { - current.force += Mf::Vector2(-force, 0.0); + mState.force += Mf::Vector2(-force, 0.0); return true; } else if (event.key.keysym.sym == SDLK_d) { - current.force += Mf::Vector2(force, 0.0); + mState.force += Mf::Vector2(force, 0.0); return true; } else if (event.key.keysym.sym == SDLK_s) { - current.force += Mf::Vector2(0.0, -force); + mState.force += Mf::Vector2(0.0, -force); return true; } else if (event.key.keysym.sym == SDLK_w) { - current.force += Mf::Vector2(0.0, force); + mState.force += Mf::Vector2(0.0, force); return true; } case SDL_KEYUP: if (event.key.keysym.sym == SDLK_a) { - current.force += Mf::Vector2(force, 0.0); + mState.force += Mf::Vector2(force, 0.0); return true; } else if (event.key.keysym.sym == SDLK_d) { - current.force += Mf::Vector2(-force, 0.0); + mState.force += Mf::Vector2(-force, 0.0); return true; } else if (event.key.keysym.sym == SDLK_s) { - current.force += Mf::Vector2(0.0, force); + mState.force += Mf::Vector2(0.0, force); return true; } else if (event.key.keysym.sym == SDLK_w) { - current.force += Mf::Vector2(0.0, -force); + mState.force += Mf::Vector2(0.0, -force); return true; } } diff --git a/src/Heroine.hh b/src/Heroine.hh index 2fb40c3..7169987 100644 --- a/src/Heroine.hh +++ b/src/Heroine.hh @@ -41,12 +41,13 @@ typedef boost::shared_ptr HeroineP; /** - * Parent class of animate objects with "personalities." This basically - * includes the heroine herself and the bad guys. + * The protagonist. */ -struct Heroine : public Character +class Heroine : public Character { +public: + Heroine(); static HeroineP alloc() diff --git a/src/Hud.cc b/src/Hud.cc index 84b7bc1..a7e141e 100644 --- a/src/Hud.cc +++ b/src/Hud.cc @@ -34,14 +34,14 @@ ProgressBar::ProgressBar(const Tilemap& tilemap, Tilemap::Index index) : - progress_(0.0), - tilemap_(tilemap) + mProgress(0.0), + mTilemap(tilemap) { - tilemap.getTileCoords(index, texCoords_); + tilemap.getTileCoords(index, mTexCoords); - Mf::Scalar half = (texCoords_[2] - texCoords_[0]) / 2.0 + texCoords_[0]; - midCoords_[0] = half - 0.01; - midCoords_[1] = half + 0.01; + Mf::Scalar half = (mTexCoords[2] - mTexCoords[0]) / 2.0 + mTexCoords[0]; + mMidCoords[0] = half - 0.01; + mMidCoords[1] = half + 0.01; } void ProgressBar::resize(const Mf::Rectangle& rect) @@ -49,79 +49,79 @@ void ProgressBar::resize(const Mf::Rectangle& rect) Mf::Scalar height = rect.max[1] - rect.min[1]; Mf::Scalar halfHeight = height / 2.0; - width_ = rect.max[0] - rect.min[0] - height; + mWidth = rect.max[0] - rect.min[0] - height; // assert width > 0 - vertices_[0] = rect.min; - vertices_[1] = Mf::Vector2(rect.min[0] + halfHeight, rect.min[1]); - vertices_[2] = vertices_[1]; - vertices_[3] = Mf::Vector2(rect.min[0] + height, rect.min[1]); - vertices_[4] = Mf::Vector2(rect.min[0] + height, rect.max[1]); - vertices_[5] = Mf::Vector2(rect.min[0] + halfHeight, rect.max[1]); - vertices_[6] = vertices_[5]; - vertices_[7] = Mf::Vector2(rect.min[0], rect.max[1]); + mVertices[0] = rect.min; + mVertices[1] = Mf::Vector2(rect.min[0] + halfHeight, rect.min[1]); + mVertices[2] = mVertices[1]; + mVertices[3] = Mf::Vector2(rect.min[0] + height, rect.min[1]); + mVertices[4] = Mf::Vector2(rect.min[0] + height, rect.max[1]); + mVertices[5] = Mf::Vector2(rect.min[0] + halfHeight, rect.max[1]); + mVertices[6] = mVertices[5]; + mVertices[7] = Mf::Vector2(rect.min[0], rect.max[1]); - setProgress(progress_); + setProgress(mProgress); } void ProgressBar::setProgress(Mf::Scalar progress) { - Mf::Scalar halfHeight = (vertices_[7][1] - vertices_[0][1]) / 2.0; + Mf::Scalar halfHeight = (mVertices[7][1] - mVertices[0][1]) / 2.0; - vertices_[2][0] = vertices_[1][0] + progress * width_; - vertices_[3][0] = vertices_[1][0] + progress * width_ + halfHeight; - vertices_[4][0] = vertices_[1][0] + progress * width_ + halfHeight; - vertices_[5][0] = vertices_[1][0] + progress * width_; + mVertices[2][0] = mVertices[1][0] + progress * mWidth; + mVertices[3][0] = mVertices[1][0] + progress * mWidth + halfHeight; + mVertices[4][0] = mVertices[1][0] + progress * mWidth + halfHeight; + mVertices[5][0] = mVertices[1][0] + progress * mWidth; - progress_ = progress; + mProgress = progress; } void ProgressBar::draw(Mf::Scalar alpha) const { - if (Mf::isEqual(progress_, 0.0)) + if (Mf::isEqual(mProgress, 0.0)) { // don't draw anything if the progress is 0% return; } glColor4f(1.0f, 1.0f, 1.0f, 0.85f); - tilemap_.bind(); + mTilemap.bind(); glBegin(GL_QUADS); - glTexCoord2(texCoords_[0], texCoords_[1]); - glVertex2v(vertices_[0].data()); - glTexCoord2(midCoords_[0], texCoords_[3]); - glVertex2v(vertices_[1].data()); - glTexCoord2(midCoords_[0], texCoords_[5]); - glVertex2v(vertices_[6].data()); - glTexCoord2(texCoords_[6], texCoords_[7]); - glVertex2v(vertices_[7].data()); - - glTexCoord2(midCoords_[0], texCoords_[1]); - glVertex2v(vertices_[1].data()); - glTexCoord2(midCoords_[1], texCoords_[3]); - glVertex2v(vertices_[2].data()); - glTexCoord2(midCoords_[1], texCoords_[5]); - glVertex2v(vertices_[5].data()); - glTexCoord2(midCoords_[0], texCoords_[7]); - glVertex2v(vertices_[6].data()); - - glTexCoord2(midCoords_[1], texCoords_[1]); - glVertex2v(vertices_[2].data()); - glTexCoord2(texCoords_[2], texCoords_[3]); - glVertex2v(vertices_[3].data()); - glTexCoord2(texCoords_[4], texCoords_[5]); - glVertex2v(vertices_[4].data()); - glTexCoord2(midCoords_[1], texCoords_[7]); - glVertex2v(vertices_[5].data()); + glTexCoord2(mTexCoords[0], mTexCoords[1]); + glVertex2v(mVertices[0].data()); + glTexCoord2(mMidCoords[0], mTexCoords[3]); + glVertex2v(mVertices[1].data()); + glTexCoord2(mMidCoords[0], mTexCoords[5]); + glVertex2v(mVertices[6].data()); + glTexCoord2(mTexCoords[6], mTexCoords[7]); + glVertex2v(mVertices[7].data()); + + glTexCoord2(mMidCoords[0], mTexCoords[1]); + glVertex2v(mVertices[1].data()); + glTexCoord2(mMidCoords[1], mTexCoords[3]); + glVertex2v(mVertices[2].data()); + glTexCoord2(mMidCoords[1], mTexCoords[5]); + glVertex2v(mVertices[5].data()); + glTexCoord2(mMidCoords[0], mTexCoords[7]); + glVertex2v(mVertices[6].data()); + + glTexCoord2(mMidCoords[1], mTexCoords[1]); + glVertex2v(mVertices[2].data()); + glTexCoord2(mTexCoords[2], mTexCoords[3]); + glVertex2v(mVertices[3].data()); + glTexCoord2(mTexCoords[4], mTexCoords[5]); + glVertex2v(mVertices[4].data()); + glTexCoord2(mMidCoords[1], mTexCoords[7]); + glVertex2v(mVertices[5].data()); glEnd(); } Hud::Hud() : - bar1_(Tilemap("StatusBars"), 0), - bar2_(Tilemap("StatusBars"), 2), - font_("Font") + mBar1(Tilemap("StatusBars"), 0), + mBar2(Tilemap("StatusBars"), 2), + mFont("Font") { resize(800, 600); } @@ -129,15 +129,15 @@ Hud::Hud() : void Hud::resize(int width, int height) { - cml::matrix_orthographic_RH(projection_, + cml::matrix_orthographic_RH(mProjection, SCALAR(0.0), Mf::Scalar(width), SCALAR(0.0), Mf::Scalar(height), SCALAR(1.0), SCALAR(-1.0), cml::z_clip_neg_one); // position the two progress bars at the top-left of the screen - bar1_.resize(Mf::Rectangle(20, height - 51, + mBar1.resize(Mf::Rectangle(20, height - 51, 0.7 * width, height - 3)); - bar2_.resize(Mf::Rectangle(20, height - 28, + mBar2.resize(Mf::Rectangle(20, height - 28, 0.7 * width, height - 70)); setBar1Progress(0.05); @@ -149,7 +149,7 @@ void Hud::draw(Mf::Scalar alpha) const { glMatrixMode(GL_PROJECTION); glPushMatrix(); - glLoadMatrix(projection_.data()); + glLoadMatrix(mProjection.data()); glMatrixMode(GL_MODELVIEW); glPushMatrix(); @@ -158,8 +158,8 @@ void Hud::draw(Mf::Scalar alpha) const glDisable(GL_DEPTH_TEST); glEnable(GL_BLEND); - bar1_.draw(); - bar2_.draw(); + mBar1.draw(); + mBar2.draw(); glDisable(GL_BLEND); glEnable(GL_DEPTH_TEST); diff --git a/src/Hud.hh b/src/Hud.hh index f386fd4..59f0631 100644 --- a/src/Hud.hh +++ b/src/Hud.hh @@ -42,6 +42,8 @@ #include "Tilemap.hh" +// TODO this stuff is still just hacked up + class ProgressBar : public Mf::Drawable { public: @@ -56,14 +58,14 @@ public: private: - Mf::Scalar progress_; + Mf::Scalar mProgress; - Mf::Vector2 vertices_[8]; - Mf::Scalar width_; + Mf::Vector2 mVertices[8]; + Mf::Scalar mWidth; - Tilemap tilemap_; - Mf::Scalar texCoords_[8]; - Mf::Scalar midCoords_[2]; + Tilemap mTilemap; + Mf::Scalar mTexCoords[8]; + Mf::Scalar mMidCoords[2]; }; @@ -84,13 +86,13 @@ public: void setBar1Progress(Mf::Scalar progress) { // pass through - bar1_.setProgress(progress); + mBar1.setProgress(progress); } void setBar2Progress(Mf::Scalar progress) { // pass through - bar2_.setProgress(progress); + mBar2.setProgress(progress); } void setNumber(unsigned value); @@ -102,13 +104,13 @@ public: private: - ProgressBar bar1_; - ProgressBar bar2_; + ProgressBar mBar1; + ProgressBar mBar2; - unsigned number_; - Tilemap font_; + unsigned mNumber; + Tilemap mFont; - Mf::Matrix4 projection_; + Mf::Matrix4 mProjection; }; diff --git a/src/MainLayer.cc b/src/MainLayer.cc index 2e68785..85828c7 100644 --- a/src/MainLayer.cc +++ b/src/MainLayer.cc @@ -62,9 +62,9 @@ MainLayer::~MainLayer() } -void MainLayer::pushed(Mf::Engine& e) +void MainLayer::pushed(Mf::Engine& engine) { - engine = &e; + mEngine = &engine; //Mf::Scalar coeff[] = {0.0, 1.0}; //Mf::Lerp interp(coeff, 0.25); @@ -74,7 +74,7 @@ void MainLayer::pushed(Mf::Engine& e) //Mf::Transition::alloc(gameLayer, Mf::LayerP(), interp); //engine->push(transition); //engine->push(GameLayer::alloc()); - engine->push(TitleLayer::alloc()); + mEngine->push(TitleLayer::alloc()); } @@ -100,17 +100,17 @@ bool MainLayer::handleEvent(const Mf::Event& event) } else if (event.key.keysym.sym == SDLK_f) { - engine->getVideo().toggleFull(); + mEngine->getVideo().toggleFull(); } else if (event.key.keysym.sym == SDLK_l) { - Mf::Video& video = engine->getVideo(); + Mf::Video& video = mEngine->getVideo(); video.toggleCursorGrab(); video.toggleCursorVisible(); } else if (event.key.keysym.sym == SDLK_y) { - engine->push(GameLayer::alloc()); + mEngine->push(GameLayer::alloc()); } break; @@ -133,7 +133,7 @@ void MainLayer::quit() // the operating system will take care of cleaning up exit(0); #else - engine->clear(); + mEngine->clear(); #endif } @@ -172,7 +172,8 @@ void MainLayer::contextRecreated(const Mf::Notification* note) void printUsage() { - std::cout << "Usage: "PACKAGE" [-h|--help] [-i|--info] [OPTION=VALUE]..." << std::endl + std::cout << "Usage: "PACKAGE" [-h|--help] [-i|--info] [OPTION=VALUE]..." + << std::endl << "The alien-smashing action game." << std::endl << std::endl << "Options:" << std::endl @@ -250,6 +251,8 @@ void goodbye() } +typedef cml::matrix< Mf::Scalar, cml::fixed<5,5>, + cml::col_basis, cml::col_major > Matrix5; int main(int argc, char* argv[]) { diff --git a/src/MainLayer.hh b/src/MainLayer.hh index 44a0f23..9738583 100644 --- a/src/MainLayer.hh +++ b/src/MainLayer.hh @@ -47,8 +47,10 @@ class MainLayer; typedef boost::shared_ptr MainLayerP; -struct MainLayer : public Mf::Layer +class MainLayer : public Mf::Layer { +public: + MainLayer(); ~MainLayer(); @@ -72,7 +74,7 @@ private: void setupGL(); void contextRecreated(const Mf::Notification* note); - Mf::Engine* engine; + Mf::Engine* mEngine; }; diff --git a/src/Makefile.am b/src/Makefile.am index 7c4e61c..cecdac1 100644 --- a/src/Makefile.am +++ b/src/Makefile.am @@ -47,7 +47,7 @@ libmoof_a_SOURCES = \ Moof/Rectangle.hh \ Moof/Resource.cc \ Moof/Resource.hh \ - Moof/RK4.hh \ + Moof/RigidBody.hh \ Moof/Script.hh \ Moof/Settings.cc \ Moof/Settings.hh \ diff --git a/src/Moof/Aabb.cc b/src/Moof/Aabb.cc index df09cdd..17ce663 100644 --- a/src/Moof/Aabb.cc +++ b/src/Moof/Aabb.cc @@ -45,28 +45,35 @@ void Aabb::getOctant(Aabb& octant, int num) const octant.init(Vector3(min[0], min[1], mid[2]), Vector3(mid[0], mid[1], max[2])); break; + case 1: octant.init(Vector3(mid[0], min[1], mid[2]), Vector3(max[0], mid[1], max[2])); break; + case 2: octant.init(mid, max); break; + case 3: octant.init(Vector3(min[0], mid[1], mid[2]), Vector3(mid[0], max[1], max[2])); break; + case 4: octant.init(min, mid); break; + case 5: octant.init(Vector3(mid[0], min[1], min[2]), Vector3(max[0], mid[1], mid[2])); break; + case 6: octant.init(Vector3(mid[0], mid[1], min[2]), Vector3(max[0], max[1], mid[2])); break; + case 7: octant.init(Vector3(min[0], mid[1], min[2]), Vector3(mid[0], max[1], mid[2])); diff --git a/src/Moof/Aabb.hh b/src/Moof/Aabb.hh index 0f7bbb9..6a7e064 100644 --- a/src/Moof/Aabb.hh +++ b/src/Moof/Aabb.hh @@ -47,7 +47,6 @@ struct Aabb : public Cullable, public Drawable Vector3 min; Vector3 max; - Aabb() {} Aabb(const Vector3& a, const Vector3& b) diff --git a/src/Moof/Camera.cc b/src/Moof/Camera.cc index 6b6cfa1..8f313b7 100644 --- a/src/Moof/Camera.cc +++ b/src/Moof/Camera.cc @@ -33,148 +33,134 @@ namespace Mf { -void Camera::setPosition(const Vector3& point) +void Camera::setPosition(const Vector3& position) { - position_ = point; - calculateSecondary(); - //Vector3 coeff[2] = {position_, point}; - //pInterp_.init(coeff, 0.1); + mState.position = position; } + void Camera::setRotation(const Quaternion& rotation) { - rotation_ = rotation; + mState.orientation = rotation; +} + +void Camera::lookAt(const Vector3& point) +{ + // FIXME this doesn't work as expected + cml::quaternion_rotation_aim_at(mState.orientation, mState.position, point, + Vector3(0.0, 1.0, 0.0)); } void Camera::setProjection(const Matrix4& projection) { - projection_ = projection; + mProjection = projection; } void Camera::setProjection(Scalar fovy, Scalar aspect, Scalar abutting, Scalar distant) { - cml::matrix_perspective_yfov_RH(projection_, fovy, aspect, abutting, + cml::matrix_perspective_yfov_RH(mProjection, fovy, aspect, abutting, distant, cml::z_clip_neg_one); - calculateSecondary(); } -void Camera::uploadToGL() const +void Camera::uploadToGL(Scalar alpha) const { + calculate(alpha); + glMatrixMode(GL_PROJECTION); - glMultMatrix(projection_.data()); + glMultMatrix(mProjection.data()); glMatrixMode(GL_MODELVIEW); - glMultMatrix(modelview_.data()); + glMultMatrix(mModelview.data()); } -void Camera::update(Scalar t, Scalar dt) +void Camera::calculate(Scalar alpha) const { - //pInterp_.update(dt); - //position_ = pInterp_.getState(0.0); + State3 state = getState(alpha); - //calculateSecondary(); + cml::matrix_rotation_quaternion(mModelview, state.orientation); + + Matrix4 translate; + cml::matrix_translation(translate, state.position); + + mModelview *= translate; + + mFrustum.init(mModelview, mProjection); } -void Camera::lookAt(const Vector3& point) +void Camera::update(Scalar t, Scalar dt) +{ + RigidBody3::update(t, dt); +} + +void Camera::draw(Scalar alpha) const { - cml::quaternion_rotation_aim_at(rotation_, position_, point, - Vector3(0.0, -1.0, 0.0)); - calculateSecondary(); + mSphere.draw(alpha); } + void Camera::handleEvent(const Event& event) { + const Scalar ds = 50.0; + switch (event.type) { case SDL_KEYDOWN: if (event.key.keysym.sym == SDLK_RIGHT) { - Vector3 vec = position_; - vec[0] -= 50.0; - setPosition(vec); + mState.position[0] -= ds; } else if (event.key.keysym.sym == SDLK_LEFT) { - Vector3 vec = position_; - vec[0] += 50.0; - setPosition(vec); + mState.position[0] += ds; } else if (event.key.keysym.sym == SDLK_UP) { - Vector3 vec = position_; - vec[1] -= 50.0; - setPosition(vec); + mState.position[1] -= ds; } else if (event.key.keysym.sym == SDLK_DOWN) { - Vector3 vec = position_; - vec[1] += 50.0; - setPosition(vec); + mState.position[1] += ds; } else if (event.key.keysym.sym == SDLK_PAGEUP) { - Vector3 vec = position_; - vec[2] += 50.0; - setPosition(vec); + mState.position[2] += ds; } else if (event.key.keysym.sym == SDLK_PAGEDOWN) { - Vector3 vec = position_; - vec[2] -= 50.0; - setPosition(vec); + mState.position[2] -= ds; } break; case SDL_MOUSEMOTION: { - Scalar xrel = cml::rad(Scalar(event.motion.xrel) / 5.0); - Scalar yrel = cml::rad(Scalar(event.motion.yrel) / 5.0); + Scalar xrel = cml::rad(Scalar(event.motion.xrel) / 6.0); + Scalar yrel = cml::rad(Scalar(event.motion.yrel) / 6.0); - Quaternion rotation = rotation_; + Quaternion rotation = mState.orientation; - cml::quaternion_rotate_about_world_x(rotation, yrel); - //rotation_.normalize(); - cml::quaternion_rotate_about_world_y(rotation, xrel); - rotation.normalize(); + cml::quaternion_rotate_about_world_x(rotation, yrel); + //mRotation.normalize(); + cml::quaternion_rotate_about_world_y(rotation, xrel); - setRotation(rotation); - break; + rotation.normalize(); + mState.orientation = rotation; } + break; case SDL_MOUSEBUTTONDOWN: if (event.button.button == SDL_BUTTON_WHEELUP) { - Vector3 vec = position_; - vec[2] += 50.0; - setPosition(vec); + mState.position[2] -= ds; } else if (event.button.button == SDL_BUTTON_WHEELDOWN) { - Vector3 vec = position_; - vec[2] -= 50.0; - setPosition(vec); + mState.position[2] -= ds; } break; } - - calculateSecondary(); -} - -void Camera::calculateSecondary() -{ - cml::matrix_rotation_quaternion(modelview_, rotation_); - - Matrix4 translate; - cml::matrix_translation(translate, position_); - - //modelview_.transpose(); - modelview_ *= translate; - //modelview_ = translate * modelview_; - - frustum_.init(modelview_, projection_); } diff --git a/src/Moof/Camera.hh b/src/Moof/Camera.hh index 827c47f..8e28f54 100644 --- a/src/Moof/Camera.hh +++ b/src/Moof/Camera.hh @@ -31,57 +31,63 @@ #include #include -#include #include +#include namespace Mf { -class Camera +class Camera : public RigidBody3 { - void calculateSecondary(); - public: - Camera() : - position_(0.0, 0.0, 0.0) + + Camera() { - cml::quaternion_rotation_world_y(rotation_, SCALAR(0.0)); - calculateSecondary(); + mState.init(); + mPrevState.init(); + + cml::quaternion_rotation_world_y(mState.orientation, SCALAR(0.0)); } - void setPosition(const Vector3& point); + void setPosition(const Vector3& position); void setRotation(const Quaternion& rotation); + void lookAt(const Vector3& point); + void setProjection(const Matrix4& projection); void setProjection(Scalar fovy, Scalar aspect, Scalar near, Scalar far); - void uploadToGL() const; - - void lookAt(const Vector3& point); + const Matrix4& getModelview() const + { + return mModelview; + } - const Matrix4& getModelviewMatrix() const + const Matrix4& getProjection() const { - return modelview_; + return mProjection; } const Frustum& getFrustum() const { - return frustum_; + return mFrustum; } - void handleEvent(const Event& event); + + void uploadToGL(Scalar alpha = 0) const; + void update(Scalar t, Scalar dt); + void draw(Scalar alpha = 0) const; + void handleEvent(const Event& event); private: - Vector3 position_; - Quaternion rotation_; - Matrix4 projection_; - Matrix4 modelview_; - Frustum frustum_; + void calculate(Scalar alpha) const; + + mutable Matrix4 mModelview; + Matrix4 mProjection; - Lerp3 pInterp_; + mutable Frustum mFrustum; }; diff --git a/src/Moof/Dispatcher.cc b/src/Moof/Dispatcher.cc index 369d451..3207464 100644 --- a/src/Moof/Dispatcher.cc +++ b/src/Moof/Dispatcher.cc @@ -34,15 +34,17 @@ namespace Mf { -struct Dispatcher::Impl +class Dispatcher::Impl { + friend class Dispatcher; + Impl() : - id(1) {} + mId(1) {} Dispatcher::Handler getNewHandler() { - id += 2; - return (Dispatcher::Handler)id; + mId += 2; + return (Dispatcher::Handler)mId; } typedef std::pair Callback; @@ -56,43 +58,56 @@ struct Dispatcher::Impl inline Handler addHandler(const std::string& message, const Function& callback, Handler id) { - callbacks.insert(std::make_pair(message, std::make_pair(id, callback))); - handlers.insert(std::make_pair(id, message)); + mCallbacks.insert(std::make_pair(message, std::make_pair(id, callback))); + mHandlers.insert(std::make_pair(id, message)); return id; } inline void removeHandler(Handler id) { - std::pair matching(handlers.equal_range(id)); + std::pair matching(mHandlers.equal_range(id)); for (HandlerIter it = matching.first; it != matching.second; ++it) { - CallbackIter first = callbacks.find((*it).second); - CallbackIter last = callbacks.end(); + CallbackIter first = mCallbacks.find((*it).second); + CallbackIter last = mCallbacks.end(); for (CallbackIter jt = first; jt != last; ++jt) { if ((*jt).second.first == id) { - callbacks.erase(jt); + mCallbacks.erase(jt); break; } } } - handlers.erase(id); + mHandlers.erase(id); + } + + void dispatch(const std::string& message, const Notification* param) + { + std::pair + callbacks(mCallbacks.equal_range(message)); + + for (CallbackIter it = callbacks.first; it != callbacks.second; ++it) + { + Function callback = (*it).second.second; + callback(param); + } } - unsigned long id; - CallbackLookup callbacks; - HandlerLookup handlers; + unsigned long mId; + + CallbackLookup mCallbacks; + HandlerLookup mHandlers; }; Dispatcher::Dispatcher() : - impl_(new Dispatcher::Impl) {} + mImpl(new Dispatcher::Impl) {} Dispatcher::~Dispatcher() {} @@ -107,34 +122,28 @@ Dispatcher& Dispatcher::getInstance() Dispatcher::Handler Dispatcher::addHandler(const std::string& message, const Function& callback) { - return addHandler(message, callback, impl_->getNewHandler()); + return addHandler(message, callback, mImpl->getNewHandler()); } Dispatcher::Handler Dispatcher::addHandler(const std::string& message, const Function& callback, Handler id) { // pass through - return impl_->addHandler(message, callback, id); + return mImpl->addHandler(message, callback, id); } void Dispatcher::removeHandler(Handler id) { // pass through - return impl_->removeHandler(id); + return mImpl->removeHandler(id); } void Dispatcher::dispatch(const std::string& message, const Notification* param) { - std::pair - callbacks(impl_->callbacks.equal_range(message)); - - for (Impl::CallbackIter it = callbacks.first; it != callbacks.second; ++it) - { - Function callback = (*it).second.second; - callback(param); - } + // pass through + mImpl->dispatch(message, param); } diff --git a/src/Moof/Dispatcher.hh b/src/Moof/Dispatcher.hh index bbce878..7945752 100644 --- a/src/Moof/Dispatcher.hh +++ b/src/Moof/Dispatcher.hh @@ -57,7 +57,7 @@ public: class Dispatcher { class Impl; - boost::shared_ptr impl_; + boost::shared_ptr mImpl; public: @@ -107,7 +107,7 @@ inline void dispatch(const std::string& message, const Notification* param = 0) Dispatcher::getInstance().dispatch(message, param); } -} // namespace dispatch +} // namespace dispatcher } // namespace Mf diff --git a/src/Moof/Engine.cc b/src/Moof/Engine.cc index 16da8d4..ccf2347 100644 --- a/src/Moof/Engine.cc +++ b/src/Moof/Engine.cc @@ -51,12 +51,13 @@ 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) + mInterface(engine), + mTimestep(0.01), + mPrintFps(false) { #if defined(_WIN32) || defined (_WIN64) || defined(__WIN32__) if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_TIMER) != 0) @@ -82,24 +83,24 @@ public: if (settings.get("rngseed", randomSeed)) setSeed(randomSeed); else setSeed(); - Scalar timeStep = 80.0; - settings.get("timestep", timeStep); - timestep = 1.0 / timeStep; + Scalar timestep = 80.0; + settings.get("timestep", timestep); + mTimestep = 1.0 / timestep; Scalar maxFps = 40.0; settings.get("maxfps", maxFps); - drawRate = 1.0 / maxFps; + mDrawRate = 1.0 / maxFps; - settings.get("printfps", printFps); + settings.get("printfps", mPrintFps); - video = Video::alloc(name, iconFile); - video->makeActive(); + mVideo = Video::alloc(name, iconFile); + mVideo->makeActive(); } ~Impl() { // the video object must be destroyed before we can shutdown SDL - video.reset(); + mVideo.reset(); alutExit(); FE_Quit(); @@ -124,9 +125,9 @@ public: Scalar totalTime = 0.0; Scalar deltaTime = 0.0; - Scalar accumulator = timestep; + Scalar accumulator = mTimestep; - fps = 0; + mFps = 0; int frameAccum = 0; do @@ -140,19 +141,19 @@ public: Timer::fireIfExpired(ticksNow); - while (accumulator >= timestep) + while (accumulator >= mTimestep) { dispatchEvents(); - update(totalTime, timestep); + update(totalTime, mTimestep); - totalTime += timestep; - accumulator -= timestep; + totalTime += mTimestep; + accumulator -= mTimestep; - nextStep += timestep; + nextStep += mTimestep; } if (ticksNow >= nextStep) { - nextStep = ticksNow + timestep; + nextStep = ticksNow + mTimestep; } if (ticksNow >= nextDraw) @@ -161,7 +162,7 @@ public: if (ticksNow >= nextFpsUpdate) // determine the actual fps { - fps = frameAccum; + mFps = frameAccum; frameAccum = 0; nextFpsUpdate += 1.0; @@ -170,20 +171,20 @@ public: nextFpsUpdate = ticksNow + 1.0; } - if (printFps) + if (mPrintFps) { - logInfo("%d fps", fps); + logInfo("%d fps", mFps); } } - draw(accumulator / timestep); - video->swap(); + draw(accumulator / mTimestep); + mVideo->swap(); - nextDraw += drawRate; + nextDraw += mDrawRate; if (ticksNow >= nextDraw) { // we missed some scheduled draws, so reset the schedule - nextDraw = ticksNow + drawRate; + nextDraw = ticksNow + mDrawRate; } } @@ -191,7 +192,7 @@ public: Timer::sleep(std::min(std::min(nextStep, nextDraw), Timer::getNextFire()), true); } - while (!stack.empty()); + while (!mStack.empty()); } void dispatchEvents() @@ -212,7 +213,7 @@ public: break; case SDL_VIDEORESIZE: - video->resize(event.resize.w, event.resize.h); + mVideo->resize(event.resize.w, event.resize.h); break; } @@ -223,9 +224,9 @@ public: void update(Scalar t, Scalar dt) { - for (stackIt = stack.begin(); stackIt != stack.end(); ++stackIt) + for (mStackIt = mStack.begin(); mStackIt != mStack.end(); ++mStackIt) { - (*stackIt)->update(t, dt); + (*mStackIt)->update(t, dt); } } @@ -233,7 +234,7 @@ public: { // FIXME - this will crash if the layer being drawn pops itself std::list::reverse_iterator it; - for (it = stack.rbegin(); it != stack.rend(); ++it) + for (it = mStack.rbegin(); it != mStack.rend(); ++it) { (*it)->draw(alpha); } @@ -241,9 +242,9 @@ public: void handleEvent(const Event& event) { - for (stackIt = stack.begin(); stackIt != stack.end(); ++stackIt) + for (mStackIt = mStack.begin(); mStackIt != mStack.end(); ++mStackIt) { - if ((*stackIt)->handleEvent(event)) break; + if ((*mStackIt)->handleEvent(event)) break; } } @@ -251,22 +252,22 @@ public: void push(LayerP layer) { ASSERT(layer && "cannot push null layer"); - stack.push_front(layer); - logInfo(" push: %d", stack.size()); - layer->pushed(interface); + mStack.push_front(layer); + logInfo(" push: %d", mStack.size()); + layer->pushed(mInterface); } LayerP pop() { bool fixIt = false; - if (stack.begin() == stackIt) fixIt = true; + if (mStack.begin() == mStackIt) fixIt = true; - LayerP popped = stack.front(); - stack.pop_front(); - logInfo(" pop: %d", stack.size()); - popped->popped(interface); + LayerP popped = mStack.front(); + mStack.pop_front(); + logInfo(" pop: %d", mStack.size()); + popped->popped(mInterface); - if (fixIt) stackIt = --stack.begin(); + if (fixIt) mStackIt = --mStack.begin(); return popped; } @@ -278,23 +279,23 @@ public: std::list popped; std::list::iterator it; - for (it = stack.begin(); it != stack.end(); ++it) + for (it = mStack.begin(); it != mStack.end(); ++it) { popped.push_back(*it); - if (it == stackIt) fixIt = true; + if (it == mStackIt) fixIt = true; if ((*it).get() == layer) { ++it; - stack.erase(stack.begin(), it); + mStack.erase(mStack.begin(), it); for (it = popped.begin(); it != popped.end(); ++it) { - (*it)->popped(interface); + (*it)->popped(mInterface); } - if (fixIt) stackIt = --stack.begin(); + if (fixIt) mStackIt = --mStack.begin(); return popped.back(); } @@ -305,24 +306,24 @@ public: void clear() { - stack.clear(); - stackIt = stack.begin(); - logInfo("clear: %d", stack.size()); + mStack.clear(); + mStackIt = mStack.begin(); + logInfo("clear: %d", mStack.size()); } - Engine& interface; + Engine& mInterface; - VideoP video; + VideoP mVideo; - std::list stack; - std::list::iterator stackIt; + std::list mStack; + std::list::iterator mStackIt; - Scalar timestep; - Scalar drawRate; + Scalar mTimestep; + Scalar mDrawRate; - long fps; - bool printFps; + long mFps; + bool mPrintFps; }; @@ -330,7 +331,7 @@ 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)) + mImpl(new Engine::Impl(argc, argv, name, iconFile, configFile, *this)) { instance = this; } @@ -340,6 +341,7 @@ Engine& Engine::getInstance() { ASSERT(instance && "dereferencing null pointer"); return *instance; + // TODO this has not been completely thought out //static Engine engine; //return engine; } @@ -347,63 +349,63 @@ Engine& Engine::getInstance() void Engine::run() { - return impl_->run(); + return mImpl->run(); } void Engine::setTimestep(Scalar ts) { - impl_->timestep = ts; + mImpl->mTimestep = ts; } Scalar Engine::getTimestep() const { - return impl_->timestep; + return mImpl->mTimestep; } void Engine::setMaxFrameRate(long maxFps) { - impl_->drawRate = 1.0 / Scalar(maxFps); + mImpl->mDrawRate = 1.0 / Scalar(maxFps); } long Engine::getMaxFrameRate() const { - return long(1.0 / impl_->drawRate); + return long(1.0 / mImpl->mDrawRate); } Video& Engine::getVideo() const { - return *impl_->video; + return *mImpl->mVideo; } long Engine::getFrameRate() const { - return impl_->fps; + return mImpl->mFps; } void Engine::push(LayerP layer) { // pass through - impl_->push(layer); + mImpl->push(layer); } LayerP Engine::pop() { // pass through - return impl_->pop(); + return mImpl->pop(); } LayerP Engine::pop(Layer* layer) { // pass through - return impl_->pop(layer); + return mImpl->pop(layer); } void Engine::clear() { // pass through - impl_->clear(); + mImpl->clear(); } diff --git a/src/Moof/Engine.hh b/src/Moof/Engine.hh index e49f44d..e42510d 100644 --- a/src/Moof/Engine.hh +++ b/src/Moof/Engine.hh @@ -42,8 +42,13 @@ namespace Mf { // forward declarations class Video; -struct Engine +class Engine { + class Impl; + boost::shared_ptr mImpl; + +public: + Engine(int argc, char* argv[], const std::string& name, const std::string& iconFile, const std::string& configFile); ~Engine() {} @@ -77,10 +82,6 @@ struct Engine throw *this; } }; - -private: - class Impl; - boost::shared_ptr impl_; }; diff --git a/src/Moof/Entity.hh b/src/Moof/Entity.hh index dc60010..52cb79d 100644 --- a/src/Moof/Entity.hh +++ b/src/Moof/Entity.hh @@ -48,18 +48,39 @@ class Frustum; /** * Interface for game objects that can be drawn to the screen and have a - * specified size. + * specified volume (take up space). */ class Entity : public Cullable, public Drawable { +protected: + + Aabb mAabb; + Sphere mSphere; + public: + virtual ~Entity() {} virtual void drawIfVisible(Scalar alpha, const Frustum& frustum) const { if (isVisible(frustum)) draw(alpha); } + + virtual bool isVisible(const Frustum& frustum) const + { + return mSphere.isVisible(frustum) && mAabb.isVisible(frustum); + } + + const Aabb& getAabb() const + { + return mAabb; + } + + const Sphere& getSphere() const + { + return mSphere; + } }; diff --git a/src/Moof/Frustum.cc b/src/Moof/Frustum.cc index 51705f2..86e4d5b 100644 --- a/src/Moof/Frustum.cc +++ b/src/Moof/Frustum.cc @@ -41,12 +41,12 @@ void Frustum::init(const Matrix4& modelview, const Matrix4& projection) cml::extract_frustum_planes(modelview, projection, planes, cml::z_clip_neg_one); - planes_[0] = Plane(planes[0][0], planes[0][1], planes[0][2], planes[0][3]); - planes_[1] = Plane(planes[1][0], planes[1][1], planes[1][2], planes[1][3]); - planes_[2] = Plane(planes[2][0], planes[2][1], planes[2][2], planes[2][3]); - planes_[3] = Plane(planes[3][0], planes[3][1], planes[3][2], planes[3][3]); - planes_[4] = Plane(planes[4][0], planes[4][1], planes[4][2], planes[4][3]); - planes_[5] = Plane(planes[5][0], planes[5][1], planes[5][2], planes[5][3]); + mPlanes[0] = Plane(planes[0][0], planes[0][1], planes[0][2], planes[0][3]); + mPlanes[1] = Plane(planes[1][0], planes[1][1], planes[1][2], planes[1][3]); + mPlanes[2] = Plane(planes[2][0], planes[2][1], planes[2][2], planes[2][3]); + mPlanes[3] = Plane(planes[3][0], planes[3][1], planes[3][2], planes[3][3]); + mPlanes[4] = Plane(planes[4][0], planes[4][1], planes[4][2], planes[4][3]); + mPlanes[5] = Plane(planes[5][0], planes[5][1], planes[5][2], planes[5][3]); } void Frustum::init(const Matrix4& modelview, Scalar fovy, Scalar aspect, @@ -73,7 +73,7 @@ Frustum::Collision Frustum::contains(const Aabb& aabb) const for (int j = 0; j < 8; ++j) { - if (planes_[i].intersects(corners[j]) == + if (mPlanes[i].intersects(corners[j]) == Plane::NEGATIVE) { --nInside; @@ -93,7 +93,7 @@ Frustum::Collision Frustum::contains(const Sphere& sphere) const { for (int i = 0; i < 6; ++i) { - Plane::Halfspace halfspace = planes_[i].intersects(sphere); + Plane::Halfspace halfspace = mPlanes[i].intersects(sphere); if (halfspace == Plane::NEGATIVE) return OUTSIDE; else if (halfspace == Plane::INTERSECT) return INTERSECT; diff --git a/src/Moof/Frustum.hh b/src/Moof/Frustum.hh index 87e654f..c708c06 100644 --- a/src/Moof/Frustum.hh +++ b/src/Moof/Frustum.hh @@ -41,7 +41,7 @@ class Sphere; class Frustum { - Plane planes_[6]; // left, right, bottom, top, near, far + Plane mPlanes[6]; // left, right, bottom, top, near, far public: typedef enum diff --git a/src/Moof/Interpolator.hh b/src/Moof/Interpolator.hh index 4de3f69..7ad38fe 100644 --- a/src/Moof/Interpolator.hh +++ b/src/Moof/Interpolator.hh @@ -44,41 +44,42 @@ class Interpolator { if (value > 1.0) { - switch (mode_) + switch (mMode) { case STOP: value = 1.0; - done_ = true; + mDone = true; break; case REPEAT: value -= 1.0; break; case OSCILLATE: value = 2.0 - value; - scale_ *= -1.0; + mScale *= -1.0; break; } } else if (value < 0.0) { - switch (mode_) + switch (mMode) { case STOP: value = 0.0; - done_ = true; + mDone = true; break; case REPEAT: value += 1.0; break; case OSCILLATE: value = -value; - scale_ *= -1.0; + mScale *= -1.0; break; } } } public: + typedef enum { STOP = 0, @@ -88,77 +89,79 @@ public: void init(Scalar seconds = 1.0, Mode mode = STOP) { - scale_ = 1.0 / seconds; - alpha_ = 0.0; + mScale = 1.0 / seconds; + mAlpha = 0.0; setMode(mode); } void setMode(Mode mode) { - mode_ = mode; - done_ = false; + mMode = mode; + mDone = false; } void update(Scalar t, Scalar dt) { - if (!done_) + if (!mDone) { - alpha_ += dt * scale_; - clamp(alpha_); - calculate(alpha_); + mAlpha += dt * mScale; + clamp(mAlpha); + calculate(mAlpha); } } bool isDone() const { - return done_; + return mDone; } virtual void calculate(Scalar alpha) = 0; private: - Scalar alpha_; - Mode mode_; - Scalar scale_; - bool done_; + Scalar mAlpha; + Mode mMode; + Scalar mScale; + bool mDone; }; template class InterpolatorBase : public Interpolator { public: + void init(Scalar seconds = 1.0, Mode mode = STOP) { Interpolator::init(seconds, mode); calculate(0.0); // set value - previous_ = value_; + mPrevious = mValue; } void calculate(Scalar alpha) { - previous_ = value_; - calculate(value_, alpha); + mPrevious = mValue; + calculate(mValue, alpha); } virtual void calculate(T& value, Scalar alpha) = 0; const T& getValue() const { - return value_; + return mValue; } const T getState(Scalar alpha) const { - return cml::lerp(previous_, value_, alpha); + return cml::lerp(mPrevious, mValue, alpha); } private: - T value_; - T previous_; + + T mValue; + T mPrevious; }; @@ -166,6 +169,7 @@ template class PolynomialInterpolator : public InterpolatorBase { public: + PolynomialInterpolator() {} PolynomialInterpolator(const T coefficients[D+1], @@ -192,7 +196,7 @@ public: for (int i = 0; i <= D; ++i) { // n! / (k! * (n - k)!) - coefficients_[i] = coefficients[i] * fac[D] / (fac[i] * fac[D - i]); + mCoefficients[i] = coefficients[i] * fac[D] / (fac[i] * fac[D - i]); } InterpolatorBase::init(seconds, mode); @@ -203,17 +207,18 @@ public: { Scalar beta = 1.0 - alpha; - value = coefficients_[0] * std::pow(beta, D); + value = mCoefficients[0] * std::pow(beta, D); for (int i = 1; i <= D; ++i) { - value += coefficients_[i] * std::pow(beta, D - i) * + value += mCoefficients[i] * std::pow(beta, D - i) * std::pow(alpha, i); } } private: - T coefficients_[D+1]; + + T mCoefficients[D+1]; }; @@ -223,6 +228,7 @@ template class PolynomialInterpolator<1,T> : public InterpolatorBase { public: + PolynomialInterpolator() {} PolynomialInterpolator(const T coefficients[2], Scalar seconds = 1.0, @@ -235,8 +241,8 @@ public: void init(const T coefficients[2], Scalar seconds = 1.0, Interpolator::Mode mode = Interpolator::STOP) { - a_ = coefficients[0]; - b_ = coefficients[1]; + mA = coefficients[0]; + mB = coefficients[1]; InterpolatorBase::init(seconds, mode); } @@ -244,12 +250,13 @@ public: void calculate(T& value, Scalar alpha) { - value = cml::lerp(a_, b_, alpha); + value = cml::lerp(mA, mB, alpha); } private: - T a_; - T b_; + + T mA; + T mB; }; diff --git a/src/Moof/Layer.hh b/src/Moof/Layer.hh index 8ec678d..55e233e 100644 --- a/src/Moof/Layer.hh +++ b/src/Moof/Layer.hh @@ -43,8 +43,10 @@ namespace Mf { class Engine; -struct Layer : public Drawable +class Layer : public Drawable { +public: + virtual ~Layer() {} virtual void pushed(Engine& engine) {} diff --git a/src/Moof/Math.hh b/src/Moof/Math.hh index 6665a19..c63cfe7 100644 --- a/src/Moof/Math.hh +++ b/src/Moof/Math.hh @@ -84,7 +84,7 @@ inline Vector3 promote(const Vector2& vec, Scalar extra = 1.0) -const Scalar EPSILON = 0.000001; +const Scalar EPSILON = SCALAR(0.000001); /** * Check the equality of scalars with a certain degree of error allowed. @@ -96,6 +96,65 @@ inline bool isEqual(Scalar a, Scalar b, Scalar epsilon = EPSILON) } + +// Here are some generic implementations of a few simple integrators. To use, +// you need one type representing the state and another containing the +// derivatives of the primary state variables. The state class must implement +// these methods: +// +// void getDerivative(Derivative_Type& derivative, Scalar absoluteTime); +// void step(const Derivative_Type& derivative, Scalar deltaTime); +// +// Additionally, the derivative class must overload a few operators: +// +// Derivative_Type operator+(const Derivative_Type& other) const +// Derivative_Type operator*(const Derivative_Type& other) const + +template +inline D evaluate(const S& state, Scalar t) +{ + D derivative; + state.getDerivative(derivative, t); + return derivative; +} + +template +inline D evaluate(S state, Scalar t, Scalar dt, const D& derivative) +{ + state.step(derivative, dt); + return evaluate(state, t + dt); +} + + +template +inline void euler(S& state, Scalar t, Scalar dt) +{ + D a = evaluate(state, t); + + state.step(a, dt); +} + +template +inline void rk2(S& state, Scalar t, Scalar dt) +{ + D a = evaluate(state, t); + D b = evaluate(state, t, dt * SCALAR(0.5), a); + + state.step(b, dt); +} + +template +inline void rk4(S& state, Scalar t, Scalar dt) +{ + D a = evaluate(state, t); + D b = evaluate(state, t, dt * SCALAR(0.5), a); + D c = evaluate(state, t, dt * SCALAR(0.5), b); + D d = evaluate(state, t, dt, c); + + state.step((a + (b + c) * SCALAR(2.0) + d) * SCALAR(1.0/6.0), dt); +} + + } // namespace Mf #endif // _MOOF_MATH_HH_ diff --git a/src/Moof/Mippleton.hh b/src/Moof/Mippleton.hh index 7ad1782..a27a6c5 100644 --- a/src/Moof/Mippleton.hh +++ b/src/Moof/Mippleton.hh @@ -54,14 +54,14 @@ class Mippleton typedef std::pair PtrValue; typedef stlplus::hash PtrMap; - static PtrMap ptrs_; - std::string name_; + static PtrMap mPtrMap; + std::string mName; static T* retain(const std::string& name) { - typename PtrMap::iterator it = ptrs_.find(name); + typename PtrMap::iterator it = mPtrMap.find(name); - if (it != ptrs_.end()) + if (it != mPtrMap.end()) { ++((*it).second.first); return (*it).second.second; @@ -69,35 +69,35 @@ class Mippleton else { T* newObj = new T(name); - ptrs_.insert(std::make_pair(name, std::make_pair(1, newObj))); + mPtrMap.insert(std::make_pair(name, std::make_pair(1, newObj))); return newObj; } } static void release(T* obj) { - releaseByName(obj->name_); + releaseByName(obj->mName); } static void releaseByName(const std::string& name) { typename PtrMap::iterator it; - if ((it = ptrs_.find(name)) != ptrs_.end() && --(*it).second.first == 0) + if ((it = mPtrMap.find(name)) != mPtrMap.end() && --(*it).second.first == 0) { delete (*it).second.second; - ptrs_.erase((*it).first); + mPtrMap.erase((*it).first); } } public: explicit Mippleton(const std::string& name) : - name_(name) {} + mName(name) {} const std::string& getName() const { - return name_; + return mName; } static boost::shared_ptr getInstance(const std::string& name) @@ -108,7 +108,7 @@ public: template stlplus::hash< std::string,std::pair,getHash > - Mippleton::ptrs_; + Mippleton::mPtrMap; } // namespace Mf diff --git a/src/Moof/Octree.hh b/src/Moof/Octree.hh index 88dae7a..ca464a5 100644 --- a/src/Moof/Octree.hh +++ b/src/Moof/Octree.hh @@ -52,7 +52,6 @@ struct OctreeInsertable { virtual ~OctreeInsertable() {} - virtual bool isInsideAabb(const Aabb& aabb) const = 0; virtual int getOctant(const Aabb& aabb) const = 0; }; @@ -66,27 +65,16 @@ class Octree : public Entity { std::list objects; - Aabb aabb; - Sphere sphere; - - Node(const Aabb& box) : - aabb(box) + Node(const Aabb& aabb) { - sphere.point = aabb.getCenter(); - sphere.radius = (aabb.min - sphere.point).length(); + mAabb = aabb; + mSphere.point = mAabb.getCenter(); + mSphere.radius = (mAabb.min - mSphere.point).length(); } void draw(Scalar alpha) const { - aabb.draw(alpha); - } - - void drawIfVisible(Scalar alpha, const Frustum& frustum) const - { - if (isVisible(frustum)) - { - aabb.draw(alpha); - } + mAabb.draw(alpha); } void printSize() @@ -110,17 +98,6 @@ class Octree : public Entity if ((*it)->isVisible(frustum)) insertables.push_back(*it); } } - - - bool isVisible(const Frustum& frustum) const - { - if (sphere.isVisible(frustum)) - { - return aabb.isVisible(frustum); - } - - return false; - } }; @@ -137,14 +114,22 @@ private: ASSERT(node.valid() && "invalid node passed"); ASSERT(entity && "null entity passed"); - if (entity->isInsideAabb(node->aabb)) + Aabb entityAabb = entity->getAabb(); + Aabb nodeAabb = node->getAabb(); + + if (!(entityAabb.max[0] < nodeAabb.max[0] && + entityAabb.min[0] > nodeAabb.min[0] && + entityAabb.max[1] < nodeAabb.max[1] && + entityAabb.min[1] > nodeAabb.min[1] && + entityAabb.max[2] < nodeAabb.max[2] && + entityAabb.min[2] > nodeAabb.min[2])) { - return insert_recurse(entity, node); + node->objects.push_back(entity); + return node; } else { - node->objects.push_back(entity); - return node; + return insert_recurse(entity, node); } } @@ -153,7 +138,7 @@ private: ASSERT(node.valid() && "invalid node passed"); ASSERT(entity && "null entity passed"); - int octantNum = entity->getOctant(node->aabb); + int octantNum = entity->getOctant(node->getAabb()); if (octantNum == -1) { node->objects.push_back(entity); @@ -161,12 +146,12 @@ private: } else { - if ((int)tree_.children(node) <= octantNum) + if ((int)mTree.children(node) <= octantNum) { addChild(node, octantNum); } - NodeP child = tree_.child(node, octantNum); + NodeP child = mTree.child(node, octantNum); ASSERT(child.valid() && "expected valid child node"); return insert_recurse(entity, child); @@ -179,10 +164,10 @@ private: Aabb octant; - for (int i = tree_.children(node); i <= index; ++i) + for (int i = mTree.children(node); i <= index; ++i) { - node->aabb.getOctant(octant, i); - tree_.append(node, octant); + node->getAabb().getOctant(octant, i); + mTree.append(node, octant); } } @@ -194,14 +179,14 @@ private: node->printSize(); - int octantNum = entity.getOctant(node->aabb); + int octantNum = entity.getOctant(node->getAabb()); if (octantNum != -1) { node->getAll(insertables); - if (octantNum < (int)tree_.children(node)) + if (octantNum < (int)mTree.children(node)) { - NodeP child = tree_.child(node, octantNum); + NodeP child = mTree.child(node, octantNum); ASSERT(child.valid() && "expected valid child node"); getNearbyObjects(insertables, entity, child); @@ -221,9 +206,9 @@ private: node->getAll(insertables); - for (unsigned i = 0; i < tree_.children(node); ++i) + for (unsigned i = 0; i < mTree.children(node); ++i) { - NodeP child = tree_.child(node, i); + NodeP child = mTree.child(node, i); ASSERT(child.valid() && "expected valid child node"); getAll(insertables, child); @@ -236,11 +221,11 @@ private: ASSERT(node.valid() && "invalid node passed"); // try to cull by sphere - Frustum::Collision collision = frustum.contains(node->sphere); + Frustum::Collision collision = frustum.contains(node->getSphere()); if (collision == Frustum::OUTSIDE) return; // try to cull by aabb - collision = frustum.contains(node->aabb); + collision = frustum.contains(node->getAabb()); if (collision == Frustum::OUTSIDE) return; @@ -253,13 +238,13 @@ private: node->getIfVisible(insertables, frustum); } - if (tree_.children(node) > 0) + if (mTree.children(node) > 0) { if (collision == Frustum::INSIDE) { - for (unsigned i = 0; i < tree_.children(node); ++i) + for (unsigned i = 0; i < mTree.children(node); ++i) { - NodeP child = tree_.child(node, i); + NodeP child = mTree.child(node, i); ASSERT(child.valid() && "expected valid child node"); getAll(insertables, child); @@ -267,9 +252,9 @@ private: } else // collision == Frustum::INTERSECT { - for (unsigned i = 0; i < tree_.children(node); ++i) + for (unsigned i = 0; i < mTree.children(node); ++i) { - NodeP child = tree_.child(node, i); + NodeP child = mTree.child(node, i); ASSERT(child.valid() && "expected valid child node"); getIfVisible(insertables, frustum, child); @@ -279,7 +264,7 @@ private: } - mutable stlplus::ntree tree_; + mutable stlplus::ntree mTree; public: @@ -287,8 +272,8 @@ public: void print(NodeP node) { logInfo("-----"); - logInfo("depth to node: %d", tree_.depth(node)); - logInfo("size of node: %d", tree_.size(node)); + logInfo("depth to node: %d", mTree.depth(node)); + logInfo("size of node: %d", mTree.size(node)); } static Ptr alloc(const Node& rootNode) @@ -298,13 +283,13 @@ public: explicit Octree(const Node& rootNode) { - tree_.insert(rootNode); + mTree.insert(rootNode); } NodeP insert(InsertableP entity) { - return insert(entity, tree_.root()); + return insert(entity, mTree.root()); } void remove(InsertableP entity, NodeP node) @@ -344,8 +329,8 @@ public: void drawIfVisible(Scalar alpha, const Frustum& frustum) const { std::list objects; - //getIfVisible(objects, frustum); - getNearbyObjects(objects, *savedObj); + getIfVisible(objects, frustum); + //getNearbyObjects(objects, *savedObj); typename std::list::const_iterator it; for (it = objects.begin(); it != objects.end(); ++it) @@ -357,13 +342,13 @@ public: void getAll(std::list& insertables) const { - getAll(insertables, tree_.root()); + getAll(insertables, mTree.root()); } void getIfVisible(std::list& insertables, const Frustum& frustum) const { - getIfVisible(insertables, frustum, tree_.root()); + getIfVisible(insertables, frustum, mTree.root()); } mutable const OctreeInsertable* savedObj; @@ -373,7 +358,7 @@ public: const OctreeInsertable& entity) const { logDebug("--- GETTING NEARBY"); - getNearbyObjects(insertables, entity, tree_.root()); + getNearbyObjects(insertables, entity, mTree.root()); logDebug("---"); savedObj = &entity; } diff --git a/src/Moof/RK4.hh b/src/Moof/RK4.hh deleted file mode 100644 index 3293232..0000000 --- a/src/Moof/RK4.hh +++ /dev/null @@ -1,299 +0,0 @@ - -/******************************************************************************* - - 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. - -*******************************************************************************/ - -#ifndef _MOOF_RK4_HH_ -#define _MOOF_RK4_HH_ - -#include - -#include -#include - -#include - - -namespace Mf { - - -// Generic implementations of a few simple integrators. To use, you need one -// type representing the state and another containing the derivatives of the -// primary state variables. The state class must implement these methods: -// -// void getDerivative(Derivative_Type& derivative, Scalar absoluteTime); -// void step(const Derivative_Type& derivative, Scalar deltaTime); -// -// Additionally, the derivative class must overload a few operators: -// -// Derivative_Type operator+(const Derivative_Type& other) const -// Derivative_Type operator*(const Derivative_Type& other) const - -template -inline D evaluate(const S& state, Scalar t) -{ - D derivative; - state.getDerivative(derivative, t); - return derivative; -} - -template -inline D evaluate(S state, Scalar t, Scalar dt, const D& derivative) -{ - state.step(derivative, dt); - return evaluate(state, t + dt); -} - - -template -inline void euler(S& state, Scalar t, Scalar dt) -{ - D a = evaluate(state, t); - - state.step(a, dt); -} - -template -inline void rk2(S& state, Scalar t, Scalar dt) -{ - D a = evaluate(state, t); - D b = evaluate(state, t, dt * SCALAR(0.5), a); - - state.step(b, dt); -} - -template -inline void rk4(S& state, Scalar t, Scalar dt) -{ - D a = evaluate(state, t); - D b = evaluate(state, t, dt * SCALAR(0.5), a); - D c = evaluate(state, t, dt * SCALAR(0.5), b); - D d = evaluate(state, t, dt, c); - - state.step((a + (b + c) * SCALAR(2.0) + d) * SCALAR(1.0/6.0), dt); -} - - -//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - - -template -struct LinearState -{ - typedef cml::vector< Scalar, cml::fixed > Vector; - typedef boost::function ForceFunction; - - // primary - - Vector position; - Vector momentum; - - // secondary - - Vector velocity; - - // user - - Vector force; - std::vector forces; - - // constant - - Scalar mass; - Scalar inverseMass; - - - void recalculateLinear() - { - velocity = momentum * inverseMass; - } - - - struct GravityForce - { - explicit GravityForce(Scalar a = -9.8) - { - force.zero(); - acceleration = a; - } - - const Vector& operator () (const LinearState& state) - { - force[1] = state.mass * acceleration; - return force; - } - - private: - - Vector force; - Scalar acceleration; - }; - - - void init() - { - position.zero(); - momentum.zero(); - - velocity.zero(); - - force.zero(); - forces.clear(); - - mass = SCALAR(1.0); - inverseMass = 1.0 / mass; - } - - - struct Derivative - { - Vector velocity; - Vector force; - - Derivative operator*(Scalar dt) const - { - Derivative derivative; - derivative.velocity = dt * velocity; - derivative.force = dt * force; - return derivative; - } - - Derivative operator+(const Derivative& other) const - { - Derivative derivative; - derivative.velocity = velocity + other.velocity; - derivative.force = force + other.force; - return derivative; - } - }; - - - Vector getForce() const - { - Vector f(force); - - for (size_t i = 0; i < forces.size(); ++i) - { - f += forces[i](*this); - } - - return f; - } - - void getDerivative(Derivative& derivative, Scalar t) const - { - derivative.velocity = velocity; - derivative.force = getForce(); - } - - void step(const Derivative& derivative, Scalar dt) - { - position += dt * derivative.velocity; - momentum += dt * derivative.force; - recalculateLinear(); - } -}; - - -struct RotationalState2 -{ - // primary - - Scalar orientation; - Scalar angularMomentum; - - // secondary - - Scalar angularVelocity; - - // constant - - Scalar inertia; - Scalar inverseInertia; - - - void recalculateRotational() - { - angularVelocity = angularMomentum * inertia; - } - - - struct Derivative - { - Scalar angularVelocity; - Scalar torque; - }; - - void step(const Derivative& derivative, Scalar dt) - { - orientation += dt * derivative.angularVelocity; - angularMomentum += dt * derivative.torque; - recalculateRotational(); - } -}; - -struct RotationalState3 -{ - // primary - - Quaternion orientation; - Vector3 angularMomentum; - - // secondary - - Quaternion spin; - Vector3 angularVelocity; - - // constant - - Scalar inertia; - Scalar inverseInertia; -}; - - -struct State2 : public LinearState<2>, public RotationalState2 -{ - void recalculate() - { - recalculateLinear(); - recalculateRotational(); - } - - void integrate(Scalar t, Scalar dt) - { - rk4,LinearState<2>::Derivative>(*this, t, dt); - } -}; - -struct State3 : public LinearState<3>, public RotationalState3 {}; - - -} // namespace Mf - -#endif // _MOOF_RK4_HH_ - -/** vim: set ts=4 sw=4 tw=80: *************************************************/ - diff --git a/src/Moof/Resource.hh b/src/Moof/Resource.hh index f7d1782..2740fc3 100644 --- a/src/Moof/Resource.hh +++ b/src/Moof/Resource.hh @@ -34,10 +34,11 @@ * Interface for textures, sounds, and other types of resources. */ -#include #include #include +#include + namespace Mf { @@ -49,11 +50,6 @@ namespace Mf { class Resource { public: - struct Exception : public std::runtime_error - { - explicit Exception(const std::string& what_arg) : - std::runtime_error(what_arg) {} - }; virtual ~Resource(); @@ -74,7 +70,20 @@ public: static std::string getPath(const std::string& name); + + struct Exception : public Mf::Exception + { + explicit Exception(unsigned error) : + Mf::Exception(error) {} + + void raise() + { + throw *this; + } + }; + private: + static std::vector searchPaths_; }; diff --git a/src/Moof/RigidBody.hh b/src/Moof/RigidBody.hh index 501f7c9..e7dee38 100644 --- a/src/Moof/RigidBody.hh +++ b/src/Moof/RigidBody.hh @@ -29,39 +29,300 @@ #ifndef _MOOF_RIGIDBODY_HH_ #define _MOOF_RIGIDBODY_HH_ +#include + +#include +#include + +#include #include -#include namespace Mf { +template +struct LinearState +{ + typedef cml::vector< Scalar, cml::fixed > Vector; + typedef boost::function ForceFunction; + + // primary + + Vector position; + Vector momentum; + + // secondary + + Vector velocity; + + // user + + Vector force; + std::vector forces; + + // constant + + Scalar mass; + Scalar inverseMass; + + + void recalculateLinear() + { + velocity = momentum * inverseMass; + } + + + struct GravityForce + { + explicit GravityForce(Scalar a = -9.8) + { + force.zero(); + acceleration = a; + } + + const Vector& operator () (const LinearState& state) + { + force[1] = state.mass * acceleration; + return force; + } + + private: + + Vector force; + Scalar acceleration; + }; + + + void init() + { + position.zero(); + momentum.zero(); + + velocity.zero(); + + force.zero(); + forces.clear(); + + mass = SCALAR(1.0); + inverseMass = 1.0 / mass; + } + + + struct Derivative + { + Vector velocity; + Vector force; + + Derivative operator*(Scalar dt) const + { + Derivative derivative; + derivative.velocity = dt * velocity; + derivative.force = dt * force; + return derivative; + } + + Derivative operator+(const Derivative& other) const + { + Derivative derivative; + derivative.velocity = velocity + other.velocity; + derivative.force = force + other.force; + return derivative; + } + }; + + + Vector getForce() const + { + Vector f(force); + + for (size_t i = 0; i < forces.size(); ++i) + { + f += forces[i](*this); + } + + return f; + } + + void getDerivative(Derivative& derivative, Scalar t) const + { + derivative.velocity = velocity; + derivative.force = getForce(); + } + + void step(const Derivative& derivative, Scalar dt) + { + position += dt * derivative.velocity; + momentum += dt * derivative.force; + recalculateLinear(); + } +}; + + +struct RotationalState2 +{ + // primary + + Scalar orientation; + Scalar angularMomentum; + + // secondary + + Scalar angularVelocity; + + // constant + + Scalar inertia; + Scalar inverseInertia; + + + void recalculateRotational() + { + angularVelocity = angularMomentum * inertia; + } + + + struct Derivative + { + Scalar angularVelocity; + Scalar torque; + }; + + void step(const Derivative& derivative, Scalar dt) + { + orientation += dt * derivative.angularVelocity; + angularMomentum += dt * derivative.torque; + recalculateRotational(); + } +}; + +struct RotationalState3 +{ + // primary + + Quaternion orientation; + Vector3 angularMomentum; + + // secondary + + Quaternion spin; + Vector3 angularVelocity; + + // constant + + Scalar inertia; + Scalar inverseInertia; + + + void recalculateRotational() + { + angularVelocity = angularMomentum * inertia; + } +}; + + +struct State2 : public LinearState<2>, public RotationalState2 +{ + void recalculate() + { + recalculateLinear(); + recalculateRotational(); + } + + void update(Scalar t, Scalar dt) + { + rk4,LinearState<2>::Derivative>(*this, t, dt); + } +}; + +struct State3 : public LinearState<3>, public RotationalState3 +{ + void recalculate() + { + recalculateLinear(); + recalculateRotational(); + } + + void update(Scalar t, Scalar dt) + { + rk4,LinearState<3>::Derivative>(*this, t, dt); + } +}; + + +template +inline T interpolate(const T& a, const T& b, Scalar alpha) +{ + return cml::lerp(a, b, alpha); +} + +template <> +inline State2 interpolate(const State2& a, const State2& b, Scalar alpha) +{ + State2 state(b); + state.position = interpolate(a.position, b.position, alpha); + state.momentum = interpolate(a.momentum, b.momentum, alpha); + state.orientation = interpolate(a.orientation, b.orientation, alpha); + state.angularMomentum = interpolate(a.angularMomentum, b.angularMomentum, + alpha); + return state; +} + +template <> +inline State3 interpolate(const State3& a, const State3& b, Scalar alpha) +{ + State3 state(b); + state.position = interpolate(a.position, b.position, alpha); + state.momentum = interpolate(a.momentum, b.momentum, alpha); + state.orientation = cml::slerp(a.orientation, b.orientation, alpha); + state.angularMomentum = interpolate(a.angularMomentum, b.angularMomentum, + alpha); + return state; +} + + + /** - * Interface for physical things with mass, momentum, yada yada yada. + * Interface for anything that can move. */ -template -class RigidBody +template +class RigidBody : public Entity { +protected: + + T mState; + T mPrevState; + public: + virtual ~RigidBody() {} virtual void update(Scalar t, Scalar dt) { - prevState_ = currentState_; - currentState_.integrate(t, dt); + mPrevState = mState; + mState.update(t, dt); } - T getInterpolatedState(Scalar alpha) const + const T& getState() const { - return currentState_.interpolate(alpha, prevState_); + return mState; } -protected: - T prevState_; - T currentState_; + T getState(Scalar alpha) const + { + return interpolate(mPrevState, mState, alpha); + } + + const T& getLastState() const + { + return mPrevState; + } }; +typedef RigidBody RigidBody2; +typedef RigidBody RigidBody3; + } // namespace Mf @@ -69,4 +330,3 @@ protected: /** vim: set ts=4 sw=4 tw=80: *************************************************/ - diff --git a/src/Moof/Script.hh b/src/Moof/Script.hh index 2fe275e..4db93d5 100644 --- a/src/Moof/Script.hh +++ b/src/Moof/Script.hh @@ -468,15 +468,15 @@ struct Script Script() : - state_(luaL_newstate()) + mState(luaL_newstate()) { - lua_pushlightuserdata(state_, this); - lua_setfield(state_, LUA_REGISTRYINDEX, "_script_obj"); + lua_pushlightuserdata(mState, this); + lua_setfield(mState, LUA_REGISTRYINDEX, "_script_obj"); } ~Script() { - if (isMainThread_) lua_close(state_); + if (mIsMainThread) lua_close(mState); } @@ -488,24 +488,24 @@ struct Script void importStandardLibraries() { - luaL_openlibs(state_); + luaL_openlibs(mState); } void importFunction(const std::string& name, const Function& function) { push(function); - lua_setglobal(state_, name.c_str()); + lua_setglobal(mState, name.c_str()); } STATUS doString(const std::string& commands) { - return (STATUS)luaL_dostring(state_, commands.c_str()); + return (STATUS)luaL_dostring(mState, commands.c_str()); } STATUS doFile(const std::string& file) { - return (STATUS)luaL_dofile(state_, file.c_str()); + return (STATUS)luaL_dofile(mState, file.c_str()); } @@ -515,32 +515,32 @@ struct Script Script pushNewThread() { - return Script(state_); + return Script(mState); } void pushThread() { - lua_pushthread(state_); + lua_pushthread(mState); } STATUS resume(int nargs) { - return (STATUS)lua_resume(state_, nargs); + return (STATUS)lua_resume(mState, nargs); } STATUS getStatus() const { - return (STATUS)lua_status(state_); + return (STATUS)lua_status(mState); } int yield(int results) { - return lua_yield(state_, results); + return lua_yield(mState, results); } bool isMainThread() const { - return isMainThread_; + return mIsMainThread; } @@ -556,7 +556,7 @@ struct Script void throwError() { - lua_error(state_); + lua_error(mState); } @@ -566,22 +566,22 @@ struct Script Value getGlobalTable() const { - return Value(state_, GLOBALS); + return Value(mState, GLOBALS); } Value getRegistryTable() const { - return Value(state_, REGISTRY); + return Value(mState, REGISTRY); } Value getEnvironmentTable() const { - return Value(state_, ENVIRONMENT); + return Value(mState, ENVIRONMENT); } Value getTop() const { - return Value(state_, lua_gettop(state_)); + return Value(mState, lua_gettop(mState)); } /** @@ -590,12 +590,12 @@ struct Script int getSize() const { - return lua_gettop(state_); + return lua_gettop(mState); } void setSize(int size) { - lua_settop(state_, size); + lua_settop(mState, size); } void clear() @@ -614,7 +614,7 @@ struct Script bool checkStack(int extra) { - return (bool)lua_checkstack(state_, extra); + return (bool)lua_checkstack(mState, extra); } @@ -624,7 +624,7 @@ struct Script void concat(int n) { - lua_concat(state_, n); + lua_concat(mState, n); } @@ -635,77 +635,77 @@ struct Script template void push(T value) { - lua_pushinteger(state_, lua_Integer(value)); + lua_pushinteger(mState, lua_Integer(value)); } void push(bool value) { - lua_pushboolean(state_, int(value)); + lua_pushboolean(mState, int(value)); } void push(float value) { - lua_pushnumber(state_, (lua_Number)value); + lua_pushnumber(mState, (lua_Number)value); } void push(double value) { - lua_pushnumber(state_, (lua_Number)value); + lua_pushnumber(mState, (lua_Number)value); } void push(const std::string& value) { - lua_pushlstring(state_, value.c_str(), value.length()); + lua_pushlstring(mState, value.c_str(), value.length()); } void push(const char* value) { - lua_pushstring(state_, value); + lua_pushstring(mState, value); } void push(const char* value, size_t length) { - lua_pushlstring(state_, value, length); + lua_pushlstring(mState, value, length); } void push(const Function& function) { - functions_.push_back(function); + mFunctions.push_back(function); - lua_pushlightuserdata(state_, (void*)&functions_.back()); - lua_pushcclosure(state_, dispatchCall, 1); + lua_pushlightuserdata(mState, (void*)&mFunctions.back()); + lua_pushcclosure(mState, dispatchCall, 1); } void push(void* data) { - lua_pushlightuserdata(state_, data); + lua_pushlightuserdata(mState, data); } void pushNil() { - lua_pushnil(state_); + lua_pushnil(mState); } void pushFromThread(Script& thread, int n) { - lua_xmove(thread.state_, state_, n); + lua_xmove(thread.mState, mState, n); } STATUS pushCode(const std::string& filename) { - return (STATUS)luaL_loadfile(state_, filename.c_str()); + return (STATUS)luaL_loadfile(mState, filename.c_str()); } STATUS pushCode(const std::string& name, const char* buffer, size_t size) { - return (STATUS)luaL_loadbuffer(state_, buffer, size, name.c_str()); + return (STATUS)luaL_loadbuffer(mState, buffer, size, name.c_str()); } void* pushNewData(size_t size) { - return lua_newuserdata(state_, size); + return lua_newuserdata(mState, size); } void pushNewTable() { - lua_newtable(state_); + lua_newtable(mState); } @@ -718,7 +718,7 @@ struct Script STATUS call(int nargs, int nresults = LUA_MULTRET) { - return (STATUS)lua_pcall(state_, nargs, nresults, 0); + return (STATUS)lua_pcall(mState, nargs, nresults, 0); } @@ -728,7 +728,7 @@ struct Script void pop(int n = 1) { - lua_pop(state_, n); + lua_pop(mState, n); } @@ -738,7 +738,7 @@ struct Script Value operator [] (int index) const { - return Value(state_, index); + return Value(mState, index); } @@ -748,12 +748,12 @@ struct Script void get(const std::string& field, int index = GLOBALS) const { - lua_getfield(state_, index, field.c_str()); + lua_getfield(mState, index, field.c_str()); } void set(const std::string& field, int index = GLOBALS) { - lua_setfield(state_, index, field.c_str()); + lua_setfield(mState, index, field.c_str()); } @@ -763,34 +763,34 @@ struct Script void collectAll() { - lua_gc(state_, LUA_GCCOLLECT, 0); + lua_gc(mState, LUA_GCCOLLECT, 0); } void stopCollector() { - lua_gc(state_, LUA_GCSTOP, 0); + lua_gc(mState, LUA_GCSTOP, 0); } void restartCollector() { - lua_gc(state_, LUA_GCRESTART, 0); + lua_gc(mState, LUA_GCRESTART, 0); } int getUsedMemory() const { // in kilobytes - return lua_gc(state_, LUA_GCCOUNT, 0); + return lua_gc(mState, LUA_GCCOUNT, 0); } void collectStep(int step) { - lua_gc(state_, LUA_GCSTEP, step); + lua_gc(mState, LUA_GCSTEP, step); } void tuneCollector(int pause, int step) { - lua_gc(state_, LUA_GCSETPAUSE, pause); - lua_gc(state_, LUA_GCSETSTEPMUL, step); + lua_gc(mState, LUA_GCSETPAUSE, pause); + lua_gc(mState, LUA_GCSETSTEPMUL, step); } @@ -810,8 +810,8 @@ struct Script private: Script(lua_State* state) : - state_(lua_newthread(state)), - isMainThread_(false) {} + mState(lua_newthread(state)), + mIsMainThread(false) {} static int dispatchCall(lua_State* state) { @@ -825,9 +825,9 @@ private: return (*function)(*script); } - lua_State* state_; - bool isMainThread_; - std::list functions_; + lua_State* mState; + bool mIsMainThread; + std::list mFunctions; }; diff --git a/src/Moof/Settings.cc b/src/Moof/Settings.cc index 5a321b0..5a4f991 100644 --- a/src/Moof/Settings.cc +++ b/src/Moof/Settings.cc @@ -46,7 +46,7 @@ void Settings::parseArgs(int argc, char* argv[]) { for (int i = 1; i < argc; ++i) { - script_.doString(argv[i]); + mScript.doString(argv[i]); } } @@ -74,12 +74,12 @@ void Settings::loadFromFiles(const std::vector& filePaths) boost::replace_all(path, "$HOME", home); } - if (script_.doFile(path) != Script::SUCCESS) + if (mScript.doFile(path) != Script::SUCCESS) { std::string str; - script_[-1].get(str); + mScript[-1].get(str); logScript("%s", str.c_str()); - script_.clear(); + mScript.clear(); } } } diff --git a/src/Moof/Settings.hh b/src/Moof/Settings.hh index dc29deb..42e7d3a 100644 --- a/src/Moof/Settings.hh +++ b/src/Moof/Settings.hh @@ -49,11 +49,12 @@ namespace Mf { class Settings { public: + Settings() : - globals_(script_.getGlobalTable()), - top_(script_[-1]) + mGlobals(mScript.getGlobalTable()), + mTop(mScript[-1]) { - importLogScript(script_); + importLogScript(mScript); } // get global instance @@ -68,8 +69,9 @@ public: bool get(const std::string& key, T& value); private: - Script script_; - Script::Value globals_, top_; + + Script mScript; + Script::Value mGlobals, mTop; }; @@ -79,24 +81,24 @@ bool Settings::get(const std::string& key, T& value) std::vector fields; boost::split(fields, key, boost::is_any_of(".")); - globals_.pushCopy(); + mGlobals.pushCopy(); std::vector::iterator it; for (it = fields.begin(); it != fields.end(); ++it) { - if (top_.isTable()) + if (mTop.isTable()) { - top_.pushField(*it); + mTop.pushField(*it); } else { - script_.clear(); + mScript.clear(); return false; } } - bool got = top_.get(value); - script_.clear(); + bool got = mTop.get(value); + mScript.clear(); return got; } diff --git a/src/Moof/Sound.cc b/src/Moof/Sound.cc index 4cb2913..27905ba 100644 --- a/src/Moof/Sound.cc +++ b/src/Moof/Sound.cc @@ -46,8 +46,9 @@ namespace Mf { -struct Sound::Impl +class Sound::Impl { +public: static ALenum getAudioFormat(const vorbis_info* audioInfo) { @@ -55,50 +56,51 @@ struct Sound::Impl else return AL_FORMAT_STEREO16; } + class Buffer; typedef boost::shared_ptr BufferP; class Buffer : public Mippleton { - OggVorbis_File oggStream; - ALenum audioFormat; - ALsizei audioFreq; - std::vector objects; + OggVorbis_File mOggStream; + ALenum mFormat; + ALsizei mFreq; + std::vector mObjects; public: Buffer(const std::string& name) : Mippleton(name) { - oggStream.datasource = 0; + mOggStream.datasource = 0; openFile(); } ~Buffer() { - while (!objects.empty()) + while (!mObjects.empty()) { - alDeleteBuffers(1, &objects.back()); - objects.pop_back(); + alDeleteBuffers(1, &mObjects.back()); + mObjects.pop_back(); } - if (oggStream.datasource) + if (mOggStream.datasource) { - ov_clear(&oggStream); + ov_clear(&mOggStream); } } void openFile() { - if (oggStream.datasource) + if (mOggStream.datasource) { - ov_clear(&oggStream); - oggStream.datasource = 0; + ov_clear(&mOggStream); + mOggStream.datasource = 0; } std::string filePath = Sound::getPath(getName()); - int result = ov_fopen((char*)filePath.c_str(), &oggStream); + int result = ov_fopen((char*)filePath.c_str(), &mOggStream); if (result < 0) { @@ -107,9 +109,9 @@ struct Sound::Impl throw Exception(Exception::BAD_AUDIO_FORMAT); } - vorbis_info* vorbisInfo = ov_info(&oggStream, -1); - audioFormat = getAudioFormat(vorbisInfo); - audioFreq = vorbisInfo->rate; + vorbis_info* vorbisInfo = ov_info(&mOggStream, -1); + mFormat = getAudioFormat(vorbisInfo); + mFreq = vorbisInfo->rate; logDebug(" channels: %d", vorbisInfo->channels); logDebug(" frequency: %d", vorbisInfo->rate); @@ -118,8 +120,8 @@ struct Sound::Impl void loadAll(ALuint source) { - if (!oggStream.datasource) openFile(); - if (!oggStream.datasource) return; + if (!mOggStream.datasource) openFile(); + if (!mOggStream.datasource) return; char data[BUFFER_SIZE]; int size = 0; @@ -127,7 +129,7 @@ struct Sound::Impl for (;;) { int section; - int result = ov_read(&oggStream, data + size, + int result = ov_read(&mOggStream, data + size, BUFFER_SIZE - size, 0, 2, 1, §ion); if (result > 0) @@ -150,29 +152,29 @@ struct Sound::Impl ALuint obj; alGenBuffers(1, &obj); - alBufferData(obj, audioFormat, data, size, audioFreq); + alBufferData(obj, mFormat, data, size, mFreq); - objects.push_back(obj); + mObjects.push_back(obj); alSourcei(source, AL_BUFFER, obj); // don't need this anymore - ov_clear(&oggStream); - oggStream.datasource = 0; + ov_clear(&mOggStream); + mOggStream.datasource = 0; } void beginStream(ALuint source, int nBuffers = 8) { - if (!oggStream.datasource) openFile(); - if (!oggStream.datasource) return; + if (!mOggStream.datasource) openFile(); + if (!mOggStream.datasource) return; ALuint objs[nBuffers]; alGenBuffers(nBuffers, objs); for (int i = 0; i < nBuffers; ++i) { - objects.push_back(objs[i]); + mObjects.push_back(objs[i]); stream(objs[i]); } @@ -189,10 +191,10 @@ struct Sound::Impl StreamStatus stream(ALuint buffer) { std::vector::iterator it = - std::find(objects.begin(), objects.end(), buffer); + std::find(mObjects.begin(), mObjects.end(), buffer); // that buffer doesn't belong to us - if (it == objects.end()) return STREAM_WRONG; + if (it == mObjects.end()) return STREAM_WRONG; char data[BUFFER_SIZE]; int size = 0; @@ -200,7 +202,7 @@ struct Sound::Impl while (size < BUFFER_SIZE) { int section; - int result = ov_read(&oggStream, data + size, + int result = ov_read(&mOggStream, data + size, BUFFER_SIZE - size, 0, 2, 1, §ion); if (result > 0) @@ -216,15 +218,15 @@ struct Sound::Impl if (size == 0) return STREAM_EOF; - alBufferData(buffer, audioFormat, data, size, audioFreq); + alBufferData(buffer, mFormat, data, size, mFreq); return STREAM_OK; } inline void rewind() { - if (!oggStream.datasource) openFile(); - else ov_raw_seek(&oggStream, 0); + if (!mOggStream.datasource) openFile(); + else ov_raw_seek(&mOggStream, 0); } @@ -234,16 +236,16 @@ struct Sound::Impl // clear any openal errors alGetError(); - while (!objects.empty()) + while (!mObjects.empty()) { - ALuint buffer = objects.back(); + ALuint buffer = mObjects.back(); alDeleteBuffers(1, &buffer); // if an error occured, the buffer was not deleted because it's // still in use by some source if (alGetError() != AL_NO_ERROR) return false; - objects.pop_back(); + mObjects.pop_back(); } return true; @@ -252,56 +254,56 @@ struct Sound::Impl Impl(const std::string& name) : - buffer_(Buffer::getInstance(name)), - playing_(false), - looping_(false) + mBuffer(Buffer::getInstance(name)), + mIsPlaying(false), + mIsLooping(false) { ALfloat zero[] = {0.0f, 0.0f, 0.0f}; - alGenSources(1, &source_); + alGenSources(1, &mSource); - alSourcef(source_, AL_PITCH, 1.0f); - alSourcef(source_, AL_GAIN, 1.0f); - alSourcefv(source_, AL_POSITION, zero); - alSourcefv(source_, AL_VELOCITY, zero); + alSourcef(mSource, AL_PITCH, 1.0f); + alSourcef(mSource, AL_GAIN, 1.0f); + alSourcefv(mSource, AL_POSITION, zero); + alSourcefv(mSource, AL_VELOCITY, zero); } ~Impl() { - alDeleteSources(1, &source_); + alDeleteSources(1, &mSource); } void play() { ALenum type; - alGetSourcei(source_, AL_SOURCE_TYPE, &type); + alGetSourcei(mSource, AL_SOURCE_TYPE, &type); if (type != AL_STATIC) { - buffer_->loadAll(source_); + mBuffer->loadAll(mSource); } - alSourcei(source_, AL_LOOPING, looping_); - alSourcePlay(source_); - playing_ = true; + alSourcei(mSource, AL_LOOPING, mIsLooping); + alSourcePlay(mSource); + mIsPlaying = true; } void stream() { ALenum type; - alGetSourcei(source_, AL_SOURCE_TYPE, &type); + alGetSourcei(mSource, AL_SOURCE_TYPE, &type); - alSourcei(source_, AL_BUFFER, AL_NONE); - buffer_->rewind(); - buffer_->beginStream(source_); + alSourcei(mSource, AL_BUFFER, AL_NONE); + mBuffer->rewind(); + mBuffer->beginStream(mSource); - alSourcei(source_, AL_LOOPING, AL_FALSE); - alSourcePlay(source_); - playing_ = true; + alSourcei(mSource, AL_LOOPING, AL_FALSE); + alSourcePlay(mSource); + mIsPlaying = true; - streamTimer.init(boost::bind(&Impl::streamUpdate, this, _1, _2), 1.0, + mStreamTimer.init(boost::bind(&Impl::streamUpdate, this, _1, _2), 1.0, Timer::REPEAT); } @@ -309,53 +311,53 @@ struct Sound::Impl { ALint finished = 0; - alGetSourcei(source_, AL_BUFFERS_PROCESSED, &finished); + alGetSourcei(mSource, AL_BUFFERS_PROCESSED, &finished); while (finished-- > 0) { ALuint buffer; - alSourceUnqueueBuffers(source_, 1, &buffer); + alSourceUnqueueBuffers(mSource, 1, &buffer); - Buffer::StreamStatus status = buffer_->stream(buffer); + Buffer::StreamStatus status = mBuffer->stream(buffer); if (status == Buffer::STREAM_OK) { - alSourceQueueBuffers(source_, 1, &buffer); + alSourceQueueBuffers(mSource, 1, &buffer); } else if (status == Buffer::STREAM_EOF) { - if (!queue_.empty()) + if (!mQueue.empty()) { // begin the next buffer in the queue - expired_.push_back(buffer_); - buffer_ = queue_.front(); - queue_.pop(); - buffer_->beginStream(source_, 1); + mExpired.push_back(mBuffer); + mBuffer = mQueue.front(); + mQueue.pop(); + mBuffer->beginStream(mSource, 1); } - else if (looping_) + else if (mIsLooping) { // restart from the beginning - buffer_->rewind(); - buffer_->stream(buffer); - alSourceQueueBuffers(source_, 1, &buffer); + mBuffer->rewind(); + mBuffer->stream(buffer); + alSourceQueueBuffers(mSource, 1, &buffer); } } else if (status == Buffer::STREAM_WRONG) { clear(); - buffer_->beginStream(source_, 1); + mBuffer->beginStream(mSource, 1); } } ALenum state; - alGetSourcei(source_, AL_SOURCE_STATE, &state); + alGetSourcei(mSource, AL_SOURCE_STATE, &state); // restart playing if we're stopped but supposed to be playing... this // means we didn't queue enough and the audio skipped - if (playing_ && state != AL_PLAYING) + if (mIsPlaying && state != AL_PLAYING) { - alSourcePlay(source_); + alSourcePlay(mSource); } } @@ -363,29 +365,29 @@ struct Sound::Impl { // try to remove expired buffers std::vector::iterator it; - for (it = expired_.end() - 1; it >= expired_.begin(); --it) + for (it = mExpired.end() - 1; it >= mExpired.begin(); --it) { - if ((*it)->clear()) expired_.erase(it); + if ((*it)->clear()) mExpired.erase(it); } } void stop() { - alSourceStop(source_); - playing_ = false; + alSourceStop(mSource); + mIsPlaying = false; } inline void pause() { - alSourcePause(source_); - playing_ = false; + alSourcePause(mSource); + mIsPlaying = false; } inline void resume() { - alSourcePlay(source_); - playing_ = true; + alSourcePlay(mSource); + mIsPlaying = true; } @@ -393,12 +395,12 @@ struct Sound::Impl { bool playing = isPlaying(); ALenum type; - alGetSourcei(source_, AL_SOURCE_TYPE, &type); + alGetSourcei(mSource, AL_SOURCE_TYPE, &type); stop(); - //alSourcei(source_, AL_BUFFER, AL_NONE); - buffer_ = Buffer::getInstance(name); + //alSourcei(mSource, AL_BUFFER, AL_NONE); + mBuffer = Buffer::getInstance(name); if (type == AL_STREAMING) { @@ -413,16 +415,16 @@ struct Sound::Impl inline void enqueue(const std::string& name) { BufferP buffer = Buffer::getInstance(name); - queue_.push(buffer); + mQueue.push(buffer); } inline bool isPlaying() const { - if (playing_) return true; + if (mIsPlaying) return true; ALenum state; - alGetSourcei(source_, AL_SOURCE_STATE, &state); + alGetSourcei(mSource, AL_SOURCE_STATE, &state); return state == AL_PLAYING; } @@ -430,28 +432,28 @@ struct Sound::Impl inline void setLooping(bool looping) { - looping_ = looping; + mIsLooping = looping; ALenum type; - alGetSourcei(source_, AL_SOURCE_TYPE, &type); + alGetSourcei(mSource, AL_SOURCE_TYPE, &type); if (type != AL_STREAMING) { - alSourcei(source_, AL_LOOPING, looping_); + alSourcei(mSource, AL_LOOPING, mIsLooping); } } - ALuint source_; - BufferP buffer_; + ALuint mSource; + BufferP mBuffer; - bool playing_; - bool looping_; + bool mIsPlaying; + bool mIsLooping; - std::queue queue_; - std::vector expired_; + std::queue mQueue; + std::vector mExpired; - Timer streamTimer; + Timer mStreamTimer; void streamUpdate(Timer& timer, Scalar t) { @@ -464,43 +466,43 @@ struct Sound::Impl Sound::Sound(const std::string& name) : // pass through - impl_(new Sound::Impl(name)) {} + mImpl(new Sound::Impl(name)) {} void Sound::play() { // pass through - impl_->play(); + mImpl->play(); } void Sound::stream() { // pass through - impl_->stream(); + mImpl->stream(); } void Sound::stop() { // pass through - impl_->stop(); + mImpl->stop(); } void Sound::pause() { // pass through - impl_->pause(); + mImpl->pause(); } void Sound::resume() { // pass through - impl_->resume(); + mImpl->resume(); } void Sound::toggle() { - if (impl_->playing_) pause(); + if (mImpl->mIsPlaying) pause(); else resume(); } @@ -508,48 +510,48 @@ void Sound::toggle() void Sound::setSample(const std::string& name) { // pass through - impl_->setSample(name); + mImpl->setSample(name); } void Sound::enqueue(const std::string& name) { // pass through - impl_->enqueue(name); + mImpl->enqueue(name); } bool Sound::isPlaying() const { // pass through - return impl_->isPlaying(); + return mImpl->isPlaying(); } void Sound::setPosition(const Vector3& position) { float p[3] = {position[0], position[1], position[2]}; - alSourcefv(impl_->source_, AL_POSITION, p); + alSourcefv(mImpl->mSource, AL_POSITION, p); } void Sound::setVelocity(const Vector3& velocity) { float v[3] = {velocity[0], velocity[1], velocity[2]}; - alSourcefv(impl_->source_, AL_VELOCITY, v); + alSourcefv(mImpl->mSource, AL_VELOCITY, v); } void Sound::setGain(Scalar gain) { - alSourcef(impl_->source_, AL_GAIN, float(gain)); + alSourcef(mImpl->mSource, AL_GAIN, float(gain)); } void Sound::setPitch(Scalar pitch) { - alSourcef(impl_->source_, AL_PITCH, float(pitch)); + alSourcef(mImpl->mSource, AL_PITCH, float(pitch)); } void Sound::setLooping(bool looping) { // pass through - impl_->setLooping(looping); + mImpl->setLooping(looping); } diff --git a/src/Moof/Sound.hh b/src/Moof/Sound.hh index e5d312a..4e80fbe 100644 --- a/src/Moof/Sound.hh +++ b/src/Moof/Sound.hh @@ -51,7 +51,7 @@ typedef boost::shared_ptr SoundP; class Sound : public Resource { class Impl; - boost::shared_ptr impl_; + boost::shared_ptr mImpl; public: @@ -66,9 +66,7 @@ public: void play(); void stream(); - // TODO - i don't like how there are two different methods that essentially - // do the same thing; the API should be exactly the same for both types of - // sounds; need a different way to distinguish how to handle the sound + // TODO - this API sucks void stop(); void pause(); diff --git a/src/Moof/Texture.cc b/src/Moof/Texture.cc index b778c1c..fc50cfa 100644 --- a/src/Moof/Texture.cc +++ b/src/Moof/Texture.cc @@ -61,15 +61,15 @@ class Texture::Impl : public Mippleton void unloadFromGL() { - if (object_) + if (mObject) { - if (object_ == globalObject_) + if (mObject == globalObject_) { globalObject_ = 0; } - glDeleteTextures(1, &object_); - object_ = 0; + glDeleteTextures(1, &mObject); + mObject = 0; } } @@ -81,7 +81,7 @@ class Texture::Impl : public Mippleton void contextRecreated(const Notification* note) { - object_ = globalObject_ = 0; + mObject = globalObject_ = 0; uploadToGL(); } @@ -132,15 +132,15 @@ public: explicit Impl(const std::string& name) : Mippleton(name), - surface_(0), - width_(0), - height_(0), - mode_(0), - minFilter_(GL_NEAREST), - magFilter_(GL_NEAREST), - wrapS_(GL_CLAMP), - wrapT_(GL_CLAMP), - object_(0) + mContext(0), + mWidth(0), + mHeight(0), + mMode(0), + mMinFilter(GL_NEAREST), + mMagFilter(GL_NEAREST), + mWrapS(GL_CLAMP), + mWrapT(GL_CLAMP), + mObject(0) { loadFromFile(); @@ -151,9 +151,9 @@ public: ~Impl() { - if (surface_) + if (mContext) { - SDL_FreeSurface(surface_); + SDL_FreeSurface(mContext); } unloadFromGL(); @@ -258,11 +258,11 @@ public: if (temp->format->BytesPerPixel == 3) { - mode_ = GL_RGB; + mMode = GL_RGB; } else if (temp->format->BytesPerPixel == 4) { - mode_ = GL_RGBA; + mMode = GL_RGBA; } else { @@ -270,10 +270,10 @@ public: throw Exception(Exception::BAD_IMAGE_FORMAT); } - width_ = temp->w; - height_ = temp->h; + mWidth = temp->w; + mHeight = temp->h; - surface_ = temp; + mContext = temp; } @@ -284,34 +284,34 @@ public: void uploadToGL() { - if (object_) + if (mObject) { // already loaded return; } - if (!surface_) loadFromFile(); + if (!mContext) loadFromFile(); - glGenTextures(1, &object_); - glBindTexture(GL_TEXTURE_2D, object_); + glGenTextures(1, &mObject); + glBindTexture(GL_TEXTURE_2D, mObject); glTexImage2D ( GL_TEXTURE_2D, 0, - mode_, - surface_->w, - surface_->h, + mMode, + mContext->w, + mContext->h, 0, - mode_, + mMode, GL_UNSIGNED_BYTE, - surface_->pixels + mContext->pixels ); setProperties(); - SDL_FreeSurface(surface_); - surface_ = 0; + SDL_FreeSurface(mContext); + mContext = 0; } @@ -322,66 +322,66 @@ public: void setProperties() { - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, minFilter_); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, magFilter_); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, wrapS_); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, wrapT_); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, mMinFilter); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, mMagFilter); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, mWrapS); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, mWrapT); } inline void setMinFilter(GLuint filter) { bind(); - minFilter_ = filter; - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, minFilter_); + mMinFilter = filter; + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, mMinFilter); } inline void setMagFilter(GLuint filter) { bind(); - magFilter_ = filter; - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, magFilter_); + mMagFilter = filter; + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, mMagFilter); } inline void setWrapS(GLuint wrap) { bind(); - wrapS_ = wrap; - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, wrapS_); + mWrapS = wrap; + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, mWrapS); } inline void setWrapT(GLuint wrap) { bind(); - wrapT_ = wrap; - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, wrapT_); + mWrapT = wrap; + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, mWrapT); } inline void bind() { - if (object_ == 0) + if (mObject == 0) { uploadToGL(); } - if (object_ != globalObject_) + if (mObject != globalObject_) { - glBindTexture(GL_TEXTURE_2D, object_); - globalObject_ = object_; + glBindTexture(GL_TEXTURE_2D, mObject); + globalObject_ = mObject; } } - SDL_Surface* surface_; - unsigned width_; ///< Horizontal dimension of the image. - unsigned height_; ///< Vertical dimension. + SDL_Surface* mContext; + unsigned mWidth; ///< Horizontal dimension of the image. + unsigned mHeight; ///< Vertical dimension. - GLuint mode_; ///< Depth of the image, GL_RGB or GL_RGBA. - GLuint minFilter_; ///< Minifcation filter. - GLuint magFilter_; ///< Magnification filter. - GLuint wrapS_; ///< Wrapping behavior horizontally. - GLuint wrapT_; ///< Wrapping behavior vertically. + GLuint mMode; ///< Depth of the image, GL_RGB or GL_RGBA. + GLuint mMinFilter; ///< Minifcation filter. + GLuint mMagFilter; ///< Magnification filter. + GLuint mWrapS; ///< Wrapping behavior horizontally. + GLuint mWrapT; ///< Wrapping behavior vertically. - GLuint object_; ///< GL texture handle. + GLuint mObject; ///< GL texture handle. static GLuint globalObject_; ///< Global GL texture handle. }; @@ -390,7 +390,7 @@ GLuint Texture::Impl::globalObject_ = 0; Texture::Texture(const std::string& name) : // pass through - impl_(Texture::Impl::getInstance(name)) {} + mImpl(Texture::Impl::getInstance(name)) {} /** @@ -400,7 +400,7 @@ Texture::Texture(const std::string& name) : void Texture::bind() const { // pass through - impl_->bind(); + mImpl->bind(); } @@ -411,7 +411,7 @@ void Texture::bind() const GLuint Texture::getObject() const { // pass through - return impl_->object_; + return mImpl->mObject; } @@ -425,38 +425,38 @@ void Texture::resetBind() unsigned Texture::getWidth() const { // pass through - return impl_->width_; + return mImpl->mWidth; } unsigned Texture::getHeight() const { // pass through - return impl_->height_; + return mImpl->mHeight; } void Texture::setMinFilter(GLuint filter) { // pass through - impl_->setMinFilter(filter); + mImpl->setMinFilter(filter); } void Texture::setMagFilter(GLuint filter) { // pass through - impl_->setMagFilter(filter); + mImpl->setMagFilter(filter); } void Texture::setWrapS(GLuint wrap) { // pass through - impl_->setWrapS(wrap); + mImpl->setWrapS(wrap); } void Texture::setWrapT(GLuint wrap) { // pass through - impl_->setWrapT(wrap); + mImpl->setWrapT(wrap); } diff --git a/src/Moof/Texture.hh b/src/Moof/Texture.hh index 5710298..5aa38e1 100644 --- a/src/Moof/Texture.hh +++ b/src/Moof/Texture.hh @@ -53,7 +53,7 @@ typedef boost::shared_ptr TextureP; class Texture : public Resource { class Impl; - boost::shared_ptr impl_; + boost::shared_ptr mImpl; public: diff --git a/src/Moof/Thread.hh b/src/Moof/Thread.hh index 274f717..74952fa 100644 --- a/src/Moof/Thread.hh +++ b/src/Moof/Thread.hh @@ -105,22 +105,23 @@ class Mutex friend class Condition; public: + Mutex() { - mutex_ = SDL_CreateMutex(); + mMutex = SDL_CreateMutex(); } ~Mutex() { - SDL_DestroyMutex(mutex_); + SDL_DestroyMutex(mMutex); } bool acquireLock() { - return (SDL_LockMutex(mutex_) == 0); + return (SDL_LockMutex(mMutex) == 0); } bool releaseLock() { - return (SDL_UnlockMutex(mutex_) == 0); + return (SDL_UnlockMutex(mMutex) == 0); } class Lock @@ -128,39 +129,42 @@ public: friend class Condition; public: + Lock(Mutex& mutex) { - mutex_ = &mutex; - isLocked_ = false; + mMutex = &mutex; + mIsLocked = false; } ~Lock() { - if (isLocked_) release(); + if (mIsLocked) release(); } bool acquire() { - return (isLocked_ = mutex_->acquireLock()); + return (mIsLocked = mMutex->acquireLock()); } bool release() { - return mutex_->releaseLock(); - isLocked_ = false; + return mMutex->releaseLock(); + mIsLocked = false; } bool isLocked() const { - return isLocked_; + return mIsLocked; } protected: - Mutex* mutex_; - bool isLocked_; + + Mutex* mMutex; + bool mIsLocked; }; class ScopedLock : public Lock { public: + ScopedLock(Mutex& mutex) : Lock(mutex) { @@ -169,13 +173,15 @@ public: }; private: - SDL_mutex* mutex_; + + SDL_mutex* mMutex; }; class Condition { public: + Condition() { condition_ = SDL_CreateCond(); @@ -187,12 +193,12 @@ public: bool wait(Mutex::Lock& lock) { - return (SDL_CondWait(condition_, lock.mutex_->mutex_) == 0); + return (SDL_CondWait(condition_, lock.mMutex->mMutex) == 0); } bool wait(Mutex::Lock& lock, unsigned ms) { // TODO for consistency, this function should take seconds - return (SDL_CondWaitTimeout(condition_, lock.mutex_->mutex_, ms) == 0); + return (SDL_CondWaitTimeout(condition_, lock.mMutex->mMutex, ms) == 0); } bool notify() @@ -205,6 +211,7 @@ public: } private: + SDL_cond* condition_; }; @@ -212,6 +219,7 @@ private: class Semaphore { public: + Semaphore(unsigned int value) { semaphore_ = SDL_CreateSemaphore(value); @@ -243,38 +251,41 @@ public: class Lock { public: + Lock(Semaphore& semaphore) { semaphore_ = &semaphore; - isLocked_ = false; + mIsLocked = false; } ~Lock() { - if (isLocked_) release(); + if (mIsLocked) release(); } bool acquire() { - return (isLocked_ = semaphore_->acquireLock()); + return (mIsLocked = semaphore_->acquireLock()); } bool release() { - return semaphore_->releaseLock(); isLocked_ = false; + return semaphore_->releaseLock(); mIsLocked = false; } bool isLocked() const { - return isLocked_; + return mIsLocked; } protected: + Semaphore* semaphore_; - bool isLocked_; + bool mIsLocked; }; class ScopedLock : public Lock { public: + ScopedLock(Semaphore& semaphore) : Lock(semaphore) { @@ -283,6 +294,7 @@ public: }; private: + SDL_sem* semaphore_; }; diff --git a/src/Moof/Timer.cc b/src/Moof/Timer.cc index d28d5e8..d17882a 100644 --- a/src/Moof/Timer.cc +++ b/src/Moof/Timer.cc @@ -59,43 +59,43 @@ void Timer::init(const Function& function, Scalar seconds, Mode mode) { invalidate(); - mode_ = mode; + mMode = mode; - if (mode_ != INVALID) + if (mMode != INVALID) { - function_ = function; + mFunction = function; if (mode == ABSOLUTEE) { - absolute_ = seconds; + mAbsolute = seconds; } else { - absolute_ = seconds - getTicks(); - interval_ = seconds; + mAbsolute = seconds - getTicks(); + mInterval = seconds; } - id_ = getNewID(); - timers_.insert(std::pair(id_, *this)); + mId = getNewID(); + timers_.insert(std::pair(mId, *this)); - if (absolute_ < nextFire_) nextFire_ = absolute_; + if (mAbsolute < nextFire_) nextFire_ = mAbsolute; } } bool Timer::isValid() const { - return mode_ != INVALID; + return mMode != INVALID; } void Timer::invalidate() { - if (mode_ != INVALID) + if (mMode != INVALID) { - timers_.erase(id_); - mode_ = INVALID; + timers_.erase(mId); + mMode = INVALID; - if (isEqual(absolute_, nextFire_)) nextFire_ = findNextFire(); + if (isEqual(mAbsolute, nextFire_)) nextFire_ = findNextFire(); } } @@ -104,14 +104,14 @@ void Timer::fire() { Scalar t = getTicks(); - if (function_) function_(*this, t); + if (mFunction) mFunction(*this, t); if (isRepeating()) { - Scalar absolute = absolute_; + Scalar absolute = mAbsolute; - if (isEqual(absolute_, t, 1.0)) absolute_ += interval_; - else absolute_ = interval_ + t; + if (isEqual(mAbsolute, t, 1.0)) mAbsolute += mInterval; + else mAbsolute = mInterval + t; if (isEqual(absolute, nextFire_)) nextFire_ = findNextFire(); } @@ -129,7 +129,7 @@ Scalar Timer::findNextFire() for (it = timers_.begin(); it != timers_.end(); ++it) { - Scalar absolute = (*it).second.absolute_; + Scalar absolute = (*it).second.mAbsolute; if (absolute < nextFire) nextFire = absolute; } @@ -139,7 +139,7 @@ Scalar Timer::findNextFire() Scalar Timer::getSecondsRemaining() const { - return absolute_ - getTicks(); + return mAbsolute - getTicks(); } bool Timer::isExpired() const @@ -149,7 +149,7 @@ bool Timer::isExpired() const bool Timer::isRepeating() const { - return mode_ == REPEAT; + return mMode == REPEAT; } diff --git a/src/Moof/Timer.hh b/src/Moof/Timer.hh index 6c1af56..ed4e2f0 100644 --- a/src/Moof/Timer.hh +++ b/src/Moof/Timer.hh @@ -59,7 +59,7 @@ struct Timer Timer() : - mode_(INVALID) {} + mMode(INVALID) {} Timer(const Function& function, Scalar seconds, Mode mode = NORMAL) { @@ -115,11 +115,11 @@ private: static unsigned getNewID(); static Scalar findNextFire(); - Function function_; - Mode mode_; - Scalar absolute_; - Scalar interval_; - unsigned id_; + Function mFunction; + Mode mMode; + Scalar mAbsolute; + Scalar mInterval; + unsigned mId; static Scalar nextFire_; static std::map timers_; diff --git a/src/Moof/Transition.hh b/src/Moof/Transition.hh index cf1595c..f1e1bcb 100644 --- a/src/Moof/Transition.hh +++ b/src/Moof/Transition.hh @@ -46,20 +46,20 @@ namespace Mf { template class Transition : public Layer { - LayerP to; - LayerP from; + LayerP mTo; + LayerP mFrom; - T interpolator; + T mInterp; - Engine* engine; + Engine* mEngine; public: Transition(LayerP t, LayerP f, const T& interp) : - to(t), - from(f), - interpolator(interp), - engine(0) {} + mTo(t), + mFrom(f), + mInterp(interp), + mEngine(0) {} typedef boost::shared_ptr Ptr; @@ -69,27 +69,27 @@ public: } - void pushed(Engine& e) + void pushed(Engine& engine) { - engine = &e; + mEngine = &engine; } - void popped(Engine& e) + void popped(Engine& engine) { - if (to) e.push(to); + if (mTo) engine.push(mTo); } void update(Scalar t, Scalar dt) { - interpolator.update(t, dt); + mInterp.update(t, dt); - if (from) from->update(t, dt); - if (to) to->update(t, dt); + if (mFrom) mFrom->update(t, dt); + if (mTo) mTo->update(t, dt); - if (interpolator.isDone()) + if (mInterp.isDone()) { // to should /replace/ this - engine->pop(this); + mEngine->pop(this); } } @@ -128,27 +128,27 @@ public: void draw(Scalar alpha) const { - Scalar a = interpolator.getState(alpha); + Scalar a = mInterp.getState(alpha); logInfo("draw state: %f", a); //glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); - if (from) + if (mFrom) { glPushMatrix(); glLoadIdentity(); glRotate(180.0 * a, 0.0, 1.0, 0.0); - from->draw(alpha); + mFrom->draw(alpha); glPopMatrix(); } //drawFade(a); - if (to) + if (mTo) { glPushMatrix(); glLoadIdentity(); glRotate(180.0 * (1.0 - a), 0.0, 1.0, 0.0); - to->draw(alpha); + mTo->draw(alpha); glPopMatrix(); } //drawFade(1.0 - a); @@ -156,13 +156,13 @@ public: bool handleEvent(const Event& event) { - if (to) + if (mTo) { - return to->handleEvent(event); + return mTo->handleEvent(event); } - else if (from) + else if (mFrom) { - return from->handleEvent(event); + return mFrom->handleEvent(event); } return false; } diff --git a/src/Moof/Video.cc b/src/Moof/Video.cc index 8de161a..c49bb1e 100644 --- a/src/Moof/Video.cc +++ b/src/Moof/Video.cc @@ -41,7 +41,7 @@ namespace Mf { Video::Video() { - init(attribs_); + init(mAttribs); } Video::Video(const Attributes& attribs) @@ -51,23 +51,23 @@ Video::Video(const Attributes& attribs) Video::Video(const std::string& caption, const std::string& icon) { - if (attribs_.caption == "Untitled") + if (mAttribs.caption == "Untitled") { - attribs_.caption = caption; + mAttribs.caption = caption; } - if (attribs_.icon == "") + if (mAttribs.icon == "") { - attribs_.icon = icon; + mAttribs.icon = icon; } - init(attribs_); + init(mAttribs); } void Video::init(const Attributes& attribs) { - context_ = 0; - flags_ = 0; - attribs_ = attribs; + mContext = 0; + mFlags = 0; + mAttribs = attribs; setFull(attribs.fullscreen); setResizable(attribs.resizable); @@ -81,53 +81,53 @@ void Video::init(const Attributes& attribs) void Video::recreateContext() { - SDL_FreeSurface(context_); - context_ = 0; - setVideoMode(attribs_.mode); + SDL_FreeSurface(mContext); + mContext = 0; + setVideoMode(mAttribs.mode); } void Video::setOpenGLAttributes() { - SDL_GL_SetAttribute(SDL_GL_RED_SIZE, attribs_.colorBuffer[0]); - SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, attribs_.colorBuffer[1]); - SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, attribs_.colorBuffer[2]); - SDL_GL_SetAttribute(SDL_GL_ALPHA_SIZE, attribs_.colorBuffer[3]); - SDL_GL_SetAttribute(SDL_GL_BUFFER_SIZE, attribs_.frameBuffer); - SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, attribs_.doubleBuffer); - SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, attribs_.depthBuffer); - SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, attribs_.stencilBuffer); - SDL_GL_SetAttribute(SDL_GL_ACCUM_RED_SIZE, attribs_.accumBuffer[0]); - SDL_GL_SetAttribute(SDL_GL_ACCUM_GREEN_SIZE, attribs_.accumBuffer[1]); - SDL_GL_SetAttribute(SDL_GL_ACCUM_BLUE_SIZE, attribs_.accumBuffer[2]); - SDL_GL_SetAttribute(SDL_GL_ACCUM_ALPHA_SIZE, attribs_.accumBuffer[3]); - SDL_GL_SetAttribute(SDL_GL_STEREO, attribs_.stereo); - SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, attribs_.multisampleBuffers); - SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, attribs_.multisampleSamples); - SDL_GL_SetAttribute(SDL_GL_SWAP_CONTROL, attribs_.swapControl); - SDL_GL_SetAttribute(SDL_GL_ACCELERATED_VISUAL, attribs_.hardwareonly); + SDL_GL_SetAttribute(SDL_GL_RED_SIZE, mAttribs.colorBuffer[0]); + SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, mAttribs.colorBuffer[1]); + SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, mAttribs.colorBuffer[2]); + SDL_GL_SetAttribute(SDL_GL_ALPHA_SIZE, mAttribs.colorBuffer[3]); + SDL_GL_SetAttribute(SDL_GL_BUFFER_SIZE, mAttribs.frameBuffer); + SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, mAttribs.doubleBuffer); + SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, mAttribs.depthBuffer); + SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, mAttribs.stencilBuffer); + SDL_GL_SetAttribute(SDL_GL_ACCUM_RED_SIZE, mAttribs.accumBuffer[0]); + SDL_GL_SetAttribute(SDL_GL_ACCUM_GREEN_SIZE, mAttribs.accumBuffer[1]); + SDL_GL_SetAttribute(SDL_GL_ACCUM_BLUE_SIZE, mAttribs.accumBuffer[2]); + SDL_GL_SetAttribute(SDL_GL_ACCUM_ALPHA_SIZE, mAttribs.accumBuffer[3]); + SDL_GL_SetAttribute(SDL_GL_STEREO, mAttribs.stereo); + SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, mAttribs.multisampleBuffers); + SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, mAttribs.multisampleSamples); + SDL_GL_SetAttribute(SDL_GL_SWAP_CONTROL, mAttribs.swapControl); + SDL_GL_SetAttribute(SDL_GL_ACCELERATED_VISUAL, mAttribs.hardwareonly); } Video::~Video() { - SDL_FreeSurface(context_); + SDL_FreeSurface(mContext); } void Video::setVideoMode(const long mode[3]) { - if (mode != attribs_.mode || !context_) + if (mode != mAttribs.mode || !mContext) { - if (context_) SDL_FreeSurface(context_); + if (mContext) SDL_FreeSurface(mContext); - context_ = SDL_SetVideoMode(mode[0], mode[1], mode[2], - SDL_OPENGL | flags_); + mContext = SDL_SetVideoMode(mode[0], mode[1], mode[2], + SDL_OPENGL | mFlags); - if (context_) + if (mContext) { - attribs_.mode[0] = mode[0]; - attribs_.mode[1] = mode[1]; - attribs_.mode[2] = mode[2]; + mAttribs.mode[0] = mode[0]; + mAttribs.mode[1] = mode[1]; + mAttribs.mode[2] = mode[2]; #if defined(_WIN32) || defined (_WIN64) || defined(__WIN32__) // on win32, creating a new context via SDL_SetVideoMode will wipe @@ -143,13 +143,13 @@ void Video::setVideoMode(const long mode[3]) Video::Attributes Video::getAttributes() const { - return attribs_; + return mAttribs; } void Video::resize(int width, int height) { - long mode[] = {width, height, attribs_.mode[2]}; + long mode[] = {width, height, mAttribs.mode[2]}; setVideoMode(mode); } @@ -161,15 +161,15 @@ bool Video::iconify() void Video::setCaption(const std::string& caption) { - attribs_.caption = caption; + mAttribs.caption = caption; SDL_WM_SetCaption(caption.c_str(), 0); } void Video::setIcon() { - if (attribs_.icon != "") + if (mAttribs.icon != "") { - SDL_Surface* icon = IMG_Load(attribs_.icon.c_str()); + SDL_Surface* icon = IMG_Load(mAttribs.icon.c_str()); if (icon) { SDL_WM_SetIcon(icon, 0); @@ -180,27 +180,27 @@ void Video::setIcon() std::string Video::getCaption() const { - return attribs_.caption; + return mAttribs.caption; } void Video::setFull(bool full) { - if (full != isFull() || !context_) + if (full != isFull() || !mContext) { - if (context_) + if (mContext) { - flags_ ^= SDL_FULLSCREEN; + mFlags ^= SDL_FULLSCREEN; #if defined(linux) || defined(__linux) || defined(__linux__) - if (SDL_WM_ToggleFullScreen(context_) == 0) + if (SDL_WM_ToggleFullScreen(mContext) == 0) #endif recreateContext(); } else { - if (full) flags_ |= SDL_FULLSCREEN; - else flags_ &= ~SDL_FULLSCREEN; + if (full) mFlags |= SDL_FULLSCREEN; + else mFlags &= ~SDL_FULLSCREEN; } } } @@ -212,7 +212,7 @@ void Video::toggleFull() bool Video::isFull() const { - return flags_ & SDL_FULLSCREEN; + return mFlags & SDL_FULLSCREEN; } @@ -234,17 +234,17 @@ bool Video::isCursorVisible() const void Video::setResizable(bool resizable) { - if (resizable != isResizable() || !context_) + if (resizable != isResizable() || !mContext) { - if (context_) + if (mContext) { - flags_ ^= SDL_RESIZABLE; + mFlags ^= SDL_RESIZABLE; recreateContext(); } else { - if (resizable) flags_ |= SDL_RESIZABLE; - else flags_ &= ~SDL_RESIZABLE; + if (resizable) mFlags |= SDL_RESIZABLE; + else mFlags &= ~SDL_RESIZABLE; } } } @@ -256,7 +256,7 @@ void Video::toggleResizable() bool Video::isResizable() const { - return flags_ & SDL_RESIZABLE; + return mFlags & SDL_RESIZABLE; } @@ -290,12 +290,12 @@ void Video::swap() int Video::getWidth() const { - return context_->w; + return mContext->w; } int Video::getHeight() const { - return context_->h; + return mContext->h; } diff --git a/src/Moof/Video.hh b/src/Moof/Video.hh index 5f56f9e..736832f 100644 --- a/src/Moof/Video.hh +++ b/src/Moof/Video.hh @@ -45,8 +45,10 @@ class Video; typedef boost::shared_ptr