Character::Character(const std::string& name) :
- texture(name),
- anim(name) {}
+ tilemap(name),
+ animation(name) {}
Character::~Character()
{
}
-void Character::draw(dc::scalar alpha) {}
+void Character::draw(Mf::Scalar alpha) {}
-dc::tilemap& Character::getTilemap()
+Mf::Tilemap& Character::getTilemap()
{
- return texture;
+ return tilemap;
}
-dc::animation& Character::getAnimation()
+Mf::Animation& Character::getAnimation()
{
- return anim;
+ return animation;
}
#ifndef _CHARACTER_HH_
#define _CHARACTER_HH_
-#include "resource.hh"
-#include "drawable.hh"
-#include "animation.hh"
-#include "tilemap.hh"
+#include <Moof/Animation.hh>
+#include <Moof/Drawable.hh>
+#include <Moof/Resource.hh>
+#include <Moof/Tilemap.hh>
/**
* Parent class of animate objects with "personalities."
*/
-class Character : public dc::drawable
+class Character : public Mf::Drawable
{
public:
- struct exception : public std::runtime_error
- {
- explicit exception(const std::string& what_arg) :
- std::runtime_error(what_arg) {}
- };
-
Character(const std::string& name);
~Character();
- void draw(dc::scalar alpha);
+ void draw(Mf::Scalar alpha);
+
+ Mf::Tilemap& getTilemap();
+ Mf::Animation& getAnimation();
- dc::tilemap& getTilemap();
- dc::animation& getAnimation();
+
+ struct Exception : public std::runtime_error
+ {
+ explicit Exception(const std::string& what_arg) :
+ std::runtime_error(what_arg) {}
+ };
private:
- dc::tilemap texture;
- dc::animation anim;
+ Mf::Tilemap tilemap;
+ Mf::Animation animation;
};
-noinst_LTLIBRARIES = libdc.la
+noinst_LTLIBRARIES = libmoof.la
-libdc_la_SOURCES = \
- ConvertUTF.c \
- ConvertUTF.h \
- aabb.hh \
- animation.cc \
- animation.hh \
- deserializer.cc \
- deserializer.hh \
- dispatcher.cc \
- dispatcher.hh \
- drawable.hh \
- engine.cc \
- engine.hh \
- event.hh \
- fastevents.c \
- fastevents.h \
- interpolator.hh \
- math.hh \
- mippleton.hh \
- opengl.hh \
- profiler.hh \
- random.cc \
- random.hh \
- resource.cc \
- resource.hh \
- scene.cc \
- scene.hh \
- serializable.cc \
- serializable.hh \
- serializer.cc \
- serializer.hh \
- settings.cc \
- settings.hh \
- singleton.hh \
- stringtools.cc \
- stringtools.hh \
- texture.cc \
- texture.hh \
- thread.hh \
- tilemap.cc \
- tilemap.hh \
- timer.cc \
- timer.hh \
- video.cc \
- video.hh \
+libmoof_la_SOURCES = \
+ Moof/Aabb.hh \
+ Moof/Animation.cc \
+ Moof/Animation.hh \
+ Moof/ConvertUTF.c \
+ Moof/ConvertUTF.h \
+ Moof/Deserializer.cc \
+ Moof/Deserializer.hh \
+ Moof/Dispatcher.cc \
+ Moof/Dispatcher.hh \
+ Moof/Drawable.hh \
+ Moof/Engine.cc \
+ Moof/Engine.hh \
+ Moof/Event.hh \
+ Moof/Interpolator.hh \
+ Moof/Math.hh \
+ Moof/Mippleton.hh \
+ Moof/OpenGL.hh \
+ Moof/Profiler.hh \
+ Moof/Random.cc \
+ Moof/Random.hh \
+ Moof/Resource.cc \
+ Moof/Resource.hh \
+ Moof/Scene.cc \
+ Moof/Scene.hh \
+ Moof/Serializable.cc \
+ Moof/Serializable.hh \
+ Moof/Serializer.cc \
+ Moof/Serializer.hh \
+ Moof/Settings.cc \
+ Moof/Settings.hh \
+ Moof/Singleton.hh \
+ Moof/StringTools.cc \
+ Moof/StringTools.hh \
+ Moof/Texture.cc \
+ Moof/Texture.hh \
+ Moof/Thread.hh \
+ Moof/Tilemap.cc \
+ Moof/Tilemap.hh \
+ Moof/Timer.cc \
+ Moof/Timer.hh \
+ Moof/Video.cc \
+ Moof/Video.hh \
+ Moof/fastevents.c \
+ Moof/fastevents.h \
$(ENDLIST)
-libdc_la_CPPFLAGS = -I$(top_srcdir)/yajl/src
-libdc_la_LIBADD = $(top_srcdir)/yajl/libyajl.la
+libmoof_la_CPPFLAGS = -I$(top_srcdir)/src/Moof -I$(top_srcdir)/yajl/src
+libmoof_la_LIBADD = $(top_srcdir)/yajl/libyajl.la
bin_PROGRAMS = yoink
YoinkApp.hh \
$(ENDLIST)
-yoink_LDADD = libdc.la
+yoink_CPPFLAGS = -I$(top_srcdir)/src/Moof
+yoink_LDADD = libmoof.la
-EXTRA_DIST = cml
+EXTRA_DIST = Moof/cml
YOINK_ENVIRONMENT = YOINK_DATADIR="$(top_srcdir)/data" \
******************************************************************************/
-#ifndef _AABB_HH_
-#define _AABB_HH_
+#ifndef _MOOF_AABB_HH_
+#define _MOOF_AABB_HH_
-#include "math.hh"
+#include <Moof/Math.hh>
-namespace dc {
+namespace Mf {
/**
* Axis-aligned Bounding Box
*/
-struct aabb
+struct Aabb
{
- aabb() {}
+ Aabb() {}
- aabb(const vector3& minPoint, const vector3& maxPoint) :
+ Aabb(const Vector3& minPoint, const Vector3& maxPoint) :
min(minPoint),
max(maxPoint) {}
- aabb (scalar minX, scalar minY, scalar minZ,
- scalar maxX, scalar maxY, scalar maxZ) :
+ Aabb (Scalar minX, Scalar minY, Scalar minZ,
+ Scalar maxX, Scalar maxY, Scalar maxZ) :
min(minX, minY, minZ),
max(maxX, maxY, maxZ) {}
- vector3 min;
- vector3 max;
+ Vector3 min;
+ Vector3 max;
};
-} // namespace dc
+} // namespace Mf
-#endif // _AABB_HH_
+#endif // _MOOF_AABB_HH_
/** vim: set ts=4 sw=4 tw=80: *************************************************/
#include <map>
#include <vector>
-#include "serializable.hh"
-#include "mippleton.hh"
-#include "animation.hh"
+#include "Animation.hh"
+#include "Mippleton.hh"
+#include "Serializable.hh"
-namespace dc {
+namespace Mf {
/**
* The collection of nested animation classes. The animation implementation
- * consists of an animation_impl classes which is allocated and initialized with
+ * consists of an AnimationImpl classes which is allocated and initialized with
* the interface object. This class contains the specific fields which are
* required to run a single instance of an animation. The sequence data is
* loaded in a difference class which can be shared amongst multiple animation
* implementation instances.
*/
-struct animation::animation_impl
+struct Animation::AnimationImpl
{
/**
* which wants to use these loaded sequences.
*/
- struct animation_data : public mippleton<animation_data>
+ struct AnimationData : public Mippleton<AnimationData>
{
/**
* A frame of an animation sequence. A frame is merely an index which
* and the duration that is how long the slide will be shown.
*/
- struct frame
+ struct Frame
{
unsigned index; ///< Frame index.
- scalar duration; ///< Frame duration.
+ Scalar duration; ///< Frame duration.
/**
* Construction is initialization. The frame data is loaded from a
* frame map which is probably loaded within an animation file.
*/
- frame(serializable_ptr root) :
+ Frame(SerializablePtr root) :
index(0),
duration(1.0)
{
- std::map<std::string,serializable_ptr> rootObj;
+ std::map<std::string,SerializablePtr> rootObj;
if (root->get(rootObj))
{
- std::map<std::string,serializable_ptr>::iterator i;
- for (i = rootObj.begin(); i != rootObj.end(); i++)
+ std::map<std::string,SerializablePtr>::iterator it;
+
+ for (it = rootObj.begin(); it != rootObj.end(); it++)
{
- std::string key = (*i).first;
+ std::string key = (*it).first;
if (key == "index")
{
long value = 0;
- (*i).second->get(value);
+ (*it).second->get(value);
index = unsigned(value);
}
else if (key == "duration")
{
double value = 0.0;
- (*i).second->getNumber(value);
- duration = scalar(value);
+ (*it).second->getNumber(value);
+ duration = Scalar(value);
}
}
}
* that they should be played.
*/
- struct sequence
+ struct Sequence
{
- std::vector<frame> frames; ///< List of frames.
- scalar delay; ///< Scale frame durations.
+ std::vector<Frame> frames; ///< List of frames.
+ Scalar delay; ///< Scale frame durations.
bool loop; ///< Does the sequence repeat?
std::string next; ///< Next sequence name.
* constructor which loads each individual frame.
*/
- sequence(serializable_ptr root) :
+ Sequence(SerializablePtr root) :
delay(0.0),
loop(true)
{
- std::map<std::string,serializable_ptr> rootObj;
+ std::map<std::string,SerializablePtr> rootObj;
if (root->get(rootObj))
{
- std::map<std::string,serializable_ptr>::iterator i;
- for (i = rootObj.begin(); i != rootObj.end(); i++)
+ std::map<std::string,SerializablePtr>::iterator it;
+ for (it = rootObj.begin(); it != rootObj.end(); it++)
{
- std::string key = (*i).first;
+ std::string key = (*it).first;
if (key == "frames")
{
- std::vector<serializable_ptr> framesObj;
+ std::vector<SerializablePtr> framesObj;
- if ((*i).second->get(framesObj))
+ if ((*it).second->get(framesObj))
{
- std::vector<serializable_ptr>::iterator j;
+ std::vector<SerializablePtr>::iterator jt;
- for (j = framesObj.begin();
- j != framesObj.end(); j++)
+ for (jt = framesObj.begin();
+ jt != framesObj.end(); jt++)
{
- if (*j)
+ if (*jt)
{
- frames.push_back(frame(*j));
+ frames.push_back(Frame(*jt));
}
}
}
else if (key == "delay")
{
double value;
- (*i).second->getNumber(value);
- delay = scalar(value);
+ (*it).second->getNumber(value);
+ delay = Scalar(value);
}
else if (key == "loop")
{
- (*i).second->get(loop);
+ (*it).second->get(loop);
}
else if (key == "next")
{
- (*i).second->get(next);
+ (*it).second->get(next);
}
}
}
void loadFromFile()
{
- std::string filePath = animation::getPathToResource(getName());
+ std::string filePath = Animation::getPathToResource(getName());
- deserializer in(filePath);
+ Deserializer deserializer(filePath);
- serializable_ptr root = in.deserialize();
+ SerializablePtr root = deserializer.deserialize();
if (root)
{
- std::map<std::string,serializable_ptr> rootObj;
+ std::map<std::string,SerializablePtr> rootObj;
if (root->get(rootObj))
{
- std::map<std::string,serializable_ptr>::iterator i;
+ std::map<std::string,SerializablePtr>::iterator it;
- for (i = rootObj.begin(); i != rootObj.end(); i++)
+ for (it = rootObj.begin(); it != rootObj.end(); it++)
{
- sequences.insert(std::pair<std::string,sequence>((*i).first,
- sequence((*i).second)));
+ sequences.insert(std::pair<std::string,Sequence>((*it).first,
+ Sequence((*it).second)));
}
}
}
* registers itself as a mippleton and then loads the animation data.
*/
- explicit animation_data(const std::string& name) :
- mippleton<animation_data>(name)
+ explicit AnimationData(const std::string& name) :
+ Mippleton<AnimationData>(name)
{
loadFromFile();
}
- std::map<std::string,sequence> sequences; ///< List of sequences.
+ std::map<std::string,Sequence> sequences; ///< List of sequences.
};
* Construction is intialization.
*/
- animation_impl(const std::string& name) :
- data(animation_data::retain(name), &animation_data::release),
+ AnimationImpl(const std::string& name) :
+ data(AnimationData::retain(name), &AnimationData::release),
currentSequence(0),
frameCounter(0),
frameIndex(0),
* updates will progress the new sequence.
*/
- void startSequence(const std::string& sequenceName)
+ void startSequence(const std::string& name)
{
- std::map<std::string,animation_data::sequence>::iterator i;
+ std::map<std::string,AnimationData::Sequence>::iterator it;
- i = data->sequences.find(sequenceName);
+ it = data->sequences.find(name);
- if (i != data->sequences.end())
+ if (it != data->sequences.end())
{
- currentSequence = &(*i).second;
+ currentSequence = &(*it).second;
frameCounter = 0;
frameIndex = currentSequence->frames[0].index;
timeAccum = 0.0;
* starts over again.
*/
- void update(scalar t, scalar dt)
+ void update(Scalar t, Scalar dt)
{
if (currentSequence)
{
}
}
- boost::shared_ptr<animation_data> data; ///< Internal data.
+ boost::shared_ptr<AnimationData> data; ///< Internal data.
- animation_data::sequence* currentSequence; ///< Active sequence.
+ AnimationData::Sequence* currentSequence; ///< Active sequence.
unsigned frameCounter; ///< Current frame.
unsigned frameIndex; ///< Index of current frame.
- scalar timeAccum; ///< Time accumulation.
- scalar frameDuration; ///< Scaled frame duration.
+ Scalar timeAccum; ///< Time accumulation.
+ Scalar frameDuration; ///< Scaled frame duration.
};
-animation::animation(const std::string& name) :
+Animation::Animation(const std::string& name) :
// pass through
- impl(new animation::animation_impl(name)) {}
+ impl_(new Animation::AnimationImpl(name)) {}
-void animation::startSequence(const std::string& sequenceName)
+void Animation::startSequence(const std::string& name)
{
// pass through
- impl->startSequence(sequenceName);
+ impl_->startSequence(name);
}
-void animation::update(scalar t, scalar dt)
+void Animation::update(Scalar t, Scalar dt)
{
// pass through
- impl->update(t, dt);
+ impl_->update(t, dt);
}
* drawing code which will draw the correct current frame.
*/
-unsigned animation::getFrame() const
+unsigned Animation::getFrame() const
{
- return impl->frameIndex;
+ return impl_->frameIndex;
}
* "animations" subdirectory of any of the searched directories.
*/
-std::string animation::getPathToResource(const std::string& name)
+std::string Animation::getPathToResource(const std::string& name)
{
- return resource::getPathToResource("animations/" + name + ".json");
+ return Resource::getPathToResource("animations/" + name + ".json");
}
-} // namespace dc
+} // namespace Mf
/** vim: set ts=4 sw=4 tw=80: *************************************************/
*******************************************************************************/
-#ifndef _ANIMATION_HH_
-#define _ANIMATION_HH_
+#ifndef _MOOF_ANIMATION_HH_
+#define _MOOF_ANIMATION_HH_
/**
- * @file animation.hh
+ * @file Animation.hh
* Motion picture!!
*/
#include <boost/shared_ptr.hpp>
-#include "resource.hh"
-#include "math.hh"
+#include <Moof/Math.hh>
+#include <Moof/Resource.hh>
-namespace dc {
+namespace Mf {
/**
* anything to whatever drawing context is used to render the frame.
*/
-class animation : public resource
+class Animation : public Resource
{
public:
- animation(const std::string& name);
+ Animation(const std::string& name);
- void startSequence(const std::string& sequenceName);
+ void startSequence(const std::string& name);
- void update(scalar t, scalar dt);
+ void update(Scalar t, Scalar dt);
unsigned getFrame() const;
static std::string getPathToResource(const std::string& name);
private:
- class animation_impl;
- boost::shared_ptr<animation_impl> impl;
+ class AnimationImpl;
+ boost::shared_ptr<AnimationImpl> impl_;
};
-} // namespace dc
+} // namespace Mf
-#endif // _ANIMATION_HH_
+#endif // _MOOF_ANIMATION_HH_
/** vim: set ts=4 sw=4 tw=80: *************************************************/
*******************************************************************************/
-#ifndef _CAMERA_HH_
-#define _CAMERA_HH_
+#ifndef _MOOF_CAMERA_HH_
+#define _MOOF_CAMERA_HH_
-namespace dc {
+namespace Mf {
-class camera
+class Camera
{
public:
private:
};
-} // namespace dc
+} // namespace Mf
-#endif // _CAMERA_HH_
+#endif // _MOOF_CAMERA_HH_
/** vim: set ts=4 sw=4 tw=80: *************************************************/
*******************************************************************************/
-#ifndef _CULLABLE_HH_
-#define _CULLABLE_HH_
+#ifndef _MOOF_CULLABLE_HH_
+#define _MOOF_CULLABLE_HH_
-#include "camera.hh"
+#include <Moof/Camera.hh>
-namespace dc {
+namespace Mf {
/**
- * Interface for anything that can be culled given a camera's frustrum.
+ * Interface for anything that can be culled. This can include more than just
+ * frustrum culling.
*/
-class cullable
+class Cullable
{
public:
- virtual bool isVisible(const camera& cam) = 0;
+ virtual bool isVisible(const Camera& cam) = 0;
};
-} // namespace dc
+} // namespace Mf
-#endif // _CULLABLE_HH_
+#endif // _MOOF_CULLABLE_HH_
/** vim: set ts=4 sw=4 tw=80: *************************************************/
#include <yajl/yajl_parse.h>
-#include "serializable.hh"
-#include "deserializer.hh"
+#include "Deserializer.hh"
+#include "Serializable.hh"
-namespace dc {
+namespace Mf {
-class deserializer::deserializer_impl
+class Deserializer::DeserializerImpl
{
public:
- deserializer_impl(const std::string& filePath, bool comments = false,
+ DeserializerImpl(const std::string& filePath, bool comments = false,
bool check = false)
{
std::ifstream* input = new std::ifstream(filePath.c_str());
init(*input, true, comments, check);
}
- deserializer_impl(std::istream& input, bool comments = false,
+ DeserializerImpl(std::istream& input, bool comments = false,
bool check = false)
{
init(input, false, comments, check);
}
- ~deserializer_impl()
+ ~DeserializerImpl()
{
while (!parsed.empty())
{
void throwError()
{
- unsigned char* errorMsg = yajl_get_error(hand, 0, 0, 0);
- deserializer::exception problem((char*)errorMsg);
- yajl_free_error(hand, errorMsg);
- throw problem;
+ unsigned char* errorStr = yajl_get_error(hand, 0, 0, 0);
+ Deserializer::Exception exception((char*)errorStr);
+ yajl_free_error(hand, errorStr);
+ throw exception;
}
static int parsedNull(void* ctx)
{
- ((deserializer_impl*)ctx)->parsed.push(new null);
+ ((DeserializerImpl*)ctx)->parsed.push(new SerializableNull);
return 1;
}
static int parsedBoolean(void* ctx, int value)
{
- ((deserializer_impl*)ctx)->parsed.push(new wrapped_boolean(value));
+ ((DeserializerImpl*)ctx)->parsed.push(new SerializableBoolean(value));
return 1;
}
static int parsedInteger(void* ctx, long value)
{
- ((deserializer_impl*)ctx)->parsed.push(new wrapped_integer(value));
+ ((DeserializerImpl*)ctx)->parsed.push(new SerializableInteger(value));
return 1;
}
static int parsedFloat(void* ctx, double value)
{
- ((deserializer_impl*)ctx)->parsed.push(new wrapped_real(value));
+ ((DeserializerImpl*)ctx)->parsed.push(new SerializableReal(value));
return 1;
}
static int parsedString(void* ctx, const unsigned char* value,
unsigned length)
{
- wrapped_string* parsed = new wrapped_string(std::string((char*)value,
- length));
- ((deserializer_impl*)ctx)->parsed.push(parsed);
+ SerializableString* parsed =
+ new SerializableString(std::string((char*)value, length));
+ ((DeserializerImpl*)ctx)->parsed.push(parsed);
return 1;
}
static int parsedBeginMap(void* ctx)
{
- ((deserializer_impl*)ctx)->parsed.push(new wrapped_dictionary);
+ ((DeserializerImpl*)ctx)->parsed.push(new SerializableMap);
return 1;
}
static int parsedEndMap(void* ctx)
{
- ((deserializer_impl*)ctx)->parsed.push(0);
+ ((DeserializerImpl*)ctx)->parsed.push(0);
return 1;
}
static int parsedBeginArray(void* ctx)
{
- ((deserializer_impl*)ctx)->parsed.push(new wrapped_array);
+ ((DeserializerImpl*)ctx)->parsed.push(new SerializableArray);
return 1;
}
static int parsedEndArray(void* ctx)
{
- ((deserializer_impl*)ctx)->parsed.push(0);
+ ((DeserializerImpl*)ctx)->parsed.push(0);
return 1;
}
std::istream* in;
bool deleteWhenDone;
- std::queue<serializable*> parsed;
+ std::queue<Serializable*> parsed;
private:
void init(std::istream& input, bool deleteIn, bool comments, bool check)
// internal data structures but rather keeps a pointer to this
static const yajl_callbacks callbacks =
{
- deserializer_impl::parsedNull,
- deserializer_impl::parsedBoolean,
- deserializer_impl::parsedInteger,
- deserializer_impl::parsedFloat,
+ DeserializerImpl::parsedNull,
+ DeserializerImpl::parsedBoolean,
+ DeserializerImpl::parsedInteger,
+ DeserializerImpl::parsedFloat,
0,
- deserializer_impl::parsedString,
- deserializer_impl::parsedBeginMap,
- deserializer_impl::parsedMapKey,
- deserializer_impl::parsedEndMap,
- deserializer_impl::parsedBeginArray,
- deserializer_impl::parsedEndArray
+ DeserializerImpl::parsedString,
+ DeserializerImpl::parsedBeginMap,
+ DeserializerImpl::parsedMapKey,
+ DeserializerImpl::parsedEndMap,
+ DeserializerImpl::parsedBeginArray,
+ DeserializerImpl::parsedEndArray
};
in = &input;
};
-deserializer::deserializer(const std::string& filePath, bool comments,
+Deserializer::Deserializer(const std::string& filePath, bool comments,
bool check) :
// pass through
- impl(new deserializer::deserializer_impl(filePath, comments, check)) {}
+ impl_(new Deserializer::DeserializerImpl(filePath, comments, check)) {}
-deserializer::deserializer(std::istream& input, bool comments, bool check) :
+Deserializer::Deserializer(std::istream& input, bool comments, bool check) :
// pass through
- impl(new deserializer::deserializer_impl(input, comments, check)) {}
+ impl_(new Deserializer::DeserializerImpl(input, comments, check)) {}
-serializable_ptr deserializer::deserialize()
+SerializablePtr Deserializer::deserialize()
{
- serializable* ptr = pullNext();
+ Serializable* ptr = pullNext();
if (ptr)
{
ptr->deserialize(*this);
}
- return serializable_ptr(ptr);
+ return SerializablePtr(ptr);
}
-serializable* deserializer::pullNext()
+Serializable* Deserializer::pullNext()
{
- impl->parse();
- if (!impl->parsed.empty())
+ impl_->parse();
+ if (!impl_->parsed.empty())
{
- serializable* ptr = impl->parsed.front();
+ Serializable* ptr = impl_->parsed.front();
return ptr;
}
return 0;
}
-void deserializer::pop()
+void Deserializer::pop()
{
// pass through
- impl->parsed.pop();
+ impl_->parsed.pop();
}
-} // namespace dc
+} // namespace Mf
/** vim: set ts=4 sw=4 tw=80: *************************************************/
*******************************************************************************/
-#ifndef _DESERIALIZER_HH_
-#define _DESERIALIZER_HH_
+#ifndef _MOOF_DESERIALIZER_HH_
+#define _MOOF_DESERIALIZER_HH_
/**
- * @file deserializer.hh
+ * @file Deserializer.hh
* Deserialize structures and types from input on a stream.
*/
#include <boost/shared_ptr.hpp>
-namespace dc {
+namespace Mf {
-class serializable; // forward declaration
-typedef boost::shared_ptr<serializable> serializable_ptr;
+class Serializable; // forward declaration
+typedef boost::shared_ptr<Serializable> SerializablePtr;
-class deserializer
+class Deserializer
{
public:
* checked.
*/
- deserializer(const std::string& filePath, bool comments = false,
+ Deserializer(const std::string& filePath, bool comments = false,
bool check = false);
- deserializer(std::istream& input, bool comments = false, bool check = false);
+ Deserializer(std::istream& input, bool comments = false, bool check = false);
/**
* deserializer.
*/
- serializable_ptr deserialize();
+ SerializablePtr deserialize();
/**
* Used by serializable objects to parse themselves. These methods should
* method to return the next object as expected.
*/
- serializable* pullNext();
+ Serializable* pullNext();
/**
* If the object returned by pullNext() has been received successfully and
* This exception is thrown upon deserialization errors.
*/
- struct exception : std::runtime_error
+ struct Exception : std::runtime_error
{
- explicit exception(const std::string& what_arg) :
+ explicit Exception(const std::string& what_arg) :
std::runtime_error(what_arg) {}
};
private:
- class deserializer_impl;
- boost::shared_ptr<deserializer_impl> impl;
+ class DeserializerImpl;
+ boost::shared_ptr<DeserializerImpl> impl_;
};
-} // namespace dc
+} // namespace Mf
-#endif // _DESERIALIZER_HH_
+#endif // _MOOF_DESERIALIZER_HH_
/** vim: set ts=4 sw=4 tw=80: *************************************************/
--- /dev/null
+
+/*******************************************************************************
+
+ Copyright (c) 2009, Charles McGarvey
+ All rights reserved.
+
+ Redistribution and use in source and binary forms, with or without
+ modification, are permitted provided that the following conditions are met:
+
+ * Redistributions of source code must retain the above copyright notice,
+ this list of conditions and the following disclaimer.
+ * Redistributions in binary form must reproduce the above copyright notice,
+ this list of conditions and the following disclaimer in the documentation
+ and/or other materials provided with the distribution.
+
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
+ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+*******************************************************************************/
+
+#include <map>
+
+#include "Dispatcher.hh"
+
+
+namespace Mf {
+
+
+Notification::~Notification() {}
+
+
+class Dispatcher::DispatcherImpl
+{
+public:
+ DispatcherImpl() : id(1) {}
+
+ Dispatcher::Handler getNewHandlerID()
+ {
+ id += 4;
+ return (Dispatcher::Handler)id;
+ }
+
+ typedef std::pair<Dispatcher::Handler,Dispatcher::Function> Callback;
+ typedef std::multimap<std::string,Callback> CallbackLookup;
+ typedef CallbackLookup::iterator CallbackIter;
+
+ typedef std::multimap<Dispatcher::Handler,std::string> HandlerLookup;
+ typedef HandlerLookup::iterator HandlerIter;
+
+ unsigned long long id;
+
+ CallbackLookup callbacks;
+ HandlerLookup handlers;
+};
+
+
+Dispatcher::Dispatcher() :
+ impl_(new Dispatcher::DispatcherImpl) {}
+
+
+// TODO these methods are ugly
+
+Dispatcher::Handler Dispatcher::addHandler(const std::string& message,
+ const Function& callback)
+{
+ return addHandler(message, callback, impl_->getNewHandlerID());
+}
+
+Dispatcher::Handler Dispatcher::addHandler(const std::string& message,
+ const Function& callback, Handler id)
+{
+ std::pair<std::string,Dispatcher::DispatcherImpl::Callback>
+ callbackPair(message, Dispatcher::DispatcherImpl::Callback(id, callback));
+
+ std::pair<Handler,std::string> handlerPair(id, message);
+
+ impl_->callbacks.insert(callbackPair);
+ impl_->handlers.insert(handlerPair);
+
+ return id;
+}
+
+
+void Dispatcher::removeHandler(Handler id)
+{
+ std::pair<Dispatcher::DispatcherImpl::HandlerIter,Dispatcher::DispatcherImpl::HandlerIter>
+ handlers(impl_->handlers.equal_range(id));
+
+ Dispatcher::DispatcherImpl::HandlerIter i;
+ for (i = handlers.first; i != handlers.second; i++)
+ {
+ Dispatcher::DispatcherImpl::CallbackIter it = impl_->callbacks.find((*i).second);
+ Dispatcher::DispatcherImpl::CallbackIter last = impl_->callbacks.end();
+
+ Dispatcher::DispatcherImpl::CallbackIter j;
+ for (j = it; j != last; j++)
+ {
+ if (((*j).second).first == id)
+ {
+ impl_->callbacks.erase(j);
+ break;
+ }
+ }
+ }
+
+ impl_->handlers.erase(id);
+}
+
+
+void Dispatcher::dispatch(const std::string& message)
+{
+ dispatch(message, Notification());
+}
+
+void Dispatcher::dispatch(const std::string& message, const Notification& param)
+{
+ std::pair<Dispatcher::DispatcherImpl::CallbackIter,Dispatcher::DispatcherImpl::CallbackIter>
+ callbacks(impl_->callbacks.equal_range(message));
+
+ Dispatcher::DispatcherImpl::CallbackIter i;
+ for (i = callbacks.first; i != callbacks.second; i++)
+ {
+ Function callback = ((*i).second).second;
+ callback(param);
+ }
+}
+
+
+} // namespace Mf
+
+/** vim: set ts=4 sw=4 tw=80: *************************************************/
+
*******************************************************************************/
-#ifndef _DISPATCHER_HH_
-#define _DISPATCHER_HH_
+#ifndef _MOOF_DISPATCHER_HH_
+#define _MOOF_DISPATCHER_HH_
#include <string>
#include <boost/shared_ptr.hpp>
#include <boost/function.hpp>
-#include "singleton.hh"
+#include <Moof/Singleton.hh>
-namespace dc {
+namespace Mf {
/**
* Interface for a notification class.
*/
-class notification
+class Notification
{
public:
- virtual ~notification();
+ virtual ~Notification();
};
* Dispatcher of notifications to interested parties.
*/
-class dispatcher : public singleton<dispatcher>
+class Dispatcher : public Singleton<Dispatcher>
{
public:
- typedef void* handler;
+ typedef void* Handler;
+ typedef boost::function<void(const Notification&)> Function;
- dispatcher();
+ Dispatcher();
- typedef boost::function<void(const notification&)> function;
+ Handler addHandler(const std::string& message, const Function& callback);
+ Handler addHandler(const std::string& message, const Function& callback,
+ Handler id);
- handler addHandler(const std::string& message, const function& callback);
- handler addHandler(const std::string& message, const function& callback,
- handler id);
-
- void removeHandler(handler id);
+ void removeHandler(Handler id);
void dispatch(const std::string& message);
- void dispatch(const std::string& message, const notification& param);
+ void dispatch(const std::string& message, const Notification& param);
private:
- class dispatcher_impl;
- boost::shared_ptr<dispatcher_impl> impl;
+ class DispatcherImpl;
+ boost::shared_ptr<DispatcherImpl> impl_;
};
-} // namespace dc
+} // namespace Mf
-#endif // _DISPATCHER_HH_
+#endif // _MOOF_DISPATCHER_HH_
/** vim: set ts=4 sw=4 tw=80: *************************************************/
*******************************************************************************/
-#ifndef _DRAWABLE_HH_
-#define _DRAWABLE_HH_
+#ifndef _MOOF_DRAWABLE_HH_
+#define _MOOF_DRAWABLE_HH_
-#include "math.hh"
+#include <Moof/Math.hh>
-namespace dc {
+namespace Mf {
/**
* Interface for anything that can be drawn.
*/
-class drawable
+class Drawable
{
public:
- virtual void draw(scalar alpha) = 0;
+ virtual void draw(Scalar alpha) = 0;
};
-} // namespace dc
+} // namespace Mf
-#endif // _DRAWABLE_HH_
+#endif // _MOOF_DRAWABLE_HH_
/** vim: set ts=4 sw=4 tw=80: *************************************************/
*******************************************************************************/
-#include <iostream>
#include <cstdlib> // exit
-#include <string>
+#include <iostream>
#include <stdexcept>
+#include <string>
#include <SDL/SDL.h>
#include "fastevents.h"
-#include "random.hh"
-#include "timer.hh"
-#include "video.hh"
-#include "settings.hh"
-#include "dispatcher.hh"
-
-#include "engine.hh"
+#include "Dispatcher.hh"
+#include "Engine.hh"
+#include "Random.hh"
+#include "Settings.hh"
+#include "Timer.hh"
+#include "Video.hh"
-namespace dc {
+namespace Mf {
-class engine::engine_impl
+class Engine::EngineImpl
{
public:
- engine_impl(const std::string& name, int argc, char* argv[],
- const std::string& configFile, engine* outer) :
- config(argc, argv),
+ EngineImpl(const std::string& name, int argc, char* argv[],
+ const std::string& configFile, Engine* outer) :
+ settings(argc, argv),
interface(outer)
{
if (SDL_Init(SDL_INIT_EVERYTHING | SDL_INIT_EVENTTHREAD) != 0)
throw std::runtime_error(FE_GetError());
}
- rng::seed();
+ setSeed();
- config.loadFromFile(configFile);
+ settings.loadFromFile(configFile);
- screen = video_ptr(new video(name));
- screen->makeActive();
+ video = VideoPtr(new Video(name));
+ video->makeActive();
double ts = 0.01;
- config.get("engine.timestep", ts);
- timestep = scalar(ts);
+ settings.get("engine.timestep", ts);
+ timestep = Scalar(ts);
- long maxfps = 40;
- config.getNumber("video.maxfps", maxfps);
- drawrate = 1.0 / scalar(maxfps);
+ long maxFps = 40;
+ settings.getNumber("video.maxfps", maxFps);
+ drawRate = 1.0 / Scalar(maxFps);
- printfps = false;
- config.get("video.printfps", printfps);
+ printFps = false;
+ settings.get("video.printfps", printFps);
}
- ~engine_impl()
+ ~EngineImpl()
{
// The video object must be destroyed before we can shutdown SDL.
- screen.reset();
+ video.reset();
FE_Quit();
SDL_Quit();
int run()
{
- scalar ticksNow = ticks();
+ Scalar ticksNow = getTicks();
- scalar nextStep = ticksNow;
- scalar nextDraw = ticksNow;
- scalar nextFPSUpdate = ticksNow + 1.0;
+ Scalar nextStep = ticksNow;
+ Scalar nextDraw = ticksNow;
+ Scalar nextFpsUpdate = ticksNow + 1.0;
- scalar totalTime = 0.0;
- scalar deltaTime = 0.0;
- scalar accumulator = timestep;
+ Scalar totalTime = 0.0;
+ Scalar deltaTime = 0.0;
+ Scalar accumulator = timestep;
fps = 0;
int frameAccum = 0;
running = true;
do
{
- scalar newTicks = ticks();
+ Scalar newTicks = getTicks();
deltaTime = newTicks - ticksNow;
ticksNow = newTicks;
{
frameAccum++;
- if (ticksNow >= nextFPSUpdate) // determine the actual fps
+ if (ticksNow >= nextFpsUpdate) // determine the actual fps
{
fps = frameAccum;
frameAccum = 0;
- nextFPSUpdate += 1.0;
- if (ticksNow >= nextFPSUpdate)
+ nextFpsUpdate += 1.0;
+ if (ticksNow >= nextFpsUpdate)
{
- nextFPSUpdate = ticksNow + 1.0;
+ nextFpsUpdate = ticksNow + 1.0;
}
- if (printfps)
+ if (printFps)
{
std::cout << "FPS: " << fps << std::endl;
}
}
interface->draw(accumulator / timestep);
- screen->swap();
+ video->swap();
- nextDraw += drawrate;
+ nextDraw += drawRate;
if (ticksNow >= nextDraw)
{
// we missed some scheduled draws, so reset the schedule
- nextDraw = ticksNow + drawrate;
+ nextDraw = ticksNow + drawRate;
}
}
void dispatchEvents()
{
- SDL_Event e;
+ SDL_Event event;
- while (FE_PollEvent(&e) == 1)
+ while (FE_PollEvent(&event) == 1)
{
- switch (e.type)
+ switch (event.type)
{
case SDL_KEYDOWN:
- if (e.key.keysym.sym == SDLK_ESCAPE &&
+ if (event.key.keysym.sym == SDLK_ESCAPE &&
(SDL_GetModState() & KMOD_CTRL) )
{
exit(0);
break;
case SDL_VIDEORESIZE:
- screen->resize(e.resize.w, e.resize.h);
+ video->resize(event.resize.w, event.resize.h);
break;
}
- interface->handleEvent(e);
+ interface->handleEvent(event);
}
}
- settings config;
- dispatcher relay;
- video_ptr screen;
+ Settings settings;
+ Dispatcher dispatcher;
+ VideoPtr video;
- bool running;
+ bool running;
- scalar timestep;
- scalar drawrate;
+ Scalar timestep;
+ Scalar drawRate;
- long fps;
- bool printfps;
+ long fps;
+ bool printFps;
- engine* interface;
+ Engine* interface;
};
-engine::engine(const std::string& name, int argc, char* argv[],
+Engine::Engine(const std::string& name, int argc, char* argv[],
const std::string& configFile) :
- impl(new engine::engine_impl(name, argc, argv, configFile, this)) {}
+ impl_(new Engine::EngineImpl(name, argc, argv, configFile, this)) {}
-engine::~engine() {}
+Engine::~Engine() {}
-int engine::run()
+int Engine::run()
{
- return impl->run();
+ return impl_->run();
}
-void engine::stop()
+void Engine::stop()
{
- impl->running = false;
+ impl_->running = false;
}
-void engine::setTimestep(scalar ts)
+void Engine::setTimestep(Scalar ts)
{
- impl->timestep = ts;
+ impl_->timestep = ts;
}
-scalar engine::getTimestep()
+Scalar Engine::getTimestep()
{
- return impl->timestep;
+ return impl_->timestep;
}
-void engine::setMaxFPS(long maxfps)
+void Engine::setMaxFrameRate(long maxFps)
{
- impl->drawrate = 1.0 / scalar(maxfps);
+ impl_->drawRate = 1.0 / Scalar(maxFps);
}
-long engine::getMaxFPS()
+long Engine::getMaxFrameRate()
{
- return long(1.0 / impl->drawrate);
+ return long(1.0 / impl_->drawRate);
}
-video& engine::getVideo()
+Video& Engine::getVideo()
{
- return *impl->screen;
+ return *impl_->video;
}
-long engine::getFPS()
+long Engine::getFrameRate()
{
- return impl->fps;
+ return impl_->fps;
}
-void engine::update(scalar t, scalar dt) {}
-void engine::draw(scalar alpha) {}
-void engine::handleEvent(const SDL_Event& e) {}
+void Engine::update(Scalar t, Scalar dt) {}
+void Engine::draw(Scalar alpha) {}
+void Engine::handleEvent(const Event& event) {}
-} // namespace dc
+} // namespace Mf
/** vim: set ts=4 sw=4 tw=80: *************************************************/
*******************************************************************************/
-#ifndef _ENGINE_HH_
-#define _ENGINE_HH_
+#ifndef _MOOF_ENGINE_HH_
+#define _MOOF_ENGINE_HH_
#include <boost/shared_ptr.hpp>
-#include "singleton.hh"
-#include "event.hh"
-#include "dispatcher.hh"
+#include <Moof/Dispatcher.hh>
+#include <Moof/Event.hh>
+#include <Moof/Math.hh>
+#include <Moof/Singleton.hh>
-namespace dc {
+namespace Mf {
-class video;
+// forward declaration
+class Video;
-class engine : public singleton<engine>
+class Engine : public Singleton<Engine>
{
public:
- engine(const std::string& name, int argc, char* argv[],
+ Engine(const std::string& name, int argc, char* argv[],
const std::string& configFile);
- virtual ~engine();
+ virtual ~Engine();
int run();
void stop();
- void setTimestep(scalar ts);
- scalar getTimestep();
- void setMaxFPS(long maxfps);
- long getMaxFPS();
+ void setTimestep(Scalar ts);
+ Scalar getTimestep();
+ void setMaxFrameRate(long maxFps);
+ long getMaxFrameRate();
- video& getVideo();
- long getFPS();
+ Video& getVideo();
+ long getFrameRate();
// Override these if you want.
- virtual void update(scalar t, scalar dt);
- virtual void draw(scalar alpha);
- virtual void handleEvent(const event& e);
+ virtual void update(Scalar t, Scalar dt);
+ virtual void draw(Scalar alpha);
+ virtual void handleEvent(const Event& event);
private:
- class engine_impl;
- boost::shared_ptr<engine_impl> impl;
+ class EngineImpl;
+ boost::shared_ptr<EngineImpl> impl_;
};
-} // namespace dc
+} // namespace Mf
-#endif // _ENGINE_HH_
+#endif // _MOOF_ENGINE_HH_
/** vim: set ts=4 sw=4 tw=80: *************************************************/
*******************************************************************************/
-#ifndef _EVENT_HH_
-#define _EVENT_HH_
+#ifndef _MOOF_EVENT_HH_
+#define _MOOF_EVENT_HH_
#include <SDL/SDL.h>
-namespace dc {
+namespace Mf {
// The event handling in SDL is so big that it would take more time than it's
// to work with, and it is not the purpose of this library to completely hide
// its dependencies and provide full functionality.
-typedef SDL_Event event;
+typedef SDL_Event Event;
-} // namespace dc
+} // namespace Mf
-#endif // _EVENT_HH_
+#endif // _MOOF_EVENT_HH_
/** vim: set ts=4 sw=4 tw=80: *************************************************/
--- /dev/null
+
+/*******************************************************************************
+
+ 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_INTERPOLATOR_HH_
+#define _MOOF_INTERPOLATOR_HH_
+
+
+namespace Mf {
+
+
+class Interpolator
+{
+ void clamp(Scalar& value)
+ {
+ if (value > 1.0)
+ {
+ switch (mode_)
+ {
+ case STOP:
+ value = 1.0;
+ stopped_ = true;
+ break;
+ case REPEAT:
+ value -= 1.0;
+ break;
+ case OSCILLATE:
+ value = 2.0 - value;
+ scale_ *= -1.0;
+ break;
+ }
+ }
+ else if (value < 0.0)
+ {
+ switch (mode_)
+ {
+ case STOP:
+ value = 0.0;
+ stopped_ = true;
+ break;
+ case REPEAT:
+ value += 1.0;
+ break;
+ case OSCILLATE:
+ value = -value;
+ scale_ *= -1.0;
+ break;
+ }
+ }
+ }
+
+public:
+ typedef enum
+ {
+ STOP = 0,
+ REPEAT = 1,
+ OSCILLATE = 2
+ } Mode;
+
+ void init(Scalar seconds = 1.0, Mode mode = STOP)
+ {
+ scale_ = 1.0 / seconds;
+ alpha_ = 0.0;
+ setMode(mode);
+ }
+
+
+ void setMode(Mode mode)
+ {
+ mode_ = mode;
+ stopped_ = false;
+ }
+
+
+ void update(Scalar dt)
+ {
+ if (!stopped_)
+ {
+ alpha_ += dt * scale_;
+ clamp(alpha_);
+ calculate(alpha_);
+ }
+ }
+
+ virtual void calculate(Scalar alpha) = 0;
+
+private:
+ Scalar alpha_;
+ Mode mode_;
+ Scalar scale_;
+ bool stopped_;
+};
+
+template <class T>
+class InterpolatorBase : public Interpolator
+{
+public:
+ void init(Scalar seconds = 1.0, Mode mode = STOP)
+ {
+ Interpolator::init(seconds, mode);
+
+ calculate(0.0); // set value
+ calculate(0.0); // set previous
+ }
+
+ void calculate(Scalar alpha)
+ {
+ previous_ = value_;
+ calculate(value_, alpha);
+ }
+
+ virtual void calculate(T& value, Scalar alpha) = 0;
+
+ const T& getValue()
+ {
+ return value_;
+ }
+
+ const T getState(Scalar alpha)
+ {
+ return cml::lerp(previous_, value_, alpha);
+ }
+
+private:
+ T value_;
+ T previous_;
+};
+
+
+template <class T, int D>
+class BinomialInterpolator : public InterpolatorBase<T>
+{
+public:
+ BinomialInterpolator() {}
+
+ explicit BinomialInterpolator(const T coefficients[D+1],
+ Scalar seconds = 1.0, Interpolator::Mode mode = Interpolator::STOP)
+ {
+ init(coefficients, seconds, mode);
+ }
+
+ void init(const T coefficients[D+1], Scalar seconds = 1.0,
+ Interpolator::Mode mode = Interpolator::STOP)
+ {
+ Scalar fac[D+1];
+
+ fac[0] = 1.0;
+ fac[1] = 1.0;
+
+ // build an array of the computed factorials we will need
+ for (int i = 2; i <= D; i++)
+ {
+ fac[i] = i * fac[i - 1];
+ }
+
+ // combine the coefficients for fast updating
+ for (int i = 0; i <= D; i++)
+ {
+ // n! / (k! * (n - k)!)
+ coefficients_[i] = coefficients[i] * fac[D] / (fac[i] * fac[D - i]);
+ }
+
+ InterpolatorBase<T>::init(seconds, mode);
+ }
+
+
+ void calculate(T& value, Scalar alpha)
+ {
+ Scalar beta = 1.0 - alpha;
+
+ value = coefficients_[0] * std::pow(beta, D);
+
+ for (int i = 1; i <= D; i++)
+ {
+ value += coefficients_[i] * std::pow(beta, D - i) *
+ std::pow(alpha, i);
+ }
+ }
+
+private:
+ T coefficients_[D+1];
+};
+
+
+template <class T>
+class BinomialInterpolator<T,1> : public InterpolatorBase<T>
+{
+public:
+ BinomialInterpolator() {}
+
+ explicit BinomialInterpolator(const T coefficients[2], Scalar seconds = 1.0,
+ Interpolator::Mode mode = Interpolator::STOP)
+ //InterpolatorBase<T>(seconds, mode)
+ {
+ init(coefficients, seconds, mode);
+ }
+
+ void init(const T coefficients[2], Scalar seconds = 1.0,
+ Interpolator::Mode mode = Interpolator::STOP)
+ {
+ a_ = coefficients[0];
+ b_ = coefficients[1];
+
+ InterpolatorBase<T>::init(seconds, mode);
+ }
+
+
+ void calculate(T& value, Scalar alpha)
+ {
+ value = cml::lerp(a_, b_, alpha);
+ }
+
+private:
+ T a_;
+ T b_;
+};
+
+
+// Here are some aliases for more common interpolators. Also see the
+// interpolation functions in cml for other types of interpolation such as
+// slerp and some multi-alpha interpolators.
+
+typedef BinomialInterpolator<Scalar, 1> Lerps; // linear
+typedef BinomialInterpolator<Vector2,1> Lerpv2;
+typedef BinomialInterpolator<Vector3,1> Lerpv3;
+typedef BinomialInterpolator<Vector4,1> Lerpv4;
+
+typedef BinomialInterpolator<Scalar ,2> Qerps; // quadratic
+typedef BinomialInterpolator<Vector2,2> Qerpv2;
+typedef BinomialInterpolator<Vector3,2> Qerpv3;
+typedef BinomialInterpolator<Vector4,2> Qerpv4;
+
+typedef BinomialInterpolator<Scalar ,3> Cerps; // cubic
+typedef BinomialInterpolator<Vector2,3> Cerpv2;
+typedef BinomialInterpolator<Vector3,3> Cerpv3;
+typedef BinomialInterpolator<Vector4,3> Cerpv4;
+
+
+} // namespace Mf
+
+#endif // _MOOF_INTERPOLATOR_HH_
+
+/** vim: set ts=4 sw=4 tw=80: *************************************************/
+
*******************************************************************************/
-#ifndef _MATH_HH_
-#define _MATH_HH_
+#ifndef _MOOF_MATH_HH_
+#define _MOOF_MATH_HH_
/**
- * @file math.hh
+ * @file Math.hh
* General math-related types and functions.
*/
#include <cmath>
#include <cml/cml.h>
-#include <iostream>
-
-namespace dc {
+namespace Mf {
// Basic types.
-typedef float scalar; ///< Scalar type.
+typedef float Scalar; ///< Scalar type.
-typedef cml::vector2f vector2;
-typedef cml::vector3f vector3;
-typedef cml::vector4f vector4;
+typedef cml::vector2f Vector2;
+typedef cml::vector3f Vector3;
+typedef cml::vector4f Vector4;
-typedef cml::matrix33f_c matrix3;
-typedef cml::matrix44f_c matrix4;
+typedef cml::matrix33f_c Matrix3;
+typedef cml::matrix44f_c Matrix4;
-typedef cml::quaternionf_p quaternion;
+typedef cml::quaternionf_p Quaternion;
-typedef vector4 color;
+typedef Vector4 Color;
-const scalar default_epsilon = 0.00001;
+const Scalar EPSILON = 0.000001f;
/**
* Check the equality of scalars with a certain degree of error allowed.
*/
-inline bool equals(scalar a, scalar b, scalar epsilon = default_epsilon)
+inline bool checkEquality(Scalar a, Scalar b, Scalar epsilon = EPSILON)
{
return std::abs(a - b) < epsilon;
}
-} // namespace dc
+} // namespace Mf
-#endif // _MATH_HH_
+#endif // _MOOF_MATH_HH_
/** vim: set ts=4 sw=4 tw=80: *************************************************/
*******************************************************************************/
-#ifndef _MIPPLETON_HH_
-#define _MIPPLETON_HH_
+#ifndef _MOOF_MIPPLETON_HH_
+#define _MOOF_MIPPLETON_HH_
/**
- * @file mippleton.hh
+ * @file Mippleton.hh
* Related to singletons, a mippleton is an object which can be obtained
* globally using a unique name. Unlike singletons, there can be multiple
* mippletons per class, each with a different name or identifier. Mippletons
#include <string>
-namespace dc {
+namespace Mf {
template <class T>
-class mippleton
+class Mippleton
{
typedef std::pair<unsigned,T*> ptr_value_t;
typedef std::pair<std::string,ptr_value_t> ptr_map_pair_t;
std::string name_;
public:
- explicit mippleton(const std::string& name) : name_(name) {}
+ explicit Mippleton(const std::string& name) : name_(name) {}
inline const std::string& getName() const
{
};
template <class T>
-std::map<std::string,std::pair<unsigned,T*> > mippleton<T>::ptrs_;
+std::map<std::string,std::pair<unsigned,T*> > Mippleton<T>::ptrs_;
-} // namespace dc
+} // namespace Mf
-#endif // _MIPPLETON_HH_
+#endif // _MOOF_MIPPLETON_HH_
/** vim: set ts=4 sw=4 tw=80: *************************************************/
*******************************************************************************/
-#ifndef _OPENGL_HH_
-#define _OPENGL_HH_
-
-#ifdef __APPLE__
-#include <OpenGL/gl.h>
-#include <OpenGL/glu.h>
-#include <OpenGL/glext.h>
-#else
-#include <GL/gl.h>
-#include <GL/glu.h>
-#include <GL/glext.h>
-#endif
-
-#endif // _OPENGL_HH_
+#ifndef _MOOF_OPENGL_HH_
+#define _MOOF_OPENGL_HH_
+
+#include <SDL/SDL_opengl.h>
+
+#endif // _MOOF_OPENGL_HH_
/** vim: set ts=4 sw=4 tw=80: *************************************************/
*******************************************************************************/
-#ifndef _PROFILER_HH_
-#define _PROFILER_HH_
+#ifndef _MOOF_PROFILER_HH_
+#define _MOOF_PROFILER_HH_
/**
- * @file profiler.hh
+ * @file Profiler.hh
* Braindead-simple profiler.
*/
#include <ctime>
-namespace dc {
+namespace Mf {
-class profiler
+class Profiler
{
public:
- profiler(const char* name = "")
+ Profiler(const char* name = "")
{
start(name);
}
- ~profiler()
+ ~Profiler()
{
stop();
}
std::clock_t begin;
};
-} // namespace dc
+} // namespace Mf
-#endif // _PROFILER_HH_
+#endif // _MOOF_PROFILER_HH_
/** vim: set ts=4 sw=4 tw=80: *************************************************/
*******************************************************************************/
+#include <climits> // ULONG_MAX
+#include <cmath> // log
#include <cstdlib> // srand, rand, RAND_MAX
#include <ctime> // time
-#include <cmath> // log
-#include <climits> // ULONG_MAX
-#include "random.hh"
+#include "Random.hh"
+
+namespace Mf {
-namespace rng {
-unsigned seed(unsigned theSeed)
+unsigned setSeed(unsigned theSeed)
{
srand(theSeed);
return theSeed;
}
-unsigned seed()
+unsigned setSeed()
{
- return seed(time(0));
+ return setSeed(time(0));
}
template <typename T>
-T get()
+T getRandom()
{
const float ln2 = 0.693147;
static const unsigned bitsPerPiece = std::log(float(RAND_MAX)) / ln2;
template <>
-bool get<bool>()
+bool getRandom<bool>()
{
return rand() % 2;
}
template <typename T>
-T get(T lower, T upper)
+T getRandom(T lower, T upper)
{
- unsigned short randInt = get<unsigned int>();
+ unsigned short randInt = getRandom<unsigned int>();
return lower + T(randInt % (upper - lower + 1));
}
template <>
-float get(float lower, float upper)
+float getRandom(float lower, float upper)
{
- unsigned long randInt = get<unsigned long>();
+ unsigned long randInt = getRandom<unsigned long>();
return (float(randInt) / float(ULONG_MAX)) * (upper - lower) + lower;
}
template <>
-double get(double lower, double upper)
+double getRandom(double lower, double upper)
{
- unsigned long long randInt = get<unsigned long long>();
+ unsigned long long randInt = getRandom<unsigned long long>();
return (double(randInt) / double(ULLONG_MAX)) * (upper - lower) + lower;
}
template <>
-float get()
+float getRandom()
{
- return get<float>(0.0, 1.0);
+ return getRandom<float>(0.0, 1.0);
}
template <>
-double get()
+double getRandom()
{
- return get<double>(0.0, 1.0);
+ return getRandom<double>(0.0, 1.0);
}
-}; // namespace rng
+}; // namespace Mf
/** vim: set ts=4 sw=4 tw=80: *************************************************/
*******************************************************************************/
-#ifndef _RNG_RANDOM_HH_
-#define _RNG_RANDOM_HH_
+#ifndef _MOOF_RANDOM_HH_
+#define _MOOF_RANDOM_HH_
/**
- * @file random.hh
+ * @file Random.hh
* Simple pseudo-random number generators.
*/
-namespace rng {
+namespace Mf {
/**
* Provide the RNG with a seed.
* @return theSeed
*/
-unsigned seed(unsigned theSeed);
+unsigned setSeed(unsigned theSeed);
/**
* Seed the RNG with the current time. This is good enough in most cases.
* @return The seed used.
*/
-unsigned seed();
+unsigned setSeed();
/**
*/
template <typename T>
-T get();
+T getRandom();
/**
*/
template <>
-bool get<bool>();
+bool getRandom<bool>();
/**
*/
template <typename T>
-T get(T lower, T upper);
+T getRandom(T lower, T upper);
/**
*/
template <>
-float get(float lower, float upper);
+float getRandom(float lower, float upper);
/**
* Get a random double with a limited domain.
*/
template <>
-double get(double lower, double upper);
+double getRandom(double lower, double upper);
/**
* Get a random float with a domain limited to [0.0, 1.0].
*/
template <>
-float get();
+float getRandom();
/**
* Get a random double with a domain limited to [0.0, 1.0].
*/
template <>
-double get();
+double getRandom();
-}; // namespace rng
+} // namespace Mf
-#endif // _RNG_RANDOM_HH_
+#endif // _MOOF_RANDOM_HH_
/** vim: set ts=4 sw=4 tw=80: *************************************************/
#include <unistd.h>
-#include "resource.hh"
+#include "Resource.hh"
-namespace dc {
+namespace Mf {
-std::vector<std::string> resource::searchPaths_;
+// static member
+std::vector<std::string> Resource::searchPaths_;
-resource::~resource() {}
+Resource::~Resource() {}
-void resource::addSearchPath(const std::string& directory)
+void Resource::addSearchPath(const std::string& directory)
{
// add a slash if there isn't one already
if (directory[directory.length() - 1] != '/')
}
}
-std::string resource::getPathToResource(const std::string& name)
+std::string Resource::getPathToResource(const std::string& name)
{
- std::vector<std::string>::iterator i;
+ std::vector<std::string>::iterator it;
- for (i = searchPaths_.begin(); i != searchPaths_.end(); i++)
+ for (it = searchPaths_.begin(); it != searchPaths_.end(); it++)
{
- std::string fullPath(*i);
+ std::string fullPath(*it);
fullPath += name;
- // TODO access(2) is not all that portable
+ // TODO this could be more portable
if (access(fullPath.c_str(), R_OK) == 0)
{
return fullPath;
}
-} // namespace dc
+} // namespace Mf
/** vim: set ts=4 sw=4 tw=80: *************************************************/
*******************************************************************************/
-#ifndef _RESOURCE_HH_
-#define _RESOURCE_HH_
+#ifndef _MOOF_RESOURCE_HH_
+#define _MOOF_RESOURCE_HH_
/**
- * @file resource.hh
- * Parent class of textures, sounds, other assets.
+ * @file Resource.hh
+ * Interface for textures, sounds, and other types of resources.
*/
#include <stdexcept>
#include <vector>
-namespace dc {
+namespace Mf {
/**
* Generic resource class.
*/
-class resource
+class Resource
{
public:
- struct exception : public std::runtime_error
+ struct Exception : public std::runtime_error
{
- explicit exception(const std::string& what_arg) :
+ explicit Exception(const std::string& what_arg) :
std::runtime_error(what_arg) {}
};
- virtual ~resource();
+ virtual ~Resource();
/**
};
-} // namespace dc
+} // namespace Mf
-#endif // _RESOURCE_HH_
+#endif // _MOOF_RESOURCE_HH_
/** vim: set ts=4 sw=4 tw=80: *************************************************/
#include <map>
#include <vector>
-#include "aabb.hh"
-#include "camera.hh"
-#include "cullable.hh"
-#include "deserializer.hh"
-#include "drawable.hh"
-#include "math.hh"
-#include "mippleton.hh"
-#include "opengl.hh"
-#include "serializable.hh"
-#include "tilemap.hh"
+#include "Aabb.hh"
+#include "Camera.hh"
+#include "Cullable.hh"
+#include "Deserializer.hh"
+#include "Drawable.hh"
+#include "Math.hh"
+#include "Mippleton.hh"
+#include "OpenGL.hh"
+#include "Scene.hh"
+#include "Serializable.hh"
+#include "Tilemap.hh"
-#include "scene.hh"
+namespace Mf {
-namespace dc {
-
-class scene::scene_impl : public mippleton<scene_impl>
+class Scene::SceneImpl : public Mippleton<SceneImpl>
{
- class scenery : public drawable, public cullable
+ class Scenery : public Drawable, public Cullable
{
public:
- scenery(const matrix4& transform, const std::string& textureName) :
+ Scenery(const Matrix4& transform, const std::string& textureName) :
transformation(transform),
image(textureName) {}
protected:
- matrix4 transformation;
- tilemap image;
+ Matrix4 transformation;
+ Tilemap image;
bool blending;
long detail;
bool fog;
};
- class tiles : public scenery
+ class TilePanel : public Scenery
{
public:
- tiles(const matrix4& transform, const std::string& textureName,
- serializable_ptr root) :
- scenery(transform, textureName),
+ TilePanel(const Matrix4& transform, const std::string& textureName,
+ SerializablePtr root) :
+ Scenery(transform, textureName),
width(1),
height(1)
{
- std::map<std::string,serializable_ptr> rootObj;
+ std::map<std::string,SerializablePtr> rootObj;
if (root->get(rootObj))
{
- std::map<std::string,serializable_ptr>::iterator it;
+ std::map<std::string,SerializablePtr>::iterator it;
if ((it = rootObj.find("width")) != rootObj.end())
{
}
if ((it = rootObj.find("tiles")) != rootObj.end())
{
- std::vector<serializable_ptr> theTiles;
+ std::vector<SerializablePtr> theTiles;
if ((*it).second->get(theTiles))
{
- std::vector<serializable_ptr>::iterator jt;
+ std::vector<SerializablePtr>::iterator jt;
height = theTiles.size() / width;
int w, h;
for (h = height - 1, jt = theTiles.begin();
jt != theTiles.end(); h--)
{
- std::vector<unsigned> row;
+ std::vector<Tilemap::Index> row;
for (w = 0; w < width && jt != theTiles.end();
w++, jt++)
if ((*jt)->get(index))
{
- row.push_back(unsigned(index));
+ row.push_back(Tilemap::Index(index));
}
}
}
}
- void draw(scalar alpha)
+ void draw(Scalar alpha)
{
glPushMatrix();
//std::cout << "transforming..." << std::endl;
image.bind();
long x, y;
- scalar xf, yf;
+ Scalar xf, yf;
for (y = 0, yf = 0.0; y < height; y++, yf += 1.0)
{
for (x = 0, xf = 0.0; x < width; x++, xf += 1.0)
{
- scalar texCoords[8];
+ Scalar texCoords[8];
- unsigned index = indices[y][x];
+ Tilemap::Index index = indices[y][x];
if (image.getTileCoords(index, texCoords))
{
glPopMatrix();
}
- bool isVisible(const camera& cam)
+ bool isVisible(const Camera& cam)
{
return true;
}
private:
long width, height;
- std::vector<std::vector<unsigned> > indices;
+ std::vector<std::vector<Tilemap::Index> > indices;
};
- class billboard : public scenery
+ class Billboard : public Scenery
{
public:
- billboard(const matrix4& transform, const std::string& textureName,
- serializable_ptr root) :
- scenery(transform, textureName),
+ Billboard(const Matrix4& transform, const std::string& textureName,
+ SerializablePtr root) :
+ Scenery(transform, textureName),
index(0)
{
- std::map<std::string,serializable_ptr> rootObj;
+ std::map<std::string,SerializablePtr> rootObj;
if (root->get(rootObj))
{
- std::map<std::string,serializable_ptr>::iterator it;
+ std::map<std::string,SerializablePtr>::iterator it;
if ((it = rootObj.find("tile")) != rootObj.end())
{
long value;
if ((*it).second->get(value))
{
- index = unsigned(value);
+ index = Tilemap::Index(value);
}
}
}
image.getTileCoords(index, texCoords);
}
- void draw(scalar alpha)
+ void draw(Scalar alpha)
{
glPushMatrix();
glMultMatrixf(transformation.data());
glPopMatrix();
}
- bool isVisible(const camera& cam)
+ bool isVisible(const Camera& cam)
{
return false;
}
private:
- unsigned index;
- scalar texCoords[8];
+ Tilemap::Index index;
+ Scalar texCoords[8];
};
- static bool loadBox(aabb& theBox, serializable_ptr obj)
+ static bool loadBox(Aabb& theBox, SerializablePtr obj)
{
- std::vector<serializable_ptr> numbers;
+ std::vector<SerializablePtr> numbers;
if (obj->get(numbers))
{
}
public:
- scene_impl(const std::string& name) :
- mippleton<scene_impl>(name)
+ SceneImpl(const std::string& name) :
+ Mippleton<SceneImpl>(name)
{
loadFromFile();
}
- void loadInstructions(serializable_ptr root)
+ void loadInstructions(SerializablePtr root)
{
- std::vector<serializable_ptr> rootObj;
+ std::vector<SerializablePtr> rootObj;
if (root->get(rootObj))
{
- std::vector<serializable_ptr>::iterator it;
+ std::vector<SerializablePtr>::iterator it;
- matrix4 transform;
- std::string texture;
+ Matrix4 transform;
+ std::string texture;
for (it = rootObj.begin(); it != rootObj.end(); it++)
{
}
else if (instruction == "translate")
{
- std::vector<serializable_ptr> values;
+ std::vector<SerializablePtr> values;
it++;
if ((*it)->get(values))
{
- vector3 vec;
+ Vector3 vec;
- for (unsigned i = 0; i < values.size(); i++)
+ for (size_t i = 0; i < values.size(); i++)
{
double value;
}
}
- matrix4 translation;
+ Matrix4 translation;
cml::matrix_translation(translation, vec);
transform = translation * transform;
//std::cout << "TRANSLATE\t" << vec << std::endl
}
else if (instruction == "scale")
{
- std::vector<serializable_ptr> values;
+ std::vector<SerializablePtr> values;
it++;
if ((*it)->get(values))
values[0]->getNumber(value);
- matrix4 scaling;
- cml::matrix_uniform_scale(scaling, scalar(value));
+ Matrix4 scaling;
+ cml::matrix_uniform_scale(scaling, Scalar(value));
transform = scaling * transform;
//std::cout << "SCALE\t\t" << value << std::endl
//<< transform << std::endl;
}
else if (values.size() == 3)
{
- vector3 vec;
+ Vector3 vec;
- for (unsigned i = 0; i < values.size(); i++)
+ for (size_t i = 0; i < values.size(); i++)
{
double value;
}
}
- matrix4 scaling;
+ Matrix4 scaling;
cml::matrix_scale(scaling, vec);
transform = scaling * transform;
//std::cout << "SCALE\t\t" << vec << std::endl
}
else if (instruction == "rotate")
{
- std::vector<serializable_ptr> values;
+ std::vector<SerializablePtr> values;
it++;
if ((*it)->get(values))
}
cml::matrix_rotate_about_local_axis(transform,
- axisIndex, scalar(value * cml::constantsd::rad_per_deg()));
+ axisIndex, Scalar(value * cml::constantsd::rad_per_deg()));
//std::cout << "ROTATE\t" << axis << " " << value << std::endl
//<< transform << std::endl;
}
//std::cout << transform << std::endl;
it++;
- tiles* newTiles = new tiles(transform, texture, *it);
- boost::shared_ptr<scenery> sceneItem(newTiles);
+ TilePanel* tilePanel = new TilePanel(transform, texture,
+ *it);
+ boost::shared_ptr<Scenery> sceneItem(tilePanel);
objects.push_back(sceneItem);
}
else if (instruction == "billboard")
//std::cout << transform << std::endl;
it++;
- billboard* newBB = new billboard(transform, texture,
+ Billboard* billboard = new Billboard(transform, texture,
*it);
- boost::shared_ptr<scenery> sceneItem(newBB);
+ boost::shared_ptr<Scenery> sceneItem(billboard);
objects.push_back(sceneItem);
}
}
void loadFromFile()
{
- std::string filePath = scene::getPathToResource(getName());
+ std::string filePath = Scene::getPathToResource(getName());
- deserializer in(filePath, true);
+ Deserializer deserializer(filePath, true);
- serializable_ptr root = in.deserialize();
+ SerializablePtr root = deserializer.deserialize();
if (root)
{
- std::map<std::string,serializable_ptr> rootObj;
+ std::map<std::string,SerializablePtr> rootObj;
if (root->get(rootObj))
{
- std::map<std::string,serializable_ptr>::iterator it;
+ std::map<std::string,SerializablePtr>::iterator it;
if ((it = rootObj.find("playfield_bounds")) != rootObj.end())
{
}
- void draw(scalar alpha)
+ void draw(Scalar alpha)
{
- scenery_list::iterator it;
+ SceneryVector::iterator it;
for (it = objects.begin(); it != objects.end(); it++)
{
}
- aabb playfieldBounds;
- aabb maximumBounds;
+ Aabb playfieldBounds;
+ Aabb maximumBounds;
- typedef std::vector<boost::shared_ptr<scenery> > scenery_list;
- scenery_list objects;
+ typedef std::vector<boost::shared_ptr<Scenery> > SceneryVector;
+ SceneryVector objects;
};
-scene::scene(const std::string& name) :
+Scene::Scene(const std::string& name) :
// pass through
- impl(scene::scene_impl::retain(name), &scene::scene_impl::release) {}
+ impl_(Scene::SceneImpl::retain(name), &Scene::SceneImpl::release) {}
-void scene::draw(scalar alpha)
+void Scene::draw(Scalar alpha)
{
// pass through
- impl->draw(alpha);
+ impl_->draw(alpha);
}
* "scenes" subdirectory of any of the searched directories.
*/
-std::string scene::getPathToResource(const std::string& name)
+std::string Scene::getPathToResource(const std::string& name)
{
- return resource::getPathToResource("scenes/" + name + ".json");
+ return Resource::getPathToResource("scenes/" + name + ".json");
}
-} // namespace dc
+} // namespace Mf
/** vim: set ts=4 sw=4 tw=80: *************************************************/
*******************************************************************************/
-#ifndef _SCENE_HH_
-#define _SCENE_HH_
+#ifndef _MOOF_SCENE_HH_
+#define _MOOF_SCENE_HH_
#include <string>
+
#include <boost/shared_ptr.hpp>
-#include "resource.hh"
-#include "drawable.hh"
+#include <Moof/Drawable.hh>
+#include <Moof/Resource.hh>
-namespace dc {
+namespace Mf {
-class scene : public resource, public drawable
+class Scene : public Resource, public Drawable
{
public:
- scene(const std::string& name);
+ Scene(const std::string& name);
- void draw(scalar alpha);
+ void draw(Scalar alpha);
static std::string getPathToResource(const std::string& name);
private:
- class scene_impl;
- boost::shared_ptr<scene_impl> impl;
+ class SceneImpl;
+ boost::shared_ptr<SceneImpl> impl_;
};
-} // namespace dc
+} // namespace Mf
-#endif // _SCENE_HH_
+#endif // _MOOF_SCENE_HH_
/** vim: set ts=4 sw=4 tw=80: *************************************************/
*******************************************************************************/
-#include "serializable.hh"
+#include "Serializable.hh"
-namespace dc {
+namespace Mf {
-serializable::~serializable()
+Serializable::~Serializable()
{
}
-bool serializable::get(long& value)
+bool Serializable::get(long& value)
{
return false;
}
-bool serializable::get(double& value)
+bool Serializable::get(double& value)
{
return false;
}
-bool serializable::get(bool& value)
+bool Serializable::get(bool& value)
{
return false;
}
-bool serializable::get(std::string& value)
+bool Serializable::get(std::string& value)
{
return false;
}
-bool serializable::get(std::wstring& value)
+bool Serializable::get(std::wstring& value)
{
return false;
}
-bool serializable::get(std::vector<serializable_ptr>& value)
+bool Serializable::get(std::vector<SerializablePtr>& value)
{
return false;
}
-bool serializable::get(std::map<std::string,serializable_ptr>& value)
+bool Serializable::get(std::map<std::string,SerializablePtr>& value)
{
return false;
}
-bool serializable::isNull()
+bool Serializable::isNull()
{
return false;
}
-bool serializable::getNumber(long& value)
+bool Serializable::getNumber(long& value)
{
if (get(value))
{
}
else
{
- double dValue;
- if (get(dValue))
+ double doubleValue;
+ if (get(doubleValue))
{
- value = long(dValue);
+ value = long(doubleValue);
return true;
}
}
return false;
}
-bool serializable::getNumber(double& value)
+bool Serializable::getNumber(double& value)
{
if (get(value))
{
}
else
{
- long lValue;
- if (get(lValue))
+ long longValue;
+ if (get(longValue))
{
- value = double(lValue);
+ value = double(longValue);
return true;
}
}
}
-} // namespace dc
+} // namespace Mf
/** vim: set ts=4 sw=4 tw=80: *************************************************/
*******************************************************************************/
-#ifndef _SERIALIZABLE_HH_
-#define _SERIALIZABLE_HH_
+#ifndef _MOOF_SERIALIZABLE_HH_
+#define _MOOF_SERIALIZABLE_HH_
#include <iostream>
-#include <string>
#include <map>
+#include <string>
#include <vector>
-#include "stringtools.hh"
-#include "serializer.hh"
-#include "deserializer.hh"
+#include <Moof/Deserializer.hh>
+#include <Moof/Serializer.hh>
+#include <Moof/StringTools.hh>
+
+namespace Mf {
-namespace dc {
+/**
+ * Interface for a type which can be serialized and deserialized.
+ */
-class serializable
+class Serializable
{
public:
- virtual ~serializable();
+ virtual ~Serializable();
- virtual void serialize(serializer& out) const = 0;
- virtual void deserialize(deserializer& in) = 0;
+ virtual void serialize(Serializer& out) const = 0;
+ virtual void deserialize(Deserializer& in) = 0;
virtual void print() const = 0;
virtual bool get(bool& value);
virtual bool get(std::string& value);
virtual bool get(std::wstring& value);
- virtual bool get(std::vector<serializable_ptr>& value);
- virtual bool get(std::map<std::string,serializable_ptr>& value);
+ virtual bool get(std::vector<SerializablePtr>& value);
+ virtual bool get(std::map<std::string,SerializablePtr>& value);
/*
* To get a number value which may have been parsed as either an integer or
- * double, use these instead.
+ * double, use these getters instead.
*/
bool getNumber(long&);
template <class T>
-class wrapper : public serializable
+class SerializableBase : public Serializable
{
public:
- wrapper() {}
- wrapper(const T& var) : variable(var) {}
+ SerializableBase() {}
+ SerializableBase(const T& value) :
+ value_(value) {}
- void serialize(serializer& out) const;
- void deserialize(deserializer& in);
+ void serialize(Serializer& out) const;
+ void deserialize(Deserializer& in);
void print() const;
bool get(T& value);
public:
- T variable;
+ T value_;
};
-class null : public serializable
+class SerializableNull : public Serializable
{
public:
- null() {}
- void serialize(serializer& out) const;
- void deserialize(deserializer& in);
+ SerializableNull() {}
+ void serialize(Serializer& out) const;
+ void deserialize(Deserializer& in);
void print() const;
bool isNull();
};
-typedef wrapper<long> wrapped_integer;
-typedef wrapper<double> wrapped_real;
-typedef wrapper<bool> wrapped_boolean;
-typedef wrapper<std::string> wrapped_string;
-typedef wrapper<std::wstring> wrapped_wstring;
-typedef wrapper<std::vector<serializable_ptr> > wrapped_array;
-typedef wrapper<std::map<std::string,serializable_ptr> > wrapped_dictionary;
+typedef SerializableBase<long> SerializableInteger;
+typedef SerializableBase<double> SerializableReal;
+typedef SerializableBase<bool> SerializableBoolean;
+typedef SerializableBase<std::string> SerializableString;
+typedef SerializableBase<std::wstring> SerializableWideString;
+typedef SerializableBase<std::vector<SerializablePtr> > SerializableArray;
+typedef SerializableBase<std::map<std::string,SerializablePtr> >
+ SerializableMap;
template <class T>
-inline void wrapper<T>::serialize(serializer& out) const
+inline void SerializableBase<T>::serialize(Serializer& out) const
{
- out.push(variable);
+ out.push(value_);
}
template <>
inline void
-wrapper<std::vector<serializable_ptr> >::serialize(serializer& out) const
+SerializableBase<std::vector<SerializablePtr> >::serialize(Serializer& out) const
{
out.pushArrayHead();
- std::vector<serializable_ptr>::const_iterator i;
- for (i = variable.begin(); i < variable.end(); i++)
+ std::vector<SerializablePtr>::const_iterator i;
+ for (i = value_.begin(); i < value_.end(); i++)
{
(*i)->serialize(out);
}
template <>
inline void
-wrapper<std::map<std::string,serializable_ptr> >::serialize(serializer& out) const
+SerializableBase<std::map<std::string,SerializablePtr> >::serialize(Serializer& out) const
{
out.pushMapHead();
- std::map<std::string,serializable_ptr>::const_iterator i;
- for (i = variable.begin(); i != variable.end(); i++)
+ std::map<std::string,SerializablePtr>::const_iterator i;
+ for (i = value_.begin(); i != value_.end(); i++)
{
out.push((*i).first);
(*i).second->serialize(out);
out.pushMapTail();
}
-inline void null::serialize(serializer& out) const
+inline void SerializableNull::serialize(Serializer& out) const
{
out.pushNull();
}
template <class T>
-inline void wrapper<T>::deserialize(deserializer& in)
+inline void SerializableBase<T>::deserialize(Deserializer& in)
{
in.pop();
}
template <>
-inline void wrapper<std::vector<serializable_ptr> >::deserialize(deserializer& in)
+inline void SerializableBase<std::vector<SerializablePtr> >::deserialize(Deserializer& in)
{
- serializable_ptr obj;
+ SerializablePtr obj;
in.pop();
while (obj = in.deserialize())
{
- variable.push_back(serializable_ptr(obj));
+ value_.push_back(SerializablePtr(obj));
}
in.pop();
template <>
inline void
-wrapper<std::map<std::string,serializable_ptr> >::deserialize(deserializer& in)
+SerializableBase<std::map<std::string,SerializablePtr> >::deserialize(Deserializer& in)
{
- serializable_ptr obj;
+ SerializablePtr obj;
in.pop();
std::string key;
if (obj->get(key))
{
- variable[key] = in.deserialize();
+ value_[key] = in.deserialize();
}
}
in.pop();
}
-inline void null::deserialize(deserializer& in)
+inline void SerializableNull::deserialize(Deserializer& in)
{
in.pop();
}
template <class T>
-inline void wrapper<T>::print() const
+inline void SerializableBase<T>::print() const
{
- std::cout << std::boolalpha << typeid(T).name() << "(" << variable << ")";
+ std::cout << std::boolalpha << typeid(T).name() << "(" << value_ << ")";
}
template <>
-inline void wrapper<std::wstring>::print() const
+inline void SerializableBase<std::wstring>::print() const
{
- std::wcout << variable;
+ std::wcout << value_;
}
template <>
-inline void wrapper<std::vector<serializable_ptr> >::print() const
+inline void SerializableBase<std::vector<SerializablePtr> >::print() const
{
std::cout << "array";
}
template <>
-inline void wrapper<std::map<std::string,serializable_ptr> >::print() const
+inline void SerializableBase<std::map<std::string,SerializablePtr> >::print() const
{
- std::cout << "dictionary";
+ std::cout << "map";
}
-inline void null::print() const
+inline void SerializableNull::print() const
{
std::cout << "null";
}
template <class T>
-inline bool wrapper<T>::get(T& value)
+inline bool SerializableBase<T>::get(T& value)
{
- value = variable;
+ value = value_;
return true;
}
-inline bool null::isNull()
+inline bool SerializableNull::isNull()
{
return true;
}
-} // namespace dc
+} // namespace Mf
-#endif // _SERIALIZABLE_HH_
+#endif // _MOOF_SERIALIZABLE_HH_
/** vim: set ts=4 sw=4 tw=80: *************************************************/
#include <yajl/yajl_gen.h>
-#include "stringtools.hh"
-#include "serializer.hh"
+#include "Serializer.hh"
+#include "StringTools.hh"
-namespace dc {
+namespace Mf {
-class serializer::serializer_impl
+class Serializer::SerializerImpl
{
public:
- serializer_impl(const std::string& filePath, const std::string& indent = "")
+ SerializerImpl(const std::string& filePath, const std::string& indent = "")
{
std::ofstream* output = new std::ofstream(filePath.c_str());
init(*output, true, indent);
}
- serializer_impl(std::ostream& output, const std::string& indent = "")
+ SerializerImpl(std::ostream& output, const std::string& indent = "")
{
init(output, false, indent);
}
- ~serializer_impl()
+ ~SerializerImpl()
{
if (deleteWhenDone)
{
switch (err)
{
case yajl_gen_generation_complete:
- throw serializer::exception("the archive has already terminated");
+ throw Serializer::Exception("the archive has already terminated");
case yajl_gen_keys_must_be_strings:
- throw serializer::exception("map keys must be strings");
+ throw Serializer::Exception("map keys must be strings");
case yajl_max_depth_exceeded:
- throw serializer::exception("maximum archive depth exceeded");
+ throw Serializer::Exception("maximum archive depth exceeded");
case yajl_gen_in_error_state:
- throw serializer::exception("serializer already in error state");
+ throw Serializer::Exception("serializer already in error state");
case yajl_gen_status_ok:
; // There is no error here. Move along...
}
}
- yajl_gen gen;
+ yajl_gen gen;
- std::ostream* out;
- bool deleteWhenDone;
+ std::ostream* out;
+ bool deleteWhenDone;
private:
void init(std::ostream& output, bool deleteOut, const std::string& indent)
{
config.beautify = true;
config.indentString = 0;
- // FIXME: a yajl bug prevents using heap-allocated strings
+ // FIXME a yajl bug prevents using heap-allocated strings
//config.indentString = indent.c_str();
}
else
};
-serializer::serializer(const std::string& filePath, const std::string& indent) :
+Serializer::Serializer(const std::string& filePath, const std::string& indent) :
// pass through
- impl(new serializer::serializer_impl(filePath, indent)) {}
+ impl_(new Serializer::SerializerImpl(filePath, indent)) {}
-serializer::serializer(std::ostream& output, const std::string& indent) :
+Serializer::Serializer(std::ostream& output, const std::string& indent) :
// pass through
- impl(new serializer::serializer_impl(output, indent)) {}
+ impl_(new Serializer::SerializerImpl(output, indent)) {}
-serializer::~serializer()
+Serializer::~Serializer()
{
flush();
}
-void serializer::push(long value)
+void Serializer::push(long value)
{
- yajl_gen_status stat = yajl_gen_integer(impl->gen, value);
+ yajl_gen_status stat = yajl_gen_integer(impl_->gen, value);
if (stat != yajl_gen_status_ok)
- serializer::serializer_impl::throwError(stat);
+ Serializer::SerializerImpl::throwError(stat);
}
-void serializer::push(double value)
+void Serializer::push(double value)
{
- yajl_gen_status stat = yajl_gen_double(impl->gen, value);
+ yajl_gen_status stat = yajl_gen_double(impl_->gen, value);
if (stat != yajl_gen_status_ok)
- serializer::serializer_impl::throwError(stat);
+ Serializer::SerializerImpl::throwError(stat);
}
-void serializer::push(bool value)
+void Serializer::push(bool value)
{
- yajl_gen_status stat = yajl_gen_bool(impl->gen, value);
+ yajl_gen_status stat = yajl_gen_bool(impl_->gen, value);
if (stat != yajl_gen_status_ok)
- serializer::serializer_impl::throwError(stat);
+ Serializer::SerializerImpl::throwError(stat);
}
-void serializer::push(const std::string& value)
+void Serializer::push(const std::string& value)
{
- yajl_gen_status stat = yajl_gen_string(impl->gen,
+ yajl_gen_status stat = yajl_gen_string(impl_->gen,
(const unsigned char*)value.c_str(), value.length());
if (stat != yajl_gen_status_ok)
- serializer::serializer_impl::throwError(stat);
+ Serializer::SerializerImpl::throwError(stat);
}
-void serializer::push(const std::wstring& value)
+void Serializer::push(const std::wstring& value)
{
push(wideToMulti(value));
}
-void serializer::pushNull()
+void Serializer::pushNull()
{
- yajl_gen_status stat = yajl_gen_null(impl->gen);
+ yajl_gen_status stat = yajl_gen_null(impl_->gen);
if (stat != yajl_gen_status_ok)
- serializer::serializer_impl::throwError(stat);
+ Serializer::SerializerImpl::throwError(stat);
}
-void serializer::pushMapHead()
+void Serializer::pushMapHead()
{
- yajl_gen_status stat = yajl_gen_map_open(impl->gen);
+ yajl_gen_status stat = yajl_gen_map_open(impl_->gen);
if (stat != yajl_gen_status_ok)
- serializer::serializer_impl::throwError(stat);
+ Serializer::SerializerImpl::throwError(stat);
}
-void serializer::pushMapTail()
+void Serializer::pushMapTail()
{
- yajl_gen_status stat = yajl_gen_map_close(impl->gen);
+ yajl_gen_status stat = yajl_gen_map_close(impl_->gen);
if (stat != yajl_gen_status_ok)
- serializer::serializer_impl::throwError(stat);
+ Serializer::SerializerImpl::throwError(stat);
}
-void serializer::pushArrayHead()
+void Serializer::pushArrayHead()
{
- yajl_gen_status stat = yajl_gen_array_open(impl->gen);
+ yajl_gen_status stat = yajl_gen_array_open(impl_->gen);
if (stat != yajl_gen_status_ok)
- serializer::serializer_impl::throwError(stat);
+ Serializer::SerializerImpl::throwError(stat);
}
-void serializer::pushArrayTail()
+void Serializer::pushArrayTail()
{
- yajl_gen_status stat = yajl_gen_array_close(impl->gen);
+ yajl_gen_status stat = yajl_gen_array_close(impl_->gen);
if (stat != yajl_gen_status_ok)
- serializer::serializer_impl::throwError(stat);
+ Serializer::SerializerImpl::throwError(stat);
}
-void serializer::flush()
+void Serializer::flush()
{
const unsigned char* buffer;
unsigned length;
- yajl_gen_get_buf(impl->gen, &buffer, &length);
- impl->out->write((const char*)buffer, length);
- yajl_gen_clear(impl->gen);
+ yajl_gen_get_buf(impl_->gen, &buffer, &length);
+ impl_->out->write((const char*)buffer, length);
+ yajl_gen_clear(impl_->gen);
}
-} // namespace dc
+} // namespace Mf
/** vim: set ts=4 sw=4 tw=80: *************************************************/
*******************************************************************************/
-#ifndef _SERIALIZER_HH_
-#define _SERIALIZER_HH_
+#ifndef _MOOF_SERIALIZER_HH_
+#define _MOOF_SERIALIZER_HH_
/**
- * @file serializer.hh
+ * @file Serializer.hh
* Serialize structures and types for output on a stream.
*/
-#include <ostream>
-#include <string>
#include <stdexcept>
+#include <string>
+#include <ostream>
#include <boost/shared_ptr.hpp>
-namespace dc {
+namespace Mf {
-class serializer
+class Serializer
{
public:
* but will be tightly packed.
*/
- serializer(const std::string& filePath, const std::string& indent = "");
- serializer(std::ostream& output, const std::string& indent = "");
+ Serializer(const std::string& filePath, const std::string& indent = "");
+ Serializer(std::ostream& output, const std::string& indent = "");
- ~serializer();
+ ~Serializer();
/**
* Push various types of data onto the stream.
* This exception is thrown for serializer-related exceptional errors.
*/
- struct exception : std::runtime_error
+ struct Exception : std::runtime_error
{
- explicit exception(const std::string& what_arg) :
+ explicit Exception(const std::string& what_arg) :
std::runtime_error(what_arg) {}
};
private:
- class serializer_impl;
- boost::shared_ptr<serializer_impl> impl;
+ class SerializerImpl;
+ boost::shared_ptr<SerializerImpl> impl_;
};
-} // namespace dc
+} // namespace Mf
-#endif // _SERIALIZER_HH_
+#endif // _MOOF_SERIALIZER_HH_
/** vim: set ts=4 sw=4 tw=80: *************************************************/
#include <boost/algorithm/string.hpp>
-#include "settings.hh"
+#include "Settings.hh"
-namespace dc {
+namespace Mf {
-settings::settings(int argc, char* argv[])
+Settings::Settings(int argc, char* argv[])
{
parseArgs(argc, argv);
}
-void settings::parseArgs(int argc, char* argv[])
+void Settings::parseArgs(int argc, char* argv[])
{
for (int i = 1; i < argc; i++)
{
std::stringstream stream;
stream << stringValue << std::endl;
- deserializer in(stream);
+ Deserializer deserializer(stream);
try
{
- serializable_ptr value(in.deserialize());
- map[key] = value;
+ SerializablePtr value(deserializer.deserialize());
+ map_[key] = value;
}
catch (std::exception e)
{
// it doesn't deserialize to anything we know, so just store it
// as a string
- map[key] = serializable_ptr(new wrapped_string(stringValue));
+ map_[key] = SerializablePtr(new SerializableString(stringValue));
}
}
}
}
-void settings::loadFromFile(const std::string& filePath, bool precedence)
+void Settings::loadFromFile(const std::string& filePath, bool precedence)
{
std::vector<std::string> paths;
boost::split(paths, filePath, boost::is_any_of(":"));
loadFromFiles(paths, precedence);
}
-void settings::loadFromFiles(const std::vector<std::string>& filePaths,
+void Settings::loadFromFiles(const std::vector<std::string>& filePaths,
bool precedence)
{
std::vector<std::string>::const_iterator it;
boost::replace_first(path, "$HOME", home);
}
- deserializer in(*it, true);
+ Deserializer deserializer(*it, true);
std::cout << "Looking for a config file at " << path << std::endl;
try
{
- serializable_ptr obj = in.deserialize();
- std::map<std::string,serializable_ptr> dict;
- if (obj && obj->get(dict))
+ SerializablePtr obj = deserializer.deserialize();
+ std::map<std::string,SerializablePtr> map;
+ if (obj && obj->get(map))
{
if (!precedence)
{
- map.insert(dict.begin(), dict.end());
+ map_.insert(map.begin(), map.end());
}
else
{
- dict.insert(map.begin(), map.end());
- map = dict;
+ map.insert(map_.begin(), map_.end());
+ map_ = map;
}
}
}
- catch (deserializer::exception e)
+ catch (Deserializer::Exception e)
{
std::cerr << "Cannot load settings from " << *it <<
" because an exception was thrown: " << e.what() << std::endl;
}
-} // namepsace dc
+} // namepsace Mf
/** vim: set ts=4 sw=4 tw=80: *************************************************/
*******************************************************************************/
-#ifndef _SETTINGS_HH_
-#define _SETTINGS_HH_
+#ifndef _MOOF_SETTINGS_HH_
+#define _MOOF_SETTINGS_HH_
/**
- * @file settings.hh
+ * @file Settings.hh
* Load, store, save program settings.
*/
-#include <string>
#include <map>
+#include <string>
-#include "singleton.hh"
-#include "serializable.hh"
+#include <Moof/Singleton.hh>
+#include <Moof/Serializable.hh>
-namespace dc {
+namespace Mf {
-class settings : public singleton<settings>
+class Settings : public Singleton<Settings>
{
public:
- settings() {}
- settings(int argc, char* argv[]);
+ Settings() {}
+ Settings(int argc, char* argv[]);
void parseArgs(int argc, char* argv[]);
bool getNumber(const std::string& key, T& value);
private:
- std::map<std::string,serializable_ptr> map;
+ std::map<std::string,SerializablePtr> map_;
};
template <typename T>
-bool settings::get(const std::string& key, T& value)
+bool Settings::get(const std::string& key, T& value)
{
- std::map<std::string,serializable_ptr>::const_iterator i = map.find(key);
+ std::map<std::string,SerializablePtr>::const_iterator it = map_.find(key);
- if (i != map.end())
+ if (it != map_.end())
{
- serializable_ptr obj = (*i).second;
+ SerializablePtr obj = (*it).second;
return obj->get(value);
}
else
}
template <typename T>
-bool settings::getNumber(const std::string& key, T& value)
+bool Settings::getNumber(const std::string& key, T& value)
{
- std::map<std::string,serializable_ptr>::const_iterator i = map.find(key);
+ std::map<std::string,SerializablePtr>::const_iterator it = map_.find(key);
- if (i != map.end())
+ if (it != map_.end())
{
- serializable_ptr obj = (*i).second;
+ SerializablePtr obj = (*it).second;
return obj->getNumber(value);
}
else
}
}
-} // namepsace dc
-#endif // _SETTINGS_HH_
+} // namepsace Mf
+
+#endif // _MOOF_SETTINGS_HH_
/** vim: set ts=4 sw=4 tw=80: *************************************************/
*******************************************************************************/
-#ifndef _SINGLETON_HH_
-#define _SINGLETON_HH_
+#ifndef _MOOF_SINGLETON_HH_
+#define _MOOF_SINGLETON_HH_
#include <stdexcept>
-namespace dc {
+namespace Mf {
template <typename T>
-class singleton
+class Singleton
{
static T* ptr_;
public:
- struct exception : public std::runtime_error
+ struct Exception : public std::runtime_error
{
- explicit exception(const std::string& what_arg) :
+ explicit Exception(const std::string& what_arg) :
std::runtime_error(what_arg) {}
};
- singleton()
+ Singleton()
{
if (!ptr_)
{
// This hack is from Game Programming Gems.
- long long offset = (long long)(T*)1 - (long long)(singleton<T>*)(T*)1;
+ long long offset = (long long)(T*)1 - (long long)(Singleton<T>*)(T*)1;
ptr_ = (T*)((long long)this + offset);
}
}
- ~singleton()
+ ~Singleton()
{
- long long offset = (long long)(T*)1 - (long long)(singleton<T>*)(T*)1;
+ long long offset = (long long)(T*)1 - (long long)(Singleton<T>*)(T*)1;
if (ptr_ == (T*)((long long)this + offset))
{
ptr_ = 0;
{
if (!ptr_)
{
- throw exception("accessing uninstantiated singleton");
+ throw Exception("accessing uninstantiated singleton");
}
return *ptr_;
}
}
};
-template <typename T> T* singleton<T>::ptr_ = 0;
+template <typename T> T* Singleton<T>::ptr_ = 0;
-} // namespace dc
+} // namespace Mf
-#endif // _SINGLETON_HH_
+#endif // _MOOF_SINGLETON_HH_
/** vim: set ts=4 sw=4 tw=80: *************************************************/
#include "ConvertUTF.h"
-#include "stringtools.hh"
+#include "StringTools.hh"
-namespace dc {
+namespace Mf {
std::wstring multiToWide(const std::string& multiStr)
*targetStart = 0;
std::wstring convertedStr(wideStr);
delete[] wideStr;
+
return convertedStr;
}
else if (sizeof(wchar_t) == 4)
*targetStart = 0;
std::wstring convertedStr(wideStr);
delete[] wideStr;
+
return convertedStr;
}
else
*targetStart = 0;
std::string convertedStr(multiStr);
delete[] multiStr;
+
return convertedStr;
}
else if (sizeof(wchar_t) == 4)
*targetStart = 0;
std::string convertedStr(multiStr);
delete[] multiStr;
+
return convertedStr;
}
else
}
-} // namespace dc
+} // namespace Mf
/** vim: set ts=4 sw=4 tw=80: *************************************************/
*******************************************************************************/
-#ifndef _STRINGTOOLS_HH_
-#define _STRINGTOOLS_HH_
+#ifndef _MOOF_STRINGTOOLS_HH_
+#define _MOOF_STRINGTOOLS_HH_
#include <string>
-namespace dc {
+namespace Mf {
std::wstring multiToWide(const std::string& multiStr);
std::string wideToMulti(const std::wstring& wideStr);
-} // namespace dc
+} // namespace Mf
-#endif // _STRINGTOOLS_HH_
+#endif // _MOOF_STRINGTOOLS_HH_
/** vim: set ts=4 sw=4 tw=80: *************************************************/
#include <SDL/SDL.h>
#include <SDL/SDL_image.h>
-#include "mippleton.hh"
+#include "Dispatcher.hh"
+#include "Mippleton.hh"
+#include "OpenGL.hh"
+#include "Texture.hh"
-#include "dispatcher.hh"
-#include "opengl.hh"
-#include "texture.hh"
-
-
-namespace dc {
+namespace Mf {
/**
* objects and avoid having duplicate textures loaded to GL.
*/
-class texture::texture_impl : public mippleton<texture_impl>
+class Texture::TextureImpl : public Mippleton<TextureImpl>
{
/**
* smart enough to cache it if the client has plenty of RAM.
*/
- void contextRecreated(const notification& note)
+ void contextRecreated(const Notification& note)
{
unloadFromGL();
uploadToGL();
* Construction is initialization.
*/
- explicit texture_impl(const std::string& name) :
- mippleton<texture_impl>(name),
+ explicit TextureImpl(const std::string& name) :
+ Mippleton<TextureImpl>(name),
width_(0),
height_(0),
mode_(0),
uploadToGL();
// we want to know when the GL context is recreated
- dispatcher::instance().addHandler("video.context_recreated",
- boost::bind(&texture_impl::contextRecreated, this, _1), this);
+ Dispatcher::instance().addHandler("video.context_recreated",
+ boost::bind(&TextureImpl::contextRecreated, this, _1), this);
}
- ~texture_impl()
+ ~TextureImpl()
{
unloadFromGL();
- dispatcher::instance().removeHandler(this);
+ Dispatcher::instance().removeHandler(this);
}
{
SDL_Surface* surface;
- surface = IMG_Load(texture::getPathToResource(getName()).c_str());
+ surface = IMG_Load(Texture::getPathToResource(getName()).c_str());
if (!surface)
{
- throw texture::exception("loading failed");
+ throw Texture::Exception("loading failed");
}
SDL_Surface* temp = prepareImageForGL(surface);
if (!temp)
{
- throw texture::exception("image couldn't be prepared for GL");
+ throw Texture::Exception("image couldn't be prepared for GL");
}
if (temp->format->BytesPerPixel == 3)
else
{
SDL_FreeSurface(temp);
- throw texture::exception("image is not the required 24 or 32 bpp");
+ throw Texture::Exception("image is not the required 24 or 32 bpp");
}
width_ = temp->w;
};
-texture::texture(const std::string& name) :
+Texture::Texture(const std::string& name) :
// pass through
- impl(texture::texture_impl::retain(name), &texture::texture_impl::release)
+ impl_(Texture::TextureImpl::retain(name), &Texture::TextureImpl::release)
{}
* Bind the GL texture for mapping, etc.
*/
-void texture::bind()
+void Texture::bind()
{
glBindTexture(GL_TEXTURE_2D, getObject());
}
* Get the texture object, for the curious.
*/
-GLuint texture::getObject()
+GLuint Texture::getObject()
{
// pass through
- return impl->object_;
+ return impl_->object_;
}
-unsigned texture::getWidth()
+unsigned Texture::getWidth()
{
// pass through
- return impl->width_;
+ return impl_->width_;
}
-unsigned texture::getHeight()
+unsigned Texture::getHeight()
{
// pass through
- return impl->height_;
+ return impl_->height_;
}
-void texture::setMinFilter(GLuint filter)
+void Texture::setMinFilter(GLuint filter)
{
- impl->minFilter_ = filter;
+ impl_->minFilter_ = filter;
}
-void texture::setMaxFilter(GLuint filter)
+void Texture::setMaxFilter(GLuint filter)
{
- impl->maxFilter_ = filter;
+ impl_->maxFilter_ = filter;
}
-void texture::setWrapU(GLuint wrap)
+void Texture::setWrapU(GLuint wrap)
{
- impl->wrapU_ = wrap;
+ impl_->wrapU_ = wrap;
}
-void texture::setWrapV(GLuint wrap)
+void Texture::setWrapV(GLuint wrap)
{
- impl->wrapV_ = wrap;
+ impl_->wrapV_ = wrap;
}
-void texture::applyChanges()
+void Texture::applyChanges()
{
bind();
- impl->setProperties();
+ impl_->setProperties();
}
-std::string texture::getPathToResource(const std::string& name)
+std::string Texture::getPathToResource(const std::string& name)
{
// TODO since this is a generic library class, more than PNG should be
// supported
- return resource::getPathToResource("textures/" + name + ".png");
+ return Resource::getPathToResource("textures/" + name + ".png");
}
-} // namespace dc
+} // namespace Mf
/** vim: set ts=4 sw=4 tw=80: *************************************************/
*******************************************************************************/
-#ifndef _TEXTURE_HH_
-#define _TEXTURE_HH_
+#ifndef _MOOF_TEXTURE_HH_
+#define _MOOF_TEXTURE_HH_
/**
- * @file texture.hh
+ * @file Texture.hh
* Image-loading and OpenGL texture loading.
*/
#include <boost/shared_ptr.hpp>
-#include "opengl.hh"
-#include "resource.hh"
+#include <Moof/Resource.hh>
+#include <Moof/OpenGL.hh>
-namespace dc {
+namespace Mf {
-class texture : public resource
+class Texture : public Resource
{
public:
- texture(const std::string& name);
+ Texture(const std::string& name);
void bind();
GLuint getObject();
static std::string getPathToResource(const std::string& name);
- struct exception : std::runtime_error
+ struct Exception : std::runtime_error
{
- explicit exception(const std::string& what_arg) :
+ explicit Exception(const std::string& what_arg) :
std::runtime_error(what_arg) {}
};
private:
- class texture_impl;
- boost::shared_ptr<texture_impl> impl;
+ class TextureImpl;
+ boost::shared_ptr<TextureImpl> impl_;
};
-} // namespace dc
+} // namespace Mf
-#endif // _TEXTURE_HH_
+#endif // _MOOF_TEXTURE_HH_
/** vim: set ts=4 sw=4 tw=80: *************************************************/
--- /dev/null
+
+/*******************************************************************************
+
+ 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_THREAD_HH_
+#define _MOOF_THREAD_HH_
+
+/**
+ * @file Thread.hh
+ * Light C++ wrapper around SDL threads.
+ */
+
+#include <boost/function.hpp>
+
+#include <SDL/SDL.h>
+
+
+namespace Mf {
+
+//
+// The detach function detaches a separate thread by calling 'func' with
+// the 'arg' parameter.
+//
+
+typedef SDL_Thread* Thread;
+
+typedef boost::function<int(void)> Function;
+
+
+int detach_(void* arg)
+{
+ Function function = *(Function*)arg;
+ int ret = function();
+
+ delete (Function*)arg;
+ return ret;
+}
+
+Thread detachFunction(const Function& function)
+{
+ Thread thread;
+ Function* fcopy = new Function(function);
+
+ thread = SDL_CreateThread(detach_, (void*)fcopy);
+ if (thread == 0) delete fcopy;
+ return thread;
+}
+
+
+int waitOnThread(Thread thread)
+{
+ int i;
+ SDL_WaitThread(thread, &i);
+ return i;
+}
+
+void killThread(Thread thread)
+{
+ SDL_KillThread(thread);
+}
+
+
+//
+// The identifier function returns a unique integer for the calling thread.
+//
+
+unsigned int getThreadIdentifier()
+{
+ return SDL_ThreadID();
+}
+
+unsigned int getThreadIdentifier(Thread thread)
+{
+ return SDL_GetThreadID(thread);
+}
+
+
+// =============================================================================
+
+class Mutex
+{
+ friend class Condition;
+
+public:
+ Mutex()
+ {
+ mutex_ = SDL_CreateMutex();
+ }
+ ~Mutex()
+ {
+ SDL_DestroyMutex(mutex_);
+ }
+
+ bool acquireLock()
+ {
+ return (SDL_LockMutex(mutex_) == 0);
+ }
+ bool releaseLock()
+ {
+ return (SDL_UnlockMutex(mutex_) == 0);
+ }
+
+ class Lock
+ {
+ friend class Condition;
+
+ public:
+ Lock(Mutex& mutex)
+ {
+ mutex_ = &mutex;
+ isLocked_ = false;
+ }
+ ~Lock()
+ {
+ if (isLocked_) release();
+ }
+
+ bool acquire()
+ {
+ return (isLocked_ = mutex_->acquireLock());
+ }
+ bool release()
+ {
+ return mutex_->releaseLock();
+ isLocked_ = false;
+ }
+
+ bool isLocked() const
+ {
+ return isLocked_;
+ }
+
+ protected:
+ Mutex* mutex_;
+ bool isLocked_;
+ };
+
+ class ScopedLock : public Lock
+ {
+ public:
+ ScopedLock(Mutex& mutex) :
+ Lock(mutex)
+ {
+ acquire();
+ }
+ };
+
+private:
+ SDL_mutex* mutex_;
+};
+
+
+class Condition
+{
+public:
+ Condition()
+ {
+ condition_ = SDL_CreateCond();
+ }
+ ~Condition()
+ {
+ SDL_DestroyCond(condition_);
+ }
+
+ bool wait(Mutex::Lock& lock)
+ {
+ return (SDL_CondWait(condition_, lock.mutex_->mutex_) == 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);
+ }
+
+ bool notify()
+ {
+ return (SDL_CondSignal(condition_) == 0);
+ }
+ bool notifyAll()
+ {
+ return (SDL_CondBroadcast(condition_) == 0);
+ }
+
+private:
+ SDL_cond* condition_;
+};
+
+
+class Semaphore
+{
+public:
+ Semaphore(unsigned int value)
+ {
+ semaphore_ = SDL_CreateSemaphore(value);
+ }
+ ~Semaphore()
+ {
+ SDL_DestroySemaphore(semaphore_);
+ }
+
+ bool acquireLock()
+ {
+ return (SDL_SemWait(semaphore_) == 0);
+ }
+ bool releaseLock()
+ {
+ return (SDL_SemPost(semaphore_) == 0);
+ }
+
+ bool tryLock()
+ {
+ return (SDL_SemTryWait(semaphore_) == 0);
+ }
+ bool tryLock(unsigned ms)
+ {
+ // TODO for consistency, this function should take seconds
+ return (SDL_SemWaitTimeout(semaphore_, ms) == 0);
+ }
+
+ class Lock
+ {
+ public:
+ Lock(Semaphore& semaphore)
+ {
+ semaphore_ = &semaphore;
+ isLocked_ = false;
+ }
+ ~Lock()
+ {
+ if (isLocked_) release();
+ }
+
+ bool acquire()
+ {
+ return (isLocked_ = semaphore_->acquireLock());
+ }
+ bool release()
+ {
+ return semaphore_->releaseLock(); isLocked_ = false;
+ }
+
+ bool isLocked() const
+ {
+ return isLocked_;
+ }
+
+ protected:
+ Semaphore* semaphore_;
+ bool isLocked_;
+ };
+
+ class ScopedLock : public Lock
+ {
+ public:
+ ScopedLock(Semaphore& semaphore) :
+ Lock(semaphore)
+ {
+ acquire();
+ }
+ };
+
+private:
+ SDL_sem* semaphore_;
+};
+
+
+} // namespace Mf
+
+
+#endif // _MOOF_THREAD_HH_
+
+/** vim: set ts=4 sw=4 tw=80: *************************************************/
+
*******************************************************************************/
-#include "deserializer.hh"
-#include "mippleton.hh"
-#include "opengl.hh"
-#include "serializable.hh"
+#include "Deserializer.hh"
+#include "Mippleton.hh"
+#include "OpenGL.hh"
+#include "Serializable.hh"
+#include "Tilemap.hh"
-#include "tilemap.hh"
+namespace Mf {
-namespace dc {
-
-class tilemap::tilemap_impl : public mippleton<tilemap_impl>
+class Tilemap::TilemapImpl : public Mippleton<TilemapImpl>
{
public:
- tilemap_impl(const std::string& name) :
- mippleton<tilemap_impl>(name),
+ TilemapImpl(const std::string& name) :
+ Mippleton<TilemapImpl>(name),
tilesU_(1),
tilesV_(1),
minFilter_(GL_NEAREST),
void loadFromFile()
{
- deserializer in(tilemap::getPathToResource(getName()));
+ Deserializer deserializer(Tilemap::getPathToResource(getName()));
- serializable_ptr root = in.deserialize();
+ SerializablePtr root = deserializer.deserialize();
if (root)
{
- std::map<std::string,serializable_ptr> rootMap;
+ std::map<std::string,SerializablePtr> rootObj;
- if (root->get(rootMap))
+ if (root->get(rootObj))
{
- std::map<std::string,serializable_ptr>::iterator it;
+ std::map<std::string,SerializablePtr>::iterator it;
- if ((it = rootMap.find("TilesU")) != rootMap.end())
+ if ((it = rootObj.find("TilesU")) != rootObj.end())
{
long value;
if ((*it).second->get(value))
tilesU_ = unsigned(value);
}
}
- if ((it = rootMap.find("TilesV")) != rootMap.end())
+ if ((it = rootObj.find("TilesV")) != rootObj.end())
{
long value;
if ((*it).second->get(value))
tilesV_ = unsigned(value);
}
}
- if ((it = rootMap.find("MinFilter")) != rootMap.end())
+ if ((it = rootObj.find("MinFilter")) != rootObj.end())
{
std::string value;
if ((*it).second->get(value))
}
}
}
- if ((it = rootMap.find("MaxFilter")) != rootMap.end())
+ if ((it = rootObj.find("MaxFilter")) != rootObj.end())
{
std::string value;
if ((*it).second->get(value))
}
}
}
- if ((it = rootMap.find("WrapU")) != rootMap.end())
+ if ((it = rootObj.find("WrapU")) != rootObj.end())
{
std::string value;
if ((*it).second->get(value))
}
}
}
- if ((it = rootMap.find("WrapV")) != rootMap.end())
+ if ((it = rootObj.find("WrapV")) != rootObj.end())
{
std::string value;
if ((*it).second->get(value))
}
}
- unsigned tilesU_;
- unsigned tilesV_;
- GLuint minFilter_;
- GLuint maxFilter_;
- GLuint wrapU_;
- GLuint wrapV_;
+ unsigned tilesU_;
+ unsigned tilesV_;
+ GLuint minFilter_;
+ GLuint maxFilter_;
+ GLuint wrapU_;
+ GLuint wrapV_;
};
-tilemap::tilemap(const std::string& name) :
- texture(name),
- impl(tilemap::tilemap_impl::retain(name), &tilemap::tilemap_impl::release)
+Tilemap::Tilemap(const std::string& name) :
+ Texture(name),
+ impl_(Tilemap::TilemapImpl::retain(name), &Tilemap::TilemapImpl::release)
{
- setMinFilter(impl->minFilter_);
- setMaxFilter(impl->maxFilter_);
- setWrapU(impl->wrapU_);
- setWrapV(impl->wrapV_);
+ setMinFilter(impl_->minFilter_);
+ setMaxFilter(impl_->maxFilter_);
+ setWrapU(impl_->wrapU_);
+ setWrapV(impl_->wrapV_);
applyChanges();
}
-bool tilemap::getTileCoords(unsigned index, scalar coords[8])
+bool Tilemap::getTileCoords(unsigned index, Scalar coords[8])
{
// make sure the index represents a real tile
- if (index >= impl->tilesU_ * impl->tilesV_) return false;
+ if (index >= impl_->tilesU_ * impl_->tilesV_) return false;
- scalar w = 1.0 / scalar(impl->tilesU_);
- scalar h = 1.0 / scalar(impl->tilesV_);
+ Scalar w = 1.0 / Scalar(impl_->tilesU_);
+ Scalar h = 1.0 / Scalar(impl_->tilesV_);
- coords[0] = scalar(index % impl->tilesU_) * w;
- coords[1] = (scalar(impl->tilesV_ - 1) - scalar(index / impl->tilesU_)) * h;
+ coords[0] = Scalar(index % impl_->tilesU_) * w;
+ coords[1] = (Scalar(impl_->tilesV_ - 1) -
+ Scalar(index / impl_->tilesU_)) * h;
coords[2] = coords[0] + w;
coords[3] = coords[1];
coords[4] = coords[2];
return true;
}
-bool tilemap::getTileCoords(unsigned index, scalar coords[8], orientation what)
+bool Tilemap::getTileCoords(unsigned index, Scalar coords[8],
+ Orientation orientation)
{
if (getTileCoords(index, coords))
{
- if (what & flip)
+ if (orientation & FLIP)
{
// this looks kinda weird, but it's just swapping in a way that
// doesn't require an intermediate variable
coords[3] = coords[7];
coords[7] = coords[5];
}
- if (what & reverse)
+ if (orientation & REVERSE)
{
coords[0] = coords[2];
coords[2] = coords[6];
}
-std::string tilemap::getPathToResource(const std::string& name)
+std::string Tilemap::getPathToResource(const std::string& name)
{
- return resource::getPathToResource("tilemaps/" + name + ".json");
+ return Resource::getPathToResource("tilemaps/" + name + ".json");
}
-} // namespace dc
+} // namespace Mf
/** vim: set ts=4 sw=4 tw=80: *************************************************/
*******************************************************************************/
-#ifndef _TILEMAP_HH_
-#define _TILEMAP_HH_
+#ifndef _MOOF_TILEMAP_HH_
+#define _MOOF_TILEMAP_HH_
/**
- * @file tilemap.hh
+ * @file Tilemap.hh
* Small subclass to give some basic tile-mapping functionality to textures.
*/
#include <boost/shared_ptr.hpp>
-#include "texture.hh"
-#include "math.hh"
+#include <Moof/Math.hh>
+#include <Moof/Texture.hh>
-namespace dc {
+namespace Mf {
/**
* simplicity, this class assumes square tiles.
*/
-class tilemap : public texture
+class Tilemap : public Texture
{
public:
/**
* Possible orientations for texture coordinates.
*/
+ typedef unsigned Index;
+
typedef enum
{
- normal = 0, ///< Normal orientation.
- flip = 1, ///< Flip over a horizontal axis.
- reverse = 2, ///< Flip over a vertical axis.
- flip_and_reverse = 3 ///< Flip over both.
- } orientation;
+ NORMAL = 0, ///< Normal orientation.
+ FLIP = 1, ///< Flip over a horizontal axis.
+ REVERSE = 2, ///< Flip over a vertical axis.
+ FLIP_AND_REVERSE = 3 ///< Flip over both.
+ } Orientation;
- tilemap(const std::string& name);
+ Tilemap(const std::string& name);
/**
* Calculate texture coordinates for a tile at a certain index. Tiles are
* @return True if index is valid, false otherwise.
*/
- bool getTileCoords(unsigned index, scalar coords[8]);
+ bool getTileCoords(Index index, Scalar coords[8]);
/**
* @return True if index is valid, false otherwise.
*/
- bool getTileCoords(unsigned index, scalar coords[8], orientation what);
+ bool getTileCoords(Index index, Scalar coords[8], Orientation what);
static std::string getPathToResource(const std::string& name);
private:
- class tilemap_impl;
- boost::shared_ptr<tilemap_impl> impl;
+ class TilemapImpl;
+ boost::shared_ptr<TilemapImpl> impl_;
};
-} // namespace dc
+} // namespace Mf
-#endif // _TILEMAP_HH_
+#endif // _MOOF_TILEMAP_HH_
/** vim: set ts=4 sw=4 tw=80: *************************************************/
*******************************************************************************/
-#include <stdexcept>
-#include <ctime>
#include <cerrno>
+#include <ctime>
+#include <stdexcept>
+
+#include "Timer.hh"
#if HAVE_CONFIG_H
#include "config.h"
#endif
-#include "timer.hh"
-
-namespace dc {
+namespace Mf {
#if HAVE_CLOCK_GETTIME
// program starts). Of course this isn't much of an issue if scalar is a
// double-precision number.
-static time_t setReference()
+static time_t setReference_()
{
struct timespec ts;
return ts.tv_sec;
}
-static const time_t reference = setReference();
+static const time_t reference = setReference_();
-scalar ticks()
+Scalar getTicks()
{
struct timespec ts;
throw std::runtime_error("cannot access monotonic clock");
}
- return scalar(ts.tv_sec - reference) + scalar(ts.tv_nsec) / 1000000000.0;
+ return Scalar(ts.tv_sec - reference) + Scalar(ts.tv_nsec) / 1000000000.0;
}
#include <SDL/SDL.h>
-scalar ticks()
+Scalar getTicks()
{
Uint32 ms = SDL_GetTicks();
- return scalar(ms / 1000) + scalar(ms % 1000) / 1000.0;
+ return Scalar(ms / 1000) + Scalar(ms % 1000) / 1000.0;
}
#endif // HAVE_CLOCK_GETTIME
-void sleep(scalar seconds, bool absolute)
+void sleep(Scalar seconds, bool absolute)
{
struct timespec ts;
int ret;
- if (absolute) seconds -= ticks();
+ if (absolute) seconds -= getTicks();
ts.tv_sec = time_t(seconds);
- ts.tv_nsec = long((seconds - scalar(ts.tv_sec)) * 1000000000.0);
+ ts.tv_nsec = long((seconds - Scalar(ts.tv_sec)) * 1000000000.0);
do
{
}
-} // namespace dc
+} // namespace Mf
/** vim: set ts=4 sw=4 tw=80: *************************************************/
*******************************************************************************/
-#ifndef _TIMER_HH_
-#define _TIMER_HH_
+#ifndef _MOOF_TIMER_HH_
+#define _MOOF_TIMER_HH_
/**
- * @file timer.hh
+ * @file Timer.hh
* Functions for measuring time in a friendly unit.
*/
-#include "math.hh"
+#include <Moof/Math.hh>
-namespace dc {
+namespace Mf {
/**
* @return Seconds.
*/
-scalar ticks();
+Scalar getTicks();
/**
* sleep for the requested amount of time.
*/
-void sleep(scalar seconds, bool absolute = false);
+void sleep(Scalar seconds, bool absolute = false);
-} // namespace dc
+} // namespace Mf
-#endif // _TIMER_HH_
+#endif // _MOOF_TIMER_HH_
/** vim: set ts=4 sw=4 tw=80: *************************************************/
#include <stdexcept>
-#include "serializable.hh"
-#include "settings.hh"
-#include "dispatcher.hh"
+#include "Dispatcher.hh"
+#include "Serializable.hh"
+#include "Settings.hh"
+#include "Video.hh"
-#include "video.hh"
+namespace Mf {
-namespace dc {
-
-video::video()
+Video::Video()
{
std::string caption;
- if (settings::instance().get("video.caption", caption))
+ if (Settings::instance().get("video.caption", caption))
{
init(attribs_, caption);
}
}
}
-video::video(const attributes& attribs, const std::string& caption)
+Video::Video(const Attributes& attribs, const std::string& caption)
{
init(attribs, caption);
}
-video::video(const attributes& attribs)
+Video::Video(const Attributes& attribs)
{
std::string caption;
- if (settings::instance().get("video.caption", caption))
+ if (Settings::instance().get("video.caption", caption))
{
init(attribs, caption);
}
}
}
-video::video(const std::string& caption)
+Video::Video(const std::string& caption)
{
init(attribs_, caption);
}
-void video::init(const attributes& attribs, const std::string& caption)
+void Video::init(const Attributes& attribs, const std::string& caption)
{
context_ = 0;
flags_ = 0;
setVideoMode(attribs.mode);
}
-void video::recreateContext()
+void Video::recreateContext()
{
SDL_FreeSurface(context_);
context_ = 0;
setVideoMode(attribs_.mode);
- dc::dispatcher::instance().dispatch("video.context_recreated");
+ Mf::Dispatcher::instance().dispatch("video.context_recreated");
}
-void video::setOpenGLAttributes()
+void Video::setOpenGLAttributes()
{
SDL_GL_SetAttribute(SDL_GL_RED_SIZE, attribs_.colorBuffer[0]);
SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, attribs_.colorBuffer[1]);
}
-video::~video()
+Video::~Video()
{
SDL_FreeSurface(context_);
}
-void video::setVideoMode(const long mode[3])
+void Video::setVideoMode(const long mode[3])
{
if (mode != attribs_.mode || !context_)
{
attribs_.mode[1] = mode[1];
attribs_.mode[2] = mode[2];
}
- else throw std::runtime_error(SDL_GetError());
+ else throw Exception(SDL_GetError());
}
}
-video::attributes video::getAttributes() const
+Video::Attributes Video::getAttributes() const
{
return attribs_;
}
-void video::resize(int width, int height)
+void Video::resize(int width, int height)
{
long mode[] = {width, height, attribs_.mode[2]};
setVideoMode(mode);
}
-bool video::iconify()
+bool Video::iconify()
{
return SDL_WM_IconifyWindow();
}
-void video::setCaption(const std::string& caption)
+void Video::setCaption(const std::string& caption)
{
SDL_WM_SetCaption(caption.c_str(), 0);
}
-std::string video::getCaption() const
+std::string Video::getCaption() const
{
char* str;
SDL_WM_GetCaption(&str, 0);
}
-void video::setFull(bool full)
+void Video::setFull(bool full)
{
if (full != isFull() || !context_)
{
}
}
-void video::toggleFull()
+void Video::toggleFull()
{
setFull(!isFull());
}
-bool video::isFull() const
+bool Video::isFull() const
{
return flags_ & SDL_FULLSCREEN;
}
-void video::setCursorVisible(bool hasCursor)
+void Video::setCursorVisible(bool hasCursor)
{
SDL_ShowCursor(hasCursor? SDL_ENABLE : SDL_DISABLE);
}
-void video::toggleCursorVisible()
+void Video::toggleCursorVisible()
{
setCursorVisible(!isCursorVisible());
}
-bool video::isCursorVisible() const
+bool Video::isCursorVisible() const
{
return (SDL_ShowCursor(SDL_QUERY) == SDL_ENABLE);
}
-void video::setResizable(bool resizable)
+void Video::setResizable(bool resizable)
{
if (resizable != isResizable() || !context_)
{
}
}
-void video::toggleResizable()
+void Video::toggleResizable()
{
setResizable(!isResizable());
}
-bool video::isResizable() const
+bool Video::isResizable() const
{
return flags_ & SDL_RESIZABLE;
}
-bool video::isCursorGrab() const
+bool Video::isCursorGrab() const
{
return (SDL_WM_GrabInput(SDL_GRAB_QUERY) == SDL_GRAB_ON);
}
-void video::toggleCursorGrab()
+void Video::toggleCursorGrab()
{
setCursorGrab(!isCursorGrab());
}
-void video::setCursorGrab(bool cursorGrab)
+void Video::setCursorGrab(bool cursorGrab)
{
SDL_WM_GrabInput(cursorGrab? SDL_GRAB_ON : SDL_GRAB_OFF);
}
-void video::makeActive()
+void Video::makeActive()
{
// NOP until the day SDL supports more than only one window.
// Still waiting...
}
-void video::swap()
+void Video::swap()
{
SDL_GL_SwapBuffers();
}
-video::attributes::attributes()
+Video::Attributes::Attributes()
{
// Set some sane GL and window defaults (see SDL_video.c:217)
colorBuffer[0] = 3;
cursorVisible = true;
cursorGrab = false;
- std::vector<serializable_ptr> colors;
- settings::instance().get("video.colorbuffers", colors);
+ std::vector<SerializablePtr> colors;
+ Settings::instance().get("video.colorbuffers", colors);
if (colors.size() > 0) colors[0]->get(colorBuffer[0]);
if (colors.size() > 1) colors[1]->get(colorBuffer[1]);
if (colors.size() > 2) colors[2]->get(colorBuffer[2]);
if (colors.size() > 3) colors[3]->get(colorBuffer[3]);
- settings::instance().get("video.framebuffer", frameBuffer);
- settings::instance().get("video.doublebuffer", doubleBuffer);
- settings::instance().get("video.depthbuffer", depthBuffer);
- settings::instance().get("video.stencilbuffer", stencilBuffer);
+ Settings::instance().get("video.framebuffer", frameBuffer);
+ Settings::instance().get("video.doublebuffer", doubleBuffer);
+ Settings::instance().get("video.depthbuffer", depthBuffer);
+ Settings::instance().get("video.stencilbuffer", stencilBuffer);
- std::vector<serializable_ptr> accum;
- settings::instance().get("video.accumbuffers", accum);
+ std::vector<SerializablePtr> accum;
+ Settings::instance().get("video.accumbuffers", accum);
if (accum.size() > 0) accum[0]->get(accumBuffer[0]);
if (accum.size() > 1) accum[1]->get(accumBuffer[1]);
if (accum.size() > 2) accum[2]->get(accumBuffer[2]);
if (accum.size() > 3) accum[3]->get(accumBuffer[3]);
- settings::instance().get("video.stereo", stereo);
- settings::instance().get("video.multiesamplebuffers", multisampleBuffers);
- settings::instance().get("video.multiesamplesamples", multisampleSamples);
- settings::instance().get("video.swapcontrol", swapControl);
- settings::instance().get("video.hardwareonly", hardwareonly);
+ Settings::instance().get("video.stereo", stereo);
+ Settings::instance().get("video.multiesamplebuffers", multisampleBuffers);
+ Settings::instance().get("video.multiesamplesamples", multisampleSamples);
+ Settings::instance().get("video.swapcontrol", swapControl);
+ Settings::instance().get("video.hardwareonly", hardwareonly);
- std::vector<serializable_ptr> dimensions;
- settings::instance().get("video.mode", dimensions);
+ std::vector<SerializablePtr> dimensions;
+ Settings::instance().get("video.mode", dimensions);
if (dimensions.size() > 0) dimensions[0]->get(mode[0]);
if (dimensions.size() > 1) dimensions[1]->get(mode[1]);
if (dimensions.size() > 2) dimensions[2]->get(mode[2]);
- settings::instance().get("video.fullscreen", fullscreen);
- settings::instance().get("video.resizable", resizable);
- settings::instance().get("video.showcursor", cursorVisible);
- settings::instance().get("input.grab", cursorGrab);
+ Settings::instance().get("video.fullscreen", fullscreen);
+ Settings::instance().get("video.resizable", resizable);
+ Settings::instance().get("video.showcursor", cursorVisible);
+ Settings::instance().get("input.grab", cursorGrab);
}
-} // namespace dc
+} // namespace Mf
/** vim: set ts=4 sw=4 tw=80: *************************************************/
*******************************************************************************/
-#ifndef _VIDEO_HH_
-#define _VIDEO_HH_
+#ifndef _MOOF_VIDEO_HH_
+#define _MOOF_VIDEO_HH_
#include <string>
#include <SDL/SDL.h>
-namespace dc {
+namespace Mf {
-class video
+class Video
{
public:
- struct attributes
+ struct Attributes
{
// OpenGL attributes
long colorBuffer[4]; // rgba
bool cursorVisible;
bool cursorGrab;
- attributes();
+ Attributes();
};
- video();
- video(const attributes& attribs);
- video(const attributes& attribs, const std::string& caption);
- video(const std::string& caption);
- ~video();
+ Video();
+ Video(const Attributes& attribs);
+ Video(const Attributes& attribs, const std::string& caption);
+ Video(const std::string& caption);
+ ~Video();
void setVideoMode(const long mode[3]);
- attributes getAttributes() const;
+ Attributes getAttributes() const;
void resize(int width, int height);
bool iconify();
void makeActive();
void swap();
+
+ struct Exception : public std::runtime_error
+ {
+ explicit Exception(const std::string& what_arg) :
+ std::runtime_error(what_arg) {}
+ };
+
private:
- void init(const attributes& attribs, const std::string& caption);
+ void init(const Attributes& attribs, const std::string& caption);
void recreateContext();
void setOpenGLAttributes();
SDL_Surface* context_;
unsigned flags_;
- attributes attribs_;
+ Attributes attribs_;
};
-typedef boost::shared_ptr<video> video_ptr;
+typedef boost::shared_ptr<Video> VideoPtr;
-} // namespace dc
+} // namespace Mf
-#endif // _VIDEO_HH_
+#endif // _MOOF_VIDEO_HH_
/** vim: set ts=4 sw=4 tw=80: *************************************************/
*******************************************************************************/
-#include "TilemapFont.hh"
#include <iostream>
+#include "TilemapFont.hh"
+
TilemapFont::TilemapFont() :
- dc::tilemap("Font")
-{}
+ Mf::Tilemap("Font") {}
-void TilemapFont::getTileCoords(char symbol, dc::scalar coords[8],
- dc::tilemap::orientation what)
+void TilemapFont::getTileCoords(char symbol, Mf::Scalar coords[8],
+ Mf::Tilemap::Orientation what)
{
- unsigned index = 0;
+ Mf::Tilemap::Index index = 0;
if (symbol >= ' ' && symbol <= '_')
{
index = 0;
}
- dc::tilemap::getTileCoords(index, coords, what);
+ Mf::Tilemap::getTileCoords(index, coords, what);
}
* Text on the screen.
*/
-#include "tilemap.hh"
+#include <Moof/Tilemap.hh>
-class TilemapFont : public dc::tilemap
+class TilemapFont : public Mf::Tilemap
{
public:
- struct exception : public std::runtime_error
+ struct Exception : public std::runtime_error
{
- explicit exception(const std::string& what_arg) :
+ explicit Exception(const std::string& what_arg) :
std::runtime_error(what_arg) {}
};
TilemapFont();
- void getTileCoords(char symbol, dc::scalar coords[8],
- dc::tilemap::orientation what = dc::tilemap::normal);
+ void getTileCoords(char symbol, Mf::Scalar coords[8],
+ Mf::Tilemap::Orientation what = Mf::Tilemap::NORMAL);
};
*******************************************************************************/
#include <algorithm>
-#include <cstdio>
#include <cstdarg>
+#include <cstdio>
#include "Typesetter.hh"
#include <string>
-#include "math.hh"
+#include <Moof/Math.hh>
class Typesetter
public:
Typesetter();
- void setLineSpacing(dc::scalar spacing);
+ void setLineSpacing(Mf::Scalar spacing);
void print(const std::string& format, ...);
private:
- dc::scalar leftBound;
- dc::scalar topBound;
- dc::scalar lineSpacing;
+ Mf::Scalar leftBound;
+ Mf::Scalar topBound;
+ Mf::Scalar lineSpacing;
};
*******************************************************************************/
+#include <cstdlib> // getenv
#include <iostream>
#include <string>
-#include <cstdlib> // getenv
-
#include <boost/bind.hpp>
-#include "math.hh"
-#include "opengl.hh"
-#include "settings.hh"
-#include "timer.hh"
-#include "video.hh"
+#include <Moof/Math.hh>
+#include <Moof/OpenGL.hh>
+#include <Moof/Settings.hh>
+#include <Moof/Timer.hh>
+#include <Moof/Video.hh>
#include "YoinkApp.hh"
YoinkApp::YoinkApp(int argc, char* argv[]) :
- dc::engine(PACKAGE_STRING, argc, argv, configFiles())
+ Mf::Engine(PACKAGE_STRING, argc, argv, configFiles())
{
std::cout << PACKAGE_STRING << std::endl
<< "Compiled " << __TIME__ " " __DATE__ << std::endl
if (dataDir)
{
- dc::resource::addSearchPath(dataDir);
+ Mf::Resource::addSearchPath(dataDir);
}
- dc::resource::addSearchPath(YOINK_DATADIR);
+ Mf::Resource::addSearchPath(YOINK_DATADIR);
- dc::dispatcher::instance().addHandler("video.context_recreated",
+ Mf::Dispatcher::instance().addHandler("video.context_recreated",
boost::bind(&YoinkApp::contextRecreated, this, _1), this);
setupGL();
font = new TilemapFont;
- dc::vector2 coeffs[4];
- coeffs[0] = dc::vector2(0.0, 0.0);
- coeffs[1] = dc::vector2(0.5, 0.0);
- coeffs[2] = dc::vector2(0.5, 0.0);
- coeffs[3] = dc::vector2(1.0, 0.0);
- interp.init(coeffs, 1.0, dc::interpolator::oscillate);
+ Mf::Vector2 coeffs[4];
+ coeffs[0] = Mf::Vector2(0.0, 0.0);
+ coeffs[1] = Mf::Vector2(0.5, 0.0);
+ coeffs[2] = Mf::Vector2(0.5, 0.0);
+ coeffs[3] = Mf::Vector2(1.0, 0.0);
+ interp.init(coeffs, 1.0, Mf::Interpolator::OSCILLATE);
- dc::scalar coeff[2] = {1.0, 0.0};
+ Mf::Scalar coeff[2] = {1.0, 0.0};
fadeIn.init(coeff, 0.5f);
- testScene = new dc::scene("Test");
+ testScene = new Mf::Scene("Test");
}
YoinkApp::~YoinkApp()
delete someChar;
delete font;
- dc::dispatcher::instance().removeHandler(this);
+ Mf::Dispatcher::instance().removeHandler(this);
std::cout << "Goodbye..." << std::endl;
}
//glLineWidth(10.0f);
}
-void YoinkApp::contextRecreated(const dc::notification& note)
+void YoinkApp::contextRecreated(const Mf::Notification& note)
{
// Whenever the context and a new one created, it probably won't contain our
// state so we need to set that up again.
}
-void YoinkApp::update(dc::scalar t, dc::scalar dt)
+void YoinkApp::update(Mf::Scalar t, Mf::Scalar dt)
{
//dt *= 0.2;
}
-void YoinkApp::draw(dc::scalar alpha)
+void YoinkApp::draw(Mf::Scalar alpha)
{
- //dc::vector4 meh;
+ //Mf::vector4 meh;
//meh.random(0.0, 1.0);
- //static dc::vector4 c1(meh);
+ //static Mf::vector4 c1(meh);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
- //dc::scalar drawstate = cml::lerp(prevstate, state, alpha);
- //dc::scalar sinstate = std::sin(drawstate);
- //dc::scalar cosstate = std::cos(drawstate);
+ //Mf::Scalar drawstate = cml::lerp(prevstate, state, alpha);
+ //Mf::Scalar sinstate = std::sin(drawstate);
+ //Mf::Scalar cosstate = std::cos(drawstate);
glMatrixMode(GL_PROJECTION);
someChar->getTilemap().getTileCoords(heroFrame, coords,
- dc::tilemap::reverse);
+ Mf::tilemap::reverse);
glBegin(GL_QUADS);
glTexCoord2f(coords[0], coords[1]);
glEnable(GL_DEPTH_TEST);*/
}
-void YoinkApp::handleEvent(const dc::event& e)
+void YoinkApp::handleEvent(const Mf::Event& event)
{
- switch (e.type)
+ switch (event.type)
{
case SDL_KEYDOWN:
- if (e.key.keysym.sym == SDLK_ESCAPE)
+ if (event.key.keysym.sym == SDLK_ESCAPE)
{
stop();
}
- else if (e.key.keysym.sym == SDLK_f)
+ else if (event.key.keysym.sym == SDLK_f)
{
getVideo().toggleFull();
}
- else if (e.key.keysym.sym == SDLK_a)
+ else if (event.key.keysym.sym == SDLK_a)
{
someChar->getAnimation().startSequence("Punch");
}
- else if (e.key.keysym.sym == SDLK_RIGHT)
+ else if (event.key.keysym.sym == SDLK_RIGHT)
{
x -= 50.0;
}
- else if (e.key.keysym.sym == SDLK_LEFT)
+ else if (event.key.keysym.sym == SDLK_LEFT)
{
x += 50.0;
}
- else if (e.key.keysym.sym == SDLK_UP)
+ else if (event.key.keysym.sym == SDLK_UP)
{
y -= 50.0;
}
- else if (e.key.keysym.sym == SDLK_DOWN)
+ else if (event.key.keysym.sym == SDLK_DOWN)
{
y += 50.0;
}
- else if (e.key.keysym.sym == SDLK_PAGEUP)
+ else if (event.key.keysym.sym == SDLK_PAGEUP)
{
z += 50.0;
}
- else if (e.key.keysym.sym == SDLK_PAGEDOWN)
+ else if (event.key.keysym.sym == SDLK_PAGEDOWN)
{
z -= 50.0;
}
break;
case SDL_VIDEORESIZE:
- glViewport(0, 0, e.resize.w, e.resize.h);
+ glViewport(0, 0, event.resize.w, event.resize.h);
break;
}
}
#include <iostream>
#include <string>
-#include "dispatcher.hh"
-#include "math.hh"
-#include "interpolator.hh"
-#include "engine.hh"
+#include <Moof/Dispatcher.hh>
+#include <Moof/Engine.hh>
+#include <Moof/Interpolator.hh>
+#include <Moof/Math.hh>
+#include <Moof/Scene.hh>
#include "Character.hh"
-
#include "TilemapFont.hh"
-#include "scene.hh"
-
-class YoinkApp : public dc::engine
+class YoinkApp : public Mf::Engine
{
public:
YoinkApp(int argc, char* argv[]);
~YoinkApp();
private:
- void update(dc::scalar t, dc::scalar dt);
- void draw(dc::scalar alpha);
- void handleEvent(const dc::event& e);
+ void update(Mf::Scalar t, Mf::Scalar dt);
+ void draw(Mf::Scalar alpha);
+ void handleEvent(const Mf::Event& event);
/**
* Set OpenGL to a state we can know and depend on.
*/
void setupGL();
- void contextRecreated(const dc::notification& note);
+ void contextRecreated(const Mf::Notification& note);
- //dc::animation* heroAnimation;
- //dc::tilemap* heroineTexture;
Character* someChar;
- //dc::binomial_interpolator<dc::vector2,2> interp;
- dc::cerpv2 interp;
- dc::lerps fadeIn;
+ TilemapFont *font;
- dc::scene* testScene;
+ Mf::Cerpv2 interp;
+ Mf::Lerps fadeIn;
- TilemapFont *font;
+ Mf::Scene* testScene;
- dc::scalar x, y, z;
+ Mf::Scalar x, y, z;
- dc::scalar state;
- dc::scalar prevstate;
+ Mf::Scalar state;
+ Mf::Scalar prevstate;
};
+++ /dev/null
-
-/*******************************************************************************
-
- Copyright (c) 2009, Charles McGarvey
- All rights reserved.
-
- Redistribution and use in source and binary forms, with or without
- modification, are permitted provided that the following conditions are met:
-
- * Redistributions of source code must retain the above copyright notice,
- this list of conditions and the following disclaimer.
- * Redistributions in binary form must reproduce the above copyright notice,
- this list of conditions and the following disclaimer in the documentation
- and/or other materials provided with the distribution.
-
- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
- AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
- FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
- DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
- SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
- CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
- OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-*******************************************************************************/
-
-#include <map>
-
-#include "dispatcher.hh"
-
-
-namespace dc {
-
-
-notification::~notification() {}
-
-
-class dispatcher::dispatcher_impl
-{
-public:
- dispatcher_impl() : id(1) {}
-
- dispatcher::handler getNewHandlerID()
- {
- id += 4;
- return (dispatcher::handler)id;
- }
-
- typedef std::pair<dispatcher::handler,dispatcher::function> callback_t;
- typedef std::multimap<std::string,callback_t> callback_lookup_t;
- typedef callback_lookup_t::iterator callback_it_t;
-
- typedef std::multimap<dispatcher::handler,std::string> handler_lookup_t;
- typedef handler_lookup_t::iterator handler_it_t;
-
- unsigned long long id;
-
- callback_lookup_t callbacks;
- handler_lookup_t handlers;
-};
-
-
-dispatcher::dispatcher() : impl(new dispatcher::dispatcher_impl) {}
-
-
-// TODO these methods are ugly
-
-dispatcher::handler dispatcher::addHandler(const std::string& message,
- const function& callback)
-{
- return addHandler(message, callback, impl->getNewHandlerID());
-}
-
-dispatcher::handler dispatcher::addHandler(const std::string& message,
- const function& callback, handler id)
-{
- std::pair<std::string,dispatcher::dispatcher_impl::callback_t>
- callbackPair(message, dispatcher::dispatcher_impl::callback_t(id, callback));
-
- std::pair<handler,std::string> handlerPair(id, message);
-
- impl->callbacks.insert(callbackPair);
- impl->handlers.insert(handlerPair);
-
- return id;
-}
-
-
-void dispatcher::removeHandler(handler id)
-{
- std::pair<dispatcher::dispatcher_impl::handler_it_t,dispatcher::dispatcher_impl::handler_it_t>
- handlers(impl->handlers.equal_range(id));
-
- dispatcher::dispatcher_impl::handler_it_t i;
- for (i = handlers.first; i != handlers.second; i++)
- {
- dispatcher::dispatcher_impl::callback_it_t it = impl->callbacks.find((*i).second);
- dispatcher::dispatcher_impl::callback_it_t last = impl->callbacks.end();
-
- dispatcher::dispatcher_impl::callback_it_t j;
- for (j = it; j != last; j++)
- {
- if (((*j).second).first == id)
- {
- impl->callbacks.erase(j);
- break;
- }
- }
- }
-
- impl->handlers.erase(id);
-}
-
-
-void dispatcher::dispatch(const std::string& message)
-{
- dispatch(message, notification());
-}
-
-void dispatcher::dispatch(const std::string& message, const notification& param)
-{
- std::pair<dispatcher::dispatcher_impl::callback_it_t,dispatcher::dispatcher_impl::callback_it_t>
- callbacks(impl->callbacks.equal_range(message));
-
- dispatcher::dispatcher_impl::callback_it_t i;
- for (i = callbacks.first; i != callbacks.second; i++)
- {
- function callback = ((*i).second).second;
- callback(param);
- }
-}
-
-
-} // namespace dc
-
-/** vim: set ts=4 sw=4 tw=80: *************************************************/
-
+++ /dev/null
-
-/*******************************************************************************
-
- 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 _INTERPOLATOR_HH_
-#define _INTERPOLATOR_HH_
-
-
-namespace dc {
-
-
-class interpolator
-{
- void clamp(scalar& value)
- {
- if (value > 1.0)
- {
- switch (theMode)
- {
- case stop:
- value = 1.0;
- stopped = true;
- break;
- case repeat:
- value -= 1.0;
- break;
- case oscillate:
- value = 2.0 - value;
- scale *= -1.0;
- break;
- }
- }
- else if (value < 0.0)
- {
- switch (theMode)
- {
- case stop:
- value = 0.0;
- stopped = true;
- break;
- case repeat:
- value += 1.0;
- break;
- case oscillate:
- value = -value;
- scale *= -1.0;
- break;
- }
- }
- }
-
-public:
- typedef enum
- {
- stop = 0,
- repeat = 1,
- oscillate = 2
- } mode;
-
- void init(scalar seconds = 1.0, mode onFinish = stop)
- {
- scale = 1.0 / seconds;
- alpha = 0.0;
- setMode(onFinish);
- }
-
-
- void setMode(mode onFinish)
- {
- theMode = onFinish;
- stopped = false;
- }
-
-
- void update(scalar dt)
- {
- if (!stopped)
- {
- alpha += dt * scale;
- clamp(alpha);
- calculate(alpha);
- }
- }
-
- virtual void calculate(scalar alpha) = 0;
-
-private:
- mode theMode;
- scalar alpha;
- scalar scale;
- bool stopped;
-};
-
-template <class T>
-class interpolator_base : public interpolator
-{
-public:
- void init(scalar seconds = 1.0, mode onFinish = stop)
- {
- interpolator::init(seconds, onFinish);
-
- calculate(0.0); // set value
- calculate(0.0); // set previous
- }
-
- void calculate(scalar alpha)
- {
- previous = value;
- calculate(value, alpha);
- }
-
- virtual void calculate(T& value, scalar alpha) = 0;
-
- const T& getValue()
- {
- return value;
- }
-
- const T getState(scalar alpha)
- {
- return cml::lerp(previous, value, alpha);
- }
-
-private:
- T value;
- T previous;
-};
-
-
-template <class T, int D>
-class binomial_interpolator : public interpolator_base<T>
-{
-public:
- binomial_interpolator() {}
-
- explicit binomial_interpolator(const T coeff[D+1], scalar seconds = 1.0,
- interpolator::mode onFinish = interpolator::stop)
- {
- init(coeff, seconds, onFinish);
- }
-
- void init(const T coeff[D+1], scalar seconds = 1.0,
- interpolator::mode onFinish = interpolator::stop)
- {
- scalar fac[D+1];
-
- fac[0] = 1.0;
- fac[1] = 1.0;
-
- // build an array of the computed factorials we will need
- for (int i = 2; i <= D; i++)
- {
- fac[i] = i * fac[i - 1];
- }
-
- // combine the coefficients for fast updating
- for (int i = 0; i <= D; i++)
- {
- // n! / (k! * (n - k)!)
- coefficient[i] = coeff[i] * fac[D] / (fac[i] * fac[D - i]);
- }
-
- interpolator_base<T>::init(seconds, onFinish);
- }
-
-
- void calculate(T& value, scalar alpha)
- {
- scalar beta = 1.0 - alpha;
-
- value = coefficient[0] * std::pow(beta, D);
-
- for (int i = 1; i <= D; i++)
- {
- value += coefficient[i] * std::pow(beta, D - i) * std::pow(alpha, i);
- }
- }
-
-private:
-
- T coefficient[D+1];
-};
-
-
-template <class T>
-class binomial_interpolator<T,1> : public interpolator_base<T>
-{
-public:
- binomial_interpolator() {}
-
- explicit binomial_interpolator(const T coeff[2], scalar seconds = 1.0,
- interpolator::mode onFinish = interpolator::stop)
- //interpolator_base<T>(seconds, onFinish)
- {
- init(coeff, seconds, onFinish);
- }
-
- void init(const T coeff[2], scalar seconds = 1.0,
- interpolator::mode onFinish = interpolator::stop)
- {
- coefficient[0] = coeff[0];
- coefficient[1] = coeff[1];
-
- interpolator_base<T>::init(seconds, onFinish);
- }
-
-
- void calculate(T& value, scalar alpha)
- {
- value = cml::lerp(coefficient[0], coefficient[1], alpha);
- }
-
-private:
- T coefficient[2];
-};
-
-
-// Here are some aliases for more common interpolators. Also see the
-// interpolation functions in cml for other types of interpolation such as
-// slerp and some multi-alpha interpolators.
-
-typedef binomial_interpolator<scalar, 1> lerps; // linear
-typedef binomial_interpolator<vector2,1> lerpv2;
-typedef binomial_interpolator<vector3,1> lerpv3;
-typedef binomial_interpolator<vector4,1> lerpv4;
-
-typedef binomial_interpolator<scalar ,2> qerps; // quadratic
-typedef binomial_interpolator<vector2,2> qerpv2;
-typedef binomial_interpolator<vector3,2> qerpv3;
-typedef binomial_interpolator<vector4,2> qerpv4;
-
-typedef binomial_interpolator<scalar ,3> cerps; // cubic
-typedef binomial_interpolator<vector2,3> cerpv2;
-typedef binomial_interpolator<vector3,3> cerpv3;
-typedef binomial_interpolator<vector4,3> cerpv4;
-
-
-} // namespace dc
-
-#endif // _INTERPOLATOR_HH_
-
-/** vim: set ts=4 sw=4 tw=80: *************************************************/
-
+++ /dev/null
-
-/*******************************************************************************
-
- 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 _THREAD_HH_
-#define _THREAD_HH_
-
-/**
- * @file thread.hh
- * Light C++ wrapper around SDL threads.
- */
-
-#include <boost/function.hpp>
-#include <SDL/SDL.h>
-
-
-namespace dc {
-namespace thread {
-
-//
-// The detach function detaches a separate thread by calling 'func' with
-// the 'arg' parameter.
-//
-
-typedef SDL_Thread* thread;
-
-typedef boost::function<int(void)> function;
-
-
-int detach_(void* arg)
-{
- function func = *(function*)arg;
- int ret = func();
-
- delete (function*)arg;
- return ret;
-}
-
-thread detach(const function& func)
-{
- thread t;
- function* fcopy = new function(func);
-
- t = SDL_CreateThread(detach_, (void*)fcopy);
- if (t == 0) delete fcopy;
- return t;
-}
-
-
-int wait(thread t)
-{
- int i;
- SDL_WaitThread(t, &i);
- return i;
-}
-
-void kill(thread t)
-{
- SDL_KillThread(t);
-}
-
-
-//
-// The identifier function returns a unique integer for the calling thread.
-//
-
-unsigned int identifier()
-{
- return SDL_ThreadID();
-}
-
-unsigned int identifier(thread t)
-{
- return SDL_GetThreadID(t);
-}
-
-
-// =============================================================================
-
-class mutex
-{
- friend class condition;
-
-public:
- mutex() { mutex_ = SDL_CreateMutex(); }
- ~mutex() { SDL_DestroyMutex(mutex_); }
-
- bool acquireLock() { return (SDL_LockMutex(mutex_) == 0); }
- bool releaseLock() { return (SDL_UnlockMutex(mutex_) == 0); }
-
- class lock
- {
- friend class condition;
-
- public:
- lock(mutex& m) { mutex_ = &m; isLocked_ = false; }
- ~lock() { if (isLocked_) release(); }
-
- bool acquire() { return (isLocked_ = mutex_->acquireLock()); }
- bool release() { return mutex_->releaseLock(); isLocked_ = false; }
- bool isLocked() const { return isLocked_; }
-
- protected:
- mutex* mutex_;
- bool isLocked_;
- };
-
- class scoped_lock : public lock
- {
- public:
- scoped_lock(mutex& m) : lock(m) { acquire(); }
- };
-
-private:
- SDL_mutex* mutex_;
-};
-
-// =============================================================================
-
-class condition
-{
-public:
- condition() { condition_ = SDL_CreateCond(); }
- ~condition() { SDL_DestroyCond(condition_); }
-
- bool wait(mutex::lock& l)
- {
- return (SDL_CondWait(condition_, l.mutex_->mutex_) == 0);
- }
- bool wait(mutex::lock& l, unsigned ms)
- {
- // TODO: For consistency, this function should take seconds, not ms.
- return (SDL_CondWaitTimeout(condition_, l.mutex_->mutex_, ms) == 0);
- }
-
- bool notify() { return (SDL_CondSignal(condition_) == 0); }
- bool notifyAll() { return (SDL_CondBroadcast(condition_) == 0); }
-
-private:
- SDL_cond* condition_;
-};
-
-// =============================================================================
-
-class semaphore
-{
-public:
- semaphore(unsigned int value) { semaphore_ = SDL_CreateSemaphore(value); }
- ~semaphore() { SDL_DestroySemaphore(semaphore_); }
-
- bool acquireLock() { return (SDL_SemWait(semaphore_) == 0); }
- bool tryLock() { return (SDL_SemTryWait(semaphore_) == 0); }
- bool tryLock(unsigned ms)
- {
- // TODO: For consistency, this function should take seconds, not ms.
- return (SDL_SemWaitTimeout(semaphore_, ms) == 0);
- }
- bool releaseLock() { return (SDL_SemPost(semaphore_) == 0); }
-
- class lock
- {
- public:
- lock(semaphore& m) { semaphore_ = &m; isLocked_ = false; }
- ~lock() { if (isLocked_) release(); }
-
- bool acquire() { return (isLocked_ = semaphore_->acquireLock()); }
- bool release() { return semaphore_->releaseLock(); isLocked_ = false; }
- bool isLocked() const { return isLocked_; }
-
- protected:
- semaphore* semaphore_;
- bool isLocked_;
- };
-
- class scoped_lock : public lock
- {
- public:
- scoped_lock(semaphore& m) : lock(m) { acquire(); }
- };
-
-private:
- SDL_sem* semaphore_;
-};
-
-
-} // namespace thread
-} // namespace dc
-
-
-#endif // _THREAD_HH_
-
-/** vim: set ts=4 sw=4 tw=80: *************************************************/
-