Add event class
This commit is contained in:
@@ -1,7 +1,12 @@
|
||||
#ifndef CORE_H
|
||||
#define CORE_H
|
||||
|
||||
#include <csignal>
|
||||
#include <csignal> // raise
|
||||
#include <functional> // bind
|
||||
|
||||
#define BIT(x) (1 << x)
|
||||
|
||||
#define NF_BIND_EVENT(f) std::bind(&f, this, std::placeholders::_1)
|
||||
|
||||
// Debugging defines
|
||||
#ifndef NDEBUG
|
||||
|
||||
@@ -0,0 +1,89 @@
|
||||
#ifndef EVENT_H
|
||||
#define EVENT_H
|
||||
|
||||
#include <ostream> // ostream
|
||||
|
||||
#include "inferno/core.h"
|
||||
|
||||
namespace Inferno {
|
||||
|
||||
enum class EventType {
|
||||
None = 0,
|
||||
WindowClose,
|
||||
WindowResize,
|
||||
};
|
||||
|
||||
enum EventCategory {
|
||||
None = 0,
|
||||
ApplicationEventCategory = BIT(0),
|
||||
};
|
||||
|
||||
class Event {
|
||||
// EventDispatcher is allowed to access Event private/protected members
|
||||
friend class EventDispatcher;
|
||||
|
||||
public:
|
||||
virtual ~Event() {}
|
||||
|
||||
virtual std::string toString() const { return getName(); }
|
||||
|
||||
inline bool inCategory(EventCategory category)
|
||||
{
|
||||
return getCategoryFlags() & category;
|
||||
}
|
||||
|
||||
// -----------------------------------------
|
||||
|
||||
// Getter function templates
|
||||
virtual char getCategoryFlags() const = 0;
|
||||
virtual const char* getName() const = 0;
|
||||
virtual EventType getType() const = 0;
|
||||
|
||||
protected:
|
||||
bool handled = false;
|
||||
};
|
||||
|
||||
class EventDispatcher {
|
||||
public:
|
||||
EventDispatcher(Event &e) : m_event(e) {}
|
||||
|
||||
// Easily dispatch all type of Events, call with:
|
||||
// dispatch<T>(std::bind(&F, this, std::placeholders::_1));
|
||||
// T is the type of Event
|
||||
// F is the function to call, signature: bool name(T &e);
|
||||
template<typename T, typename F>
|
||||
bool dispatch(const F &function)
|
||||
{
|
||||
// If <constructed> type is same as member variable type
|
||||
if (T::getTypeStatic() == m_event.getType()) {
|
||||
// Call the function
|
||||
m_event.handled = function(static_cast<T &>(m_event));
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
private:
|
||||
Event &m_event;
|
||||
};
|
||||
|
||||
// Add class type functions macro
|
||||
#define EVENT_CLASS_TYPE(type) \
|
||||
virtual const char* getName() const override { return #type; } \
|
||||
virtual EventType getType() const override { return getTypeStatic(); } \
|
||||
static inline EventType getTypeStatic() { return EventType::type; }
|
||||
|
||||
// Add class catergory function macro
|
||||
#define EVENT_CLASS_CATEGORY(category) \
|
||||
virtual char getCategoryFlags() const override { return category; }
|
||||
|
||||
// Make Events easily printable
|
||||
inline std::ostream& operator<<(std::ostream &os, const Event &e)
|
||||
{
|
||||
return os << e.toString();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
#endif // EVENT_H
|
||||
Reference in New Issue
Block a user