Just™ Game Engine
event.hpp
Go to the documentation of this file.
1/*
2 * Copyright (C) 2021-2022 Konstanty Misiak
3 *
4 * SPDX-License-Identifier: MIT
5 */
6
7#pragma once
8#include <iostream>
9
10namespace jng {
11
12 // TODO: events are blocking for now, event queue in future?
13
14 enum class EventType
15 {
16 None = 0,
21 };
22
23 class Event
24 {
25 public:
26 virtual ~Event() = default;
27
28 virtual EventType getType() const = 0;
29 virtual const char* getName() const = 0;
30 virtual std::string to_string() const { return getName(); }
31 bool isHandled() const { return m_handled; }
32 protected:
33 bool m_handled = false;
34 private:
35 friend class EventDispatcher;
36 };
37
38 inline std::ostream& operator<<(std::ostream& os, const Event& event)
39 {
40 return os << event.to_string();
41 }
42
44 {
45 public:
46 explicit EventDispatcher(Event& event) :
47 m_event(event) {}
48
49 template<typename T, typename F>
50 bool dispatch(const F& func) {
51 if (m_event.getType() == T::getStaticType()) {
52 m_event.m_handled = func(static_cast<T&>(m_event));
53 return true;
54 }
55 return false;
56 }
57 private:
58 Event& m_event;
59 };
60
61#define EVENT_CLASS_TYPE(type) static EventType getStaticType() { return EventType::type; } \
62 EventType getType() const override { return getStaticType(); } \
63 const char* getName() const override { return #type; }
64
65} // namespace jng
Definition: event.hpp:44
EventDispatcher(Event &event)
Definition: event.hpp:46
bool dispatch(const F &func)
Definition: event.hpp:50
Definition: event.hpp:24
bool isHandled() const
Definition: event.hpp:31
virtual std::string to_string() const
Definition: event.hpp:30
virtual EventType getType() const =0
virtual ~Event()=default
virtual const char * getName() const =0
bool m_handled
Definition: event.hpp:33
constexpr Code T
Definition: key_codes.hpp:56
constexpr Code F
Definition: key_codes.hpp:42
Definition: base.hpp:11
std::ostream & operator<<(std::ostream &os, const Event &event)
Definition: event.hpp:38
EventType
Definition: event.hpp:15