From 4628638f952f882e494788ca1cf880a029eba5ab Mon Sep 17 00:00:00 2001 From: WBoerenkamps Date: Tue, 1 Oct 2024 13:40:56 +0200 Subject: first try at events --- mwe/events/src/eventManager.cpp | 1 + mwe/events/src/main.cpp | 14 ++++++++++++++ mwe/events/src/window.cpp | 33 +++++++++++++++++++++++++++++++++ 3 files changed, 48 insertions(+) create mode 100644 mwe/events/src/eventManager.cpp create mode 100644 mwe/events/src/main.cpp create mode 100644 mwe/events/src/window.cpp (limited to 'mwe/events/src') diff --git a/mwe/events/src/eventManager.cpp b/mwe/events/src/eventManager.cpp new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/mwe/events/src/eventManager.cpp @@ -0,0 +1 @@ + diff --git a/mwe/events/src/main.cpp b/mwe/events/src/main.cpp new file mode 100644 index 0000000..8d8567d --- /dev/null +++ b/mwe/events/src/main.cpp @@ -0,0 +1,14 @@ +#include +#include +#include "event.h" + + +int main(int argc, char * args[]) { + + KeyPressedEvent keyEvent(1,1); + KeyReleasedEvent keyRelease(1); + std::cout << keyEvent.GetEventType() << std::endl; + std::cout << keyRelease.GetEventType() << std::endl; + std::cin; + return 0; +} diff --git a/mwe/events/src/window.cpp b/mwe/events/src/window.cpp new file mode 100644 index 0000000..61a4105 --- /dev/null +++ b/mwe/events/src/window.cpp @@ -0,0 +1,33 @@ +#include "window.h" +WindowManager::WindowManager() { + if (!initWindow()) { + printf("Failed to initialize!\n"); + } +} +WindowManager::~WindowManager() { destroyWindow(); } +SDL_Renderer * WindowManager::getRenderer() { return renderer; } + +bool WindowManager::initWindow() { + if (SDL_Init(SDL_INIT_EVERYTHING) != 0) { + fprintf(stderr, "Error inititalising SDL.\n"); + return false; + } + window = SDL_CreateWindow("SDL Tutorial", SDL_WINDOWPOS_UNDEFINED, + SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, + SCREEN_HEIGHT, SDL_WINDOW_SHOWN); + if (!window) { + fprintf(stderr, "Error creating SDL Window. \n"); + return false; + } + renderer = SDL_CreateRenderer(window, -1, 0); + if (!renderer) { + fprintf(stderr, "Error creating SDL renderer. \n"); + return false; + } + return true; +} +void WindowManager::destroyWindow() { + SDL_DestroyRenderer(renderer); + SDL_DestroyWindow(window); + SDL_Quit(); +} -- cgit v1.2.3 From 51c8a51b53a850265955a3e4bc45b40ad3f8c477 Mon Sep 17 00:00:00 2001 From: WBoerenkamps Date: Wed, 23 Oct 2024 21:13:28 +0200 Subject: custom commit poc working --- mwe/.vscode/settings.json | 11 ++ mwe/events/.vscode/c_cpp_properties.json | 15 ++ mwe/events/.vscode/settings.json | 16 +- mwe/events/CMakeLists.txt | 6 + mwe/events/include/event.h | 245 +++++++------------------------ mwe/events/include/eventHandler.h | 35 +++-- mwe/events/include/eventManager.h | 63 ++++++-- mwe/events/include/keyCodes.h | 143 ++++++++++++++++++ mwe/events/include/loopManager.h | 28 ++++ mwe/events/include/timer.h | 31 ++++ mwe/events/src/event.cpp | 56 +++++++ mwe/events/src/eventHandler.cpp | 5 + mwe/events/src/eventManager.cpp | 108 ++++++++++++++ mwe/events/src/keyCodes.cpp | 140 ++++++++++++++++++ mwe/events/src/loopManager.cpp | 90 ++++++++++++ mwe/events/src/main.cpp | 54 +++++-- mwe/events/src/timer.cpp | 54 +++++++ mwe/events/src/window.cpp | 3 - mwe/gameloop/include/loopManager.h | 1 + 19 files changed, 878 insertions(+), 226 deletions(-) create mode 100644 mwe/.vscode/settings.json create mode 100644 mwe/events/.vscode/c_cpp_properties.json create mode 100644 mwe/events/include/keyCodes.h create mode 100644 mwe/events/include/loopManager.h create mode 100644 mwe/events/include/timer.h create mode 100644 mwe/events/src/event.cpp create mode 100644 mwe/events/src/eventHandler.cpp create mode 100644 mwe/events/src/keyCodes.cpp create mode 100644 mwe/events/src/loopManager.cpp create mode 100644 mwe/events/src/timer.cpp (limited to 'mwe/events/src') diff --git a/mwe/.vscode/settings.json b/mwe/.vscode/settings.json new file mode 100644 index 0000000..c7913ab --- /dev/null +++ b/mwe/.vscode/settings.json @@ -0,0 +1,11 @@ +{ + "files.associations": { + "variant": "cpp", + "*.tcc": "cpp", + "string": "cpp", + "unordered_map": "cpp", + "string_view": "cpp", + "ostream": "cpp", + "iostream": "cpp" + } +} diff --git a/mwe/events/.vscode/c_cpp_properties.json b/mwe/events/.vscode/c_cpp_properties.json new file mode 100644 index 0000000..64d3f90 --- /dev/null +++ b/mwe/events/.vscode/c_cpp_properties.json @@ -0,0 +1,15 @@ +{ + "configurations": [ + { + "name": "Linux", + "includePath": [ + "${workspaceFolder}/**" + ], + "defines": [], + "cStandard": "c17", + "cppStandard": "c++17", + "intelliSenseMode": "linux-clang-x64" + } + ], + "version": 4 +} \ No newline at end of file diff --git a/mwe/events/.vscode/settings.json b/mwe/events/.vscode/settings.json index b2c5be7..816d790 100644 --- a/mwe/events/.vscode/settings.json +++ b/mwe/events/.vscode/settings.json @@ -49,6 +49,20 @@ "streambuf": "cpp", "cinttypes": "cpp", "typeinfo": "cpp", - "valarray": "cpp" + "valarray": "cpp", + "variant": "cpp", + "condition_variable": "cpp", + "ctime": "cpp", + "forward_list": "cpp", + "executor": "cpp", + "io_context": "cpp", + "netfwd": "cpp", + "ratio": "cpp", + "timer": "cpp", + "future": "cpp", + "mutex": "cpp", + "semaphore": "cpp", + "stop_token": "cpp", + "thread": "cpp" } } diff --git a/mwe/events/CMakeLists.txt b/mwe/events/CMakeLists.txt index 3bbda37..585d869 100644 --- a/mwe/events/CMakeLists.txt +++ b/mwe/events/CMakeLists.txt @@ -13,7 +13,13 @@ find_package(SDL2 REQUIRED) add_executable(gameloop src/window.cpp src/main.cpp + #src/eventHandler.cpp src/eventManager.cpp + src/event.cpp + src/loopManager.cpp + src/timer.cpp + src/keyCodes.cpp + src/eventHandler.cpp ) # Link the SDL2 library to your project diff --git a/mwe/events/include/event.h b/mwe/events/include/event.h index f5f426a..802140c 100644 --- a/mwe/events/include/event.h +++ b/mwe/events/include/event.h @@ -4,215 +4,84 @@ #include #include #include -using Keycode = uint16_t; -enum : Keycode { - // From glfw3.h - Space = 32, - Apostrophe = 39, /* ' */ - Comma = 44, /* , */ - Minus = 45, /* - */ - Period = 46, /* . */ - Slash = 47, /* / */ - - D0 = 48, /* 0 */ - D1 = 49, /* 1 */ - D2 = 50, /* 2 */ - D3 = 51, /* 3 */ - D4 = 52, /* 4 */ - D5 = 53, /* 5 */ - D6 = 54, /* 6 */ - D7 = 55, /* 7 */ - D8 = 56, /* 8 */ - D9 = 57, /* 9 */ - - Semicolon = 59, /* ; */ - Equal = 61, /* = */ - - A = 65, - B = 66, - C = 67, - D = 68, - E = 69, - F = 70, - G = 71, - H = 72, - I = 73, - J = 74, - K = 75, - L = 76, - M = 77, - N = 78, - O = 79, - P = 80, - Q = 81, - R = 82, - S = 83, - T = 84, - U = 85, - V = 86, - W = 87, - X = 88, - Y = 89, - Z = 90, - - LeftBracket = 91, /* [ */ - Backslash = 92, /* \ */ - RightBracket = 93, /* ] */ - GraveAccent = 96, /* ` */ - - World1 = 161, /* non-US #1 */ - World2 = 162, /* non-US #2 */ - - /* Function keys */ - Escape = 256, - Enter = 257, - Tab = 258, - Backspace = 259, - Insert = 260, - Delete = 261, - Right = 262, - Left = 263, - Down = 264, - Up = 265, - PageUp = 266, - PageDown = 267, - Home = 268, - End = 269, - CapsLock = 280, - ScrollLock = 281, - NumLock = 282, - PrintScreen = 283, - Pause = 284, - F1 = 290, - F2 = 291, - F3 = 292, - F4 = 293, - F5 = 294, - F6 = 295, - F7 = 296, - F8 = 297, - F9 = 298, - F10 = 299, - F11 = 300, - F12 = 301, - F13 = 302, - F14 = 303, - F15 = 304, - F16 = 305, - F17 = 306, - F18 = 307, - F19 = 308, - F20 = 309, - F21 = 310, - F22 = 311, - F23 = 312, - F24 = 313, - F25 = 314, - - /* Keypad */ - KP0 = 320, - KP1 = 321, - KP2 = 322, - KP3 = 323, - KP4 = 324, - KP5 = 325, - KP6 = 326, - KP7 = 327, - KP8 = 328, - KP9 = 329, - KPDecimal = 330, - KPDivide = 331, - KPMultiply = 332, - KPSubtract = 333, - KPAdd = 334, - KPEnter = 335, - KPEqual = 336, - - LeftShift = 340, - LeftControl = 341, - LeftAlt = 342, - LeftSuper = 343, - RightShift = 344, - RightControl = 345, - RightAlt = 346, - RightSuper = 347, - Menu = 348 -}; +#include "keyCodes.h" class UUIDGenerator { public: - static std::uint32_t GetUniqueID() - { + static std::uint32_t getUniqueID() { static std::uint32_t id = 0; return ++id; } }; -#define EVENT_TYPE(event_type) \ - static std::uint32_t GetStaticEventType() \ - { \ - static std::uint32_t type = UUIDGenerator::GetUniqueID(); \ - return type; \ - } \ - std::uint32_t GetEventId() const override \ - { \ - return GetStaticEventType(); \ +#define REGISTER_EVENT_TYPE(ClassName) \ +public: \ + static std::uint32_t getStaticEventType() { \ + static std::uint32_t typeID = UUIDGenerator::getUniqueID(); \ + return typeID; \ + } \ + virtual std::uint32_t getEventType() const override { \ + return getStaticEventType(); \ } class Event { - public: - Event(std::string eventType) { - eventData["eventType"] = eventType; - } - virtual ~Event() = default; - - virtual std::uint32_t GetEventId() const = 0; - virtual std::string toString() const { - return std::to_string(GetEventId()); - } - - void addArgument(const std::string& key, const std::variant& value); - - std::variant getArgument(const std::string& key) const; - - std::string getType() const; - bool isHandled() const; - void markHandled(); - private: - std::unordered_map> eventData; - bool isHandled = false; +public: + Event(std::string eventType); + virtual ~Event() = default; + virtual std::uint32_t getEventType() const = 0; + virtual std::string toString() const; + void addArgument(const std::string& key, const std::variant& value); + + std::variant getArgument(const std::string& key) const; + + std::string getType() const; + bool getHandled() const; + void markHandled(); + +private: + std::unordered_map> eventData; + bool isHandled = false; }; +// KeyPressedEvent class class KeyPressedEvent : public Event { - public: - EVENT_TYPE("KeyPressedEvent"); - KeyPressedEvent(int keyCode); - Keycode getKeyCode() const; - int getRepeatCount() const; - private: - Keycode keycode; +public: + KeyPressedEvent(int keyCode); + + REGISTER_EVENT_TYPE("KeyPressedEvent"); + + Keycode getKeyCode() const; + int getRepeatCount() const; + +private: + Keycode keycode; + public: Keycode key = 0; int repeatCount = 0; }; +// KeyReleasedEvent class class KeyReleasedEvent : public Event { - public: - EVENT_TYPE("KeyReleasedEvent"); - KeyReleasedEvent(int keyCode); - Keycode getKeyCode(); - private: - Keycode keycode; public: + KeyReleasedEvent(int keyCode); + + REGISTER_EVENT_TYPE(KeyReleasedEvent); + + Keycode getKeyCode() const; + +private: Keycode key = 0; }; +// MousePressedEvent class class MousePressedEvent : public Event { - public: - EVENT_TYPE("MousePressedEvent"); - MousePressedEvent(int mouseX,int mouseY); - std::pair getMousePosition(); - private: - Keycode keycode; - int mouseX = 0; - int mouseY = 0; - +public: + MousePressedEvent(int mouseX, int mouseY); + + REGISTER_EVENT_TYPE(MousePressedEvent) + + std::pair getMousePosition() const; + +private: + int mouseX = 0; + int mouseY = 0; }; diff --git a/mwe/events/include/eventHandler.h b/mwe/events/include/eventHandler.h index 03017dd..e5b99d6 100644 --- a/mwe/events/include/eventHandler.h +++ b/mwe/events/include/eventHandler.h @@ -1,39 +1,48 @@ #pragma once + #include "event.h" -#include + #include +#include template using EventHandler = std::function; -class IEventHandlerWrapper{ + +class IEventHandlerWrapper { public: - void Exec(const Event& e) - { - Call(e); - } + virtual ~IEventHandlerWrapper() = default; + + void exec(const Event& e); - virtual std::string GetType() const = 0; + virtual std::string getType() const = 0; + virtual bool isDestroyOnSuccess() const = 0; private: - virtual void Call(const Event& e) = 0; + virtual void call(const Event& e) = 0; }; template class EventHandlerWrapper : public IEventHandlerWrapper { public: - explicit EventHandlerWrapper(const EventHandler& handler) + explicit EventHandlerWrapper(const EventHandler& handler, const bool destroyOnSuccess = false) : m_handler(handler) - , m_handlerType(m_handler.target_type().name()) {}; + , m_handlerType(m_handler.target_type().name()) + , m_destroyOnSuccess(destroyOnSuccess) + { + // std::cout << m_handlerType << std::endl; + } private: - void Call(const Event& e) override + void call(const Event& e) override { - if (e.GetEventType() == EventType::GetStaticEventType()) { + if (e.getEventType() == EventType::getStaticEventType()) { m_handler(static_cast(e)); } } - std::string GetType() const override { return m_handlerType; } + std::string getType() const override { return m_handlerType; } + bool isDestroyOnSuccess() const { return m_destroyOnSuccess; } EventHandler m_handler; const std::string m_handlerType; + bool m_destroyOnSuccess { false }; }; diff --git a/mwe/events/include/eventManager.h b/mwe/events/include/eventManager.h index 93def36..709796a 100644 --- a/mwe/events/include/eventManager.h +++ b/mwe/events/include/eventManager.h @@ -2,17 +2,56 @@ #include #include #include "event.h" +#include "keyCodes.h" #include "eventHandler.h" -using EventType = int; -using EventId = int; -class EventManager{ - public: - - void subscribe(EventId eventId,std::unique_ptr&& handler); - void unsubscribe(EventId eventId, const std::string& handlerName); - void dispatchEvents(); - void triggerEvent(EventId eventId); - void queueEvent(); - private: - std::unordered_map>> m_subscribers; +#include +// using EventType = std::uint32_t; +// using EventId = std::uint64_t; + +class EventManager { +public: + EventManager(const EventManager&) = delete; + const EventManager& operator=(const EventManager&) = delete; + static EventManager& getInstance() { + static EventManager instance; + return instance; + } + + void shutdown(); + void subscribe(int eventType, std::unique_ptr&& handler, int eventId); + void unsubscribe(int eventType, const std::string& handlerName, int eventId); + void triggerEvent(const Event& event_, int eventId); + void queueEvent(std::unique_ptr&& event_, int eventId); + void dispatchEvents(); + +private: + EventManager() = default; + std::vector, int>> m_eventsQueue; + std::unordered_map>> m_subscribers; + std::unordered_map>>> m_subscribersByEventId; }; + + +template +inline void subscribe(const EventHandler& callback, int eventId = 0, const bool unsubscribeOnSuccess = false) +{ + std::unique_ptr handler = std::make_unique>(callback, unsubscribeOnSuccess); + EventManager::getInstance().subscribe(EventType::getStaticEventType(), std::move(handler), eventId); +} + +template +inline void unsubscribe(const EventHandler& callback, int eventId = 0) +{ + const std::string handlerName = callback.target_type().name(); + EventManager::getInstance().unsubscribe(EventType::getStaticEventType(), handlerName, eventId); +} + +inline void triggerEvent(const Event& triggeredEvent, int eventId = 0) +{ + EventManager::getInstance().triggerEvent(triggeredEvent, eventId); +} + +inline void queueEvent(std::unique_ptr&& queuedEvent, int eventId = 0) +{ + EventManager::getInstance().queueEvent(std::forward>(queuedEvent), eventId); +} diff --git a/mwe/events/include/keyCodes.h b/mwe/events/include/keyCodes.h new file mode 100644 index 0000000..c3a7826 --- /dev/null +++ b/mwe/events/include/keyCodes.h @@ -0,0 +1,143 @@ +#pragma once +#include +#include +#include +using Keycode = uint16_t; +enum : Keycode { + // From glfw3.h + Space = 32, + Apostrophe = 39, /* ' */ + Comma = 44, /* , */ + Minus = 45, /* - */ + Period = 46, /* . */ + Slash = 47, /* / */ + + D0 = 48, /* 0 */ + D1 = 49, /* 1 */ + D2 = 50, /* 2 */ + D3 = 51, /* 3 */ + D4 = 52, /* 4 */ + D5 = 53, /* 5 */ + D6 = 54, /* 6 */ + D7 = 55, /* 7 */ + D8 = 56, /* 8 */ + D9 = 57, /* 9 */ + + Semicolon = 59, /* ; */ + Equal = 61, /* = */ + + A = 65, + B = 66, + C = 67, + D = 68, + E = 69, + F = 70, + G = 71, + H = 72, + I = 73, + J = 74, + K = 75, + L = 76, + M = 77, + N = 78, + O = 79, + P = 80, + Q = 81, + R = 82, + S = 83, + T = 84, + U = 85, + V = 86, + W = 87, + X = 88, + Y = 89, + Z = 90, + + LeftBracket = 91, /* [ */ + Backslash = 92, /* \ */ + RightBracket = 93, /* ] */ + GraveAccent = 96, /* ` */ + + World1 = 161, /* non-US #1 */ + World2 = 162, /* non-US #2 */ + + /* Function keys */ + Escape = 256, + Enter = 257, + Tab = 258, + Backspace = 259, + Insert = 260, + Delete = 261, + Right = 262, + Left = 263, + Down = 264, + Up = 265, + PageUp = 266, + PageDown = 267, + Home = 268, + End = 269, + CapsLock = 280, + ScrollLock = 281, + NumLock = 282, + PrintScreen = 283, + Pause = 284, + F1 = 290, + F2 = 291, + F3 = 292, + F4 = 293, + F5 = 294, + F6 = 295, + F7 = 296, + F8 = 297, + F9 = 298, + F10 = 299, + F11 = 300, + F12 = 301, + F13 = 302, + F14 = 303, + F15 = 304, + F16 = 305, + F17 = 306, + F18 = 307, + F19 = 308, + F20 = 309, + F21 = 310, + F22 = 311, + F23 = 312, + F24 = 313, + F25 = 314, + + /* Keypad */ + KP0 = 320, + KP1 = 321, + KP2 = 322, + KP3 = 323, + KP4 = 324, + KP5 = 325, + KP6 = 326, + KP7 = 327, + KP8 = 328, + KP9 = 329, + KPDecimal = 330, + KPDivide = 331, + KPMultiply = 332, + KPSubtract = 333, + KPAdd = 334, + KPEnter = 335, + KPEqual = 336, + + LeftShift = 340, + LeftControl = 341, + LeftAlt = 342, + LeftSuper = 343, + RightShift = 344, + RightControl = 345, + RightAlt = 346, + RightSuper = 347, + Menu = 348 +}; +// Define the mapping +extern const std::unordered_map sdlToCustom; + +// Function to map SDL_Keycode to custom Keycode +Keycode getCustomKey(SDL_Keycode sdlKey); diff --git a/mwe/events/include/loopManager.h b/mwe/events/include/loopManager.h new file mode 100644 index 0000000..5c519d9 --- /dev/null +++ b/mwe/events/include/loopManager.h @@ -0,0 +1,28 @@ +#pragma once +#include "window.h" +#include +#include "timer.h" +//#include "combinedEvent.h" +#include "eventManager.h" +#include "loopManager.h" +#include "eventHandler.h" +class LoopManager { +public: + LoopManager(); + void setup(); + void loop(); + void setRunning(bool running); +private: + void processInput(); + void update(); + void lateUpdate(); + void fixedUpdate(); + void render(); + bool gameRunning = false; + WindowManager window; + int timeScale = 1; + float accumulator = 0.0; + double currentTime; + double t = 0.0; + double dt = 0.01; +}; diff --git a/mwe/events/include/timer.h b/mwe/events/include/timer.h new file mode 100644 index 0000000..22383b2 --- /dev/null +++ b/mwe/events/include/timer.h @@ -0,0 +1,31 @@ +#pragma once + +#include + +class LoopTimer { +public: + static LoopTimer & getInstance(); + void start(); + void update(); + double getDeltaTime() const; + int getCurrentTime() const; + void advanceFixedUpdate(); + double getFixedDeltaTime() const; + void setFPS(int FPS); + int getFPS() const; + void enforceFrameRate(); + double getLag() const; + +private: + LoopTimer(); + int FPS = 50; + double gameScale = 1; + double maximumDeltaTime = 0.25; + double deltaTime; + double frameTargetTime = FPS / 1000; + double fixedDeltaTime = 0.01; + double elapsedTime; + double elapsedFixedTime; + double time; + uint64_t lastFrameTime; +}; diff --git a/mwe/events/src/event.cpp b/mwe/events/src/event.cpp new file mode 100644 index 0000000..fecae76 --- /dev/null +++ b/mwe/events/src/event.cpp @@ -0,0 +1,56 @@ +#include "event.h" +#include "keyCodes.h" +// Event class methods +Event::Event(std::string eventType) { + eventData["eventType"] = eventType; +} + +void Event::addArgument(const std::string& key, const std::variant& value) { + eventData[key] = value; +} + +std::variant Event::getArgument(const std::string& key) const { + return eventData.at(key); +} + +std::string Event::getType() const { + return std::get(eventData.at("eventType")); +} +std::string Event::toString() const { + return std::to_string(getEventType()); +} +bool Event::getHandled() const { + return isHandled; +} + +void Event::markHandled() { + isHandled = true; +} + +// KeyPressedEvent class methods +KeyPressedEvent::KeyPressedEvent(int keycode) + : Event("KeyPressedEvent"), key(keycode), repeatCount(0) {} + +Keycode KeyPressedEvent::getKeyCode() const { + return key; +} + +int KeyPressedEvent::getRepeatCount() const { + return repeatCount; +} + +// KeyReleasedEvent class methods +KeyReleasedEvent::KeyReleasedEvent(int keycode) + : Event("KeyReleasedEvent"), key(keycode) {} + +Keycode KeyReleasedEvent::getKeyCode() const { + return key; +} + +// MousePressedEvent class methods +MousePressedEvent::MousePressedEvent(int mouseX, int mouseY) + : Event("MousePressedEvent"), mouseX(mouseX), mouseY(mouseY) {} + +std::pair MousePressedEvent::getMousePosition() const { + return {mouseX, mouseY}; +} diff --git a/mwe/events/src/eventHandler.cpp b/mwe/events/src/eventHandler.cpp new file mode 100644 index 0000000..7040d8d --- /dev/null +++ b/mwe/events/src/eventHandler.cpp @@ -0,0 +1,5 @@ +#include "eventHandler.h" +void IEventHandlerWrapper::exec(const Event& e) + { + call(e); + } diff --git a/mwe/events/src/eventManager.cpp b/mwe/events/src/eventManager.cpp index 8b13789..ce8e940 100644 --- a/mwe/events/src/eventManager.cpp +++ b/mwe/events/src/eventManager.cpp @@ -1 +1,109 @@ +#include "eventManager.h" +void EventManager::shutdown() +{ + m_subscribers.clear(); +} + +void EventManager::subscribe(int eventType, std::unique_ptr&& handler, int eventId) +{ + if (eventId) { + std::unordered_map>>>::iterator subscribers = m_subscribersByEventId.find(eventType); + + if (subscribers != m_subscribersByEventId.end()) { + std::unordered_map>>& handlersMap = subscribers->second; + std::unordered_map>>::iterator handlers = handlersMap.find(eventId); + if (handlers != handlersMap.end()) { + handlers->second.emplace_back(std::move(handler)); + return; + } + } + m_subscribersByEventId[eventType][eventId].emplace_back(std::move(handler)); + + } else { + std::unordered_map>>::iterator subscribers = m_subscribers.find(eventType); + if (subscribers != m_subscribers.end()) { + std::vector>& handlers = subscribers->second; + for (std::unique_ptr& it : handlers) { + if (it->getType() == handler->getType()) { + // log for double register + return; + } + } + handlers.emplace_back(std::move(handler)); + } else { + m_subscribers[eventType].emplace_back(std::move(handler)); + } + } +} + +void EventManager::unsubscribe(int eventType, const std::string& handlerName, int eventId) +{ + if (eventId) { + std::unordered_map>>>::iterator subscribers = m_subscribersByEventId.find(eventType); + if (subscribers != m_subscribersByEventId.end()) { + std::unordered_map>>& handlersMap = subscribers->second; + std::unordered_map>>::iterator handlers = handlersMap.find(eventId); + if (handlers != handlersMap.end()) { + std::vector>& callbacks = handlers->second; + for (std::vector>::iterator it = callbacks.begin(); it != callbacks.end(); ++it) { + if (it->get()->getType() == handlerName) { + it = callbacks.erase(it); + return; + } + } + } + } + } else { + std::unordered_map>>::iterator handlersIt = m_subscribers.find(eventType); + if (handlersIt != m_subscribers.end()) { + std::vector>& handlers = handlersIt->second; + for (std::vector>::iterator it = handlers.begin(); it != handlers.end(); ++it) { + if (it->get()->getType() == handlerName) { + it = handlers.erase(it); + return; + } + } + } + } +} + +void EventManager::triggerEvent(const Event& event_, int eventId) +{ + std::vector>& handlers = m_subscribers[event_.getEventType()]; + for (std::unique_ptr& handler : handlers) { + handler->exec(event_); + } + + std::unordered_map>>& handlersMap = m_subscribersByEventId[event_.getEventType()]; + std::unordered_map>>::iterator handlersIt = handlersMap.find(eventId); + if (handlersIt != handlersMap.end()) { + std::vector>& callbacks = handlersIt->second; + for (std::vector>::iterator it = callbacks.begin(); it != callbacks.end();) { + std::unique_ptr& handler = *it; + handler->exec(event_); + if (handler->isDestroyOnSuccess()) { + it = callbacks.erase(it); + } else { + ++it; + } + } + } +} + +void EventManager::queueEvent(std::unique_ptr&& event_, int eventId) +{ + m_eventsQueue.emplace_back(std::move(event_), eventId); +} + +void EventManager::dispatchEvents() +{ + for (std::vector, int>>::iterator eventIt = m_eventsQueue.begin(); eventIt != m_eventsQueue.end();) { + if (!eventIt->first.get()->getHandled()) { + triggerEvent(*eventIt->first.get(), eventIt->second); + eventIt = m_eventsQueue.erase(eventIt); + } else { + ++eventIt; + } + } +} diff --git a/mwe/events/src/keyCodes.cpp b/mwe/events/src/keyCodes.cpp new file mode 100644 index 0000000..6f35d11 --- /dev/null +++ b/mwe/events/src/keyCodes.cpp @@ -0,0 +1,140 @@ +#include "keyCodes.h" + +const std::unordered_map sdlToCustom = { + { SDLK_SPACE, Space }, + { SDLK_QUOTE, Apostrophe }, + { SDLK_COMMA, Comma }, + { SDLK_MINUS, Minus }, + { SDLK_PERIOD, Period }, + { SDLK_SLASH, Slash }, + + { SDLK_0, D0 }, + { SDLK_1, D1 }, + { SDLK_2, D2 }, + { SDLK_3, D3 }, + { SDLK_4, D4 }, + { SDLK_5, D5 }, + { SDLK_6, D6 }, + { SDLK_7, D7 }, + { SDLK_8, D8 }, + { SDLK_9, D9 }, + + { SDLK_SEMICOLON, Semicolon }, + { SDLK_EQUALS, Equal }, + + { SDLK_a, A }, + { SDLK_b, B }, + { SDLK_c, C }, + { SDLK_d, D }, + { SDLK_e, E }, + { SDLK_f, F }, + { SDLK_g, G }, + { SDLK_h, H }, + { SDLK_i, I }, + { SDLK_j, J }, + { SDLK_k, K }, + { SDLK_l, L }, + { SDLK_m, M }, + { SDLK_n, N }, + { SDLK_o, O }, + { SDLK_p, P }, + { SDLK_q, Q }, + { SDLK_r, R }, + { SDLK_s, S }, + { SDLK_t, T }, + { SDLK_u, U }, + { SDLK_v, V }, + { SDLK_w, W }, + { SDLK_x, X }, + { SDLK_y, Y }, + { SDLK_z, Z }, + + { SDLK_LEFTBRACKET, LeftBracket }, + { SDLK_BACKSLASH, Backslash }, + { SDLK_RIGHTBRACKET, RightBracket }, + { SDLK_BACKQUOTE, GraveAccent }, + + { SDLK_ESCAPE, Escape }, + { SDLK_RETURN, Enter }, + { SDLK_TAB, Tab }, + { SDLK_BACKSPACE, Backspace }, + { SDLK_INSERT, Insert }, + { SDLK_DELETE, Delete }, + { SDLK_RIGHT, Right }, + { SDLK_LEFT, Left }, + { SDLK_DOWN, Down }, + { SDLK_UP, Up }, + { SDLK_PAGEUP, PageUp }, + { SDLK_PAGEDOWN, PageDown }, + { SDLK_HOME, Home }, + { SDLK_END, End }, + + { SDLK_CAPSLOCK, CapsLock }, + { SDLK_SCROLLLOCK, ScrollLock }, + { SDLK_NUMLOCKCLEAR, NumLock }, + { SDLK_PRINTSCREEN, PrintScreen }, + { SDLK_PAUSE, Pause }, + + { SDLK_F1, F1 }, + { SDLK_F2, F2 }, + { SDLK_F3, F3 }, + { SDLK_F4, F4 }, + { SDLK_F5, F5 }, + { SDLK_F6, F6 }, + { SDLK_F7, F7 }, + { SDLK_F8, F8 }, + { SDLK_F9, F9 }, + { SDLK_F10, F10 }, + { SDLK_F11, F11 }, + { SDLK_F12, F12 }, + { SDLK_F13, F13 }, + { SDLK_F14, F14 }, + { SDLK_F15, F15 }, + { SDLK_F16, F16 }, + { SDLK_F17, F17 }, + { SDLK_F18, F18 }, + { SDLK_F19, F19 }, + { SDLK_F20, F20 }, + { SDLK_F21, F21 }, + { SDLK_F22, F22 }, + { SDLK_F23, F23 }, + { SDLK_F24, F24 }, + + { SDLK_KP_0, KP0 }, + { SDLK_KP_1, KP1 }, + { SDLK_KP_2, KP2 }, + { SDLK_KP_3, KP3 }, + { SDLK_KP_4, KP4 }, + { SDLK_KP_5, KP5 }, + { SDLK_KP_6, KP6 }, + { SDLK_KP_7, KP7 }, + { SDLK_KP_8, KP8 }, + { SDLK_KP_9, KP9 }, + + { SDLK_KP_DECIMAL, KPDecimal }, + { SDLK_KP_DIVIDE, KPDivide }, + { SDLK_KP_MULTIPLY, KPMultiply }, + { SDLK_KP_MINUS, KPSubtract }, + { SDLK_KP_PLUS, KPAdd }, + { SDLK_KP_ENTER, KPEnter }, + { SDLK_KP_EQUALS, KPEqual }, + + { SDLK_LSHIFT, LeftShift }, + { SDLK_LCTRL, LeftControl }, + { SDLK_LALT, LeftAlt }, + { SDLK_LGUI, LeftSuper }, + + { SDLK_RSHIFT, RightShift }, + { SDLK_RCTRL, RightControl }, + { SDLK_RALT, RightAlt }, + { SDLK_RGUI, RightSuper }, + + { SDLK_MENU, Menu } +}; +Keycode getCustomKey(SDL_Keycode sdlKey) { + auto it = sdlToCustom.find(sdlKey); + if (it != sdlToCustom.end()) { + return it->second; + } + return 0; +} diff --git a/mwe/events/src/loopManager.cpp b/mwe/events/src/loopManager.cpp new file mode 100644 index 0000000..6defda0 --- /dev/null +++ b/mwe/events/src/loopManager.cpp @@ -0,0 +1,90 @@ +#include "loopManager.h" + +LoopManager::LoopManager() {} +void LoopManager::processInput() { + SDL_Event event; + SDL_PollEvent(&event); + switch (event.type) { + case SDL_QUIT: + gameRunning = false; + break; + case SDL_KEYDOWN: + triggerEvent(KeyPressedEvent(getCustomKey(event.key.keysym.sym))); + break; + case SDL_MOUSEBUTTONDOWN: + int x, y; + SDL_GetMouseState(&x, &y); + triggerEvent(MousePressedEvent(x, y)); + break; + } +} +void LoopManager::setRunning(bool running){ + this->gameRunning = running; +} +void LoopManager::fixedUpdate() { + //fprintf(stderr, "fixed update\n"); +} +void LoopManager::loop() { + LoopTimer & timer = LoopTimer::getInstance(); + timer.start(); + + while (gameRunning) { + timer.update(); + + while (timer.getLag() >= timer.getFixedDeltaTime()) { + processInput(); + fixedUpdate(); + timer.advanceFixedUpdate(); + } + + update(); + render(); + + timer.enforceFrameRate(); + } + + window.destroyWindow(); +} +void onKey(const KeyPressedEvent& e) +{ + int keyCode = e.getKeyCode(); + std::cout << "keycode pressed: " << keyCode << std::endl; + +} +void onMouse(const MousePressedEvent& e){ + fprintf(stderr, "mouse Position X: %d Y: %d\n", e.getMousePosition().first, e.getMousePosition().second); +} +void LoopManager::setup() { + gameRunning = window.initWindow(); + LoopTimer::getInstance().start(); + LoopTimer::getInstance().setFPS(50); + EventHandler callback = onKey; + subscribe(callback,false); + EventHandler mouseCallback = onMouse; + subscribe(mouseCallback ,false); + EventHandler closeWindowCallback = [this](const KeyPressedEvent& e) { + if(e.getKeyCode() == Escape){ + this->setRunning(false); + } + }; + subscribe(closeWindowCallback,false); + +} +void LoopManager::render() { + //fprintf(stderr, "**********render********** \n"); + if (gameRunning) { + //window.render(objectList); + } +} + +void LoopManager::update() { + //fprintf(stderr, "**********normal update********** \n"); + LoopTimer & timer = LoopTimer::getInstance(); + + float delta = timer.getDeltaTime(); + + // for (int i = 0; i < objectList.size(); i++) { + // objectList[i]->setX(objectList[i]->getX() + 50 * delta); + // objectList[i]->setY(objectList[i]->getY() + 50 * delta); + // } +} diff --git a/mwe/events/src/main.cpp b/mwe/events/src/main.cpp index 8d8567d..3940c60 100644 --- a/mwe/events/src/main.cpp +++ b/mwe/events/src/main.cpp @@ -1,14 +1,50 @@ #include -#include +#include +#include +#include "loopManager.h" #include "event.h" +class PlayerDamagedEvent : public Event { +public: + PlayerDamagedEvent(int damage, int playerID) + : Event("PlayerDamaged"), damage(damage), playerID(playerID) {} -int main(int argc, char * args[]) { - - KeyPressedEvent keyEvent(1,1); - KeyReleasedEvent keyRelease(1); - std::cout << keyEvent.GetEventType() << std::endl; - std::cout << keyRelease.GetEventType() << std::endl; - std::cin; - return 0; + REGISTER_EVENT_TYPE(PlayerDamagedEvent); + + int getDamage() const { return damage; } + int getPlayerID() const { return playerID; } + +private: + int damage; + int playerID; +}; +void onPlayerDamaged(const PlayerDamagedEvent& e) { + std::cout << "Player " << e.getPlayerID() << " took " << e.getDamage() << " damage." << std::endl; +} + +void onKeyPressed(const KeyPressedEvent& e) +{ + const int keyCode = e.getKeyCode(); + fprintf(stderr,"KeyCode %d\n",keyCode); +} +int main(int argc, char* args[]) { + LoopManager gameLoop; + // Create an event handler for KeyPressedEvent + // EventHandler callback = [](const KeyPressedEvent& e) { + // onKeyPressed(e); + // }; + // custom event class poc + EventHandler playerDamagedHandler = onPlayerDamaged; + subscribe(playerDamagedHandler); + + triggerEvent(PlayerDamagedEvent(50, 1)); + //EventHandler callback = onKeyPressed; + //subscribe(callback,false); + std::unique_ptr anotherKeyPressEvent = std::make_unique(65); + queueEvent(std::move(anotherKeyPressEvent)); + triggerEvent(KeyPressedEvent(42)); + EventManager::getInstance().dispatchEvents(); + gameLoop.setup(); + gameLoop.loop(); + return 0; } diff --git a/mwe/events/src/timer.cpp b/mwe/events/src/timer.cpp new file mode 100644 index 0000000..f4fee23 --- /dev/null +++ b/mwe/events/src/timer.cpp @@ -0,0 +1,54 @@ +#include "timer.h" + +LoopTimer::LoopTimer() {} +LoopTimer & LoopTimer::getInstance() { + static LoopTimer instance; + return instance; +} + +void LoopTimer::start() { + lastFrameTime = SDL_GetTicks64(); + elapsedTime = 0; + elapsedFixedTime = 0; + deltaTime = 0; +} + +// Update the timer, calculate deltaTime +void LoopTimer::update() { + uint64_t currentFrameTime = SDL_GetTicks64(); + deltaTime + = (currentFrameTime - lastFrameTime) / 1000.0; + + if (deltaTime > maximumDeltaTime) { + deltaTime = maximumDeltaTime; + } + + elapsedTime += deltaTime; + lastFrameTime = currentFrameTime; +} + +double LoopTimer::getDeltaTime() const { return deltaTime; } +int LoopTimer::getCurrentTime() const { return SDL_GetTicks(); } + +void LoopTimer::advanceFixedUpdate() { elapsedFixedTime += fixedDeltaTime; } + +double LoopTimer::getFixedDeltaTime() const { return fixedDeltaTime; } + +void LoopTimer::setFPS(int FPS) { + this->FPS = FPS; + frameTargetTime = 1.0 / FPS; +} + +int LoopTimer::getFPS() const { return FPS; } + +void LoopTimer::enforceFrameRate() { + uint64_t currentFrameTime = SDL_GetTicks64(); + double frameDuration = (currentFrameTime - lastFrameTime) / 1000.0; + + if (frameDuration < frameTargetTime) { + uint32_t delayTime + = (uint32_t) ((frameTargetTime - frameDuration) * 1000.0); + SDL_Delay(delayTime); + } +} +double LoopTimer::getLag() const { return elapsedTime - elapsedFixedTime; } diff --git a/mwe/events/src/window.cpp b/mwe/events/src/window.cpp index 61a4105..9cafd57 100644 --- a/mwe/events/src/window.cpp +++ b/mwe/events/src/window.cpp @@ -1,8 +1,5 @@ #include "window.h" WindowManager::WindowManager() { - if (!initWindow()) { - printf("Failed to initialize!\n"); - } } WindowManager::~WindowManager() { destroyWindow(); } SDL_Renderer * WindowManager::getRenderer() { return renderer; } diff --git a/mwe/gameloop/include/loopManager.h b/mwe/gameloop/include/loopManager.h index e202423..dcbfedc 100644 --- a/mwe/gameloop/include/loopManager.h +++ b/mwe/gameloop/include/loopManager.h @@ -2,6 +2,7 @@ #include "gameObject.h" #include "window.h" #include +#include "event.h" class LoopManager { public: LoopManager(); -- cgit v1.2.3 From e7377daf2fe3b759fbbf7e57f88c412c3b1cf011 Mon Sep 17 00:00:00 2001 From: Loek Le Blansch Date: Thu, 24 Oct 2024 10:56:19 +0200 Subject: `make format` --- mwe/events/include/event.h | 82 ++++++------ mwe/events/include/eventHandler.h | 50 ++++---- mwe/events/include/eventManager.h | 81 ++++++------ mwe/events/include/keyCodes.h | 248 ++++++++++++++++++------------------ mwe/events/include/loopManager.h | 5 +- mwe/events/src/event.cpp | 48 +++---- mwe/events/src/eventHandler.cpp | 5 +- mwe/events/src/eventManager.cpp | 231 +++++++++++++++++++-------------- mwe/events/src/keyCodes.cpp | 247 ++++++++++++++++++----------------- mwe/events/src/loopManager.cpp | 45 +++---- mwe/events/src/main.cpp | 49 +++---- mwe/events/src/timer.cpp | 3 +- mwe/events/src/window.cpp | 3 +- mwe/gameloop/include/eventManager.h | 4 +- mwe/gameloop/include/loopManager.h | 2 +- src/crepe/api/AssetManager.h | 4 +- src/crepe/api/AssetManager.hpp | 3 +- src/crepe/api/Color.h | 1 + src/crepe/api/Config.h | 4 +- src/crepe/api/Transform.h | 1 + src/crepe/util/color.cpp | 67 +++++++--- src/crepe/util/color.h | 2 +- src/crepe/util/log.cpp | 18 ++- src/crepe/util/log.h | 13 +- src/example/log.cpp | 3 +- src/example/script.cpp | 2 +- src/makefile | 4 +- 27 files changed, 653 insertions(+), 572 deletions(-) (limited to 'mwe/events/src') diff --git a/mwe/events/include/event.h b/mwe/events/include/event.h index 802140c..5eef32f 100644 --- a/mwe/events/include/event.h +++ b/mwe/events/include/event.h @@ -1,87 +1,91 @@ #pragma once +#include "keyCodes.h" #include #include #include #include #include -#include "keyCodes.h" class UUIDGenerator { public: - static std::uint32_t getUniqueID() { - static std::uint32_t id = 0; - return ++id; - } + static std::uint32_t getUniqueID() { + static std::uint32_t id = 0; + return ++id; + } }; #define REGISTER_EVENT_TYPE(ClassName) \ +\ public: \ - static std::uint32_t getStaticEventType() { \ - static std::uint32_t typeID = UUIDGenerator::getUniqueID(); \ - return typeID; \ - } \ - virtual std::uint32_t getEventType() const override { \ - return getStaticEventType(); \ - } + static std::uint32_t getStaticEventType() { \ + static std::uint32_t typeID = UUIDGenerator::getUniqueID(); \ + return typeID; \ + } \ + virtual std::uint32_t getEventType() const override { \ + return getStaticEventType(); \ + } class Event { public: - Event(std::string eventType); - virtual ~Event() = default; - virtual std::uint32_t getEventType() const = 0; - virtual std::string toString() const; - void addArgument(const std::string& key, const std::variant& value); + Event(std::string eventType); + virtual ~Event() = default; + virtual std::uint32_t getEventType() const = 0; + virtual std::string toString() const; + void addArgument(const std::string & key, + const std::variant & value); - std::variant getArgument(const std::string& key) const; + std::variant + getArgument(const std::string & key) const; - std::string getType() const; - bool getHandled() const; - void markHandled(); + std::string getType() const; + bool getHandled() const; + void markHandled(); private: - std::unordered_map> eventData; - bool isHandled = false; + std::unordered_map> + eventData; + bool isHandled = false; }; // KeyPressedEvent class class KeyPressedEvent : public Event { public: - KeyPressedEvent(int keyCode); + KeyPressedEvent(int keyCode); - REGISTER_EVENT_TYPE("KeyPressedEvent"); + REGISTER_EVENT_TYPE("KeyPressedEvent"); - Keycode getKeyCode() const; - int getRepeatCount() const; + Keycode getKeyCode() const; + int getRepeatCount() const; private: - Keycode keycode; + Keycode keycode; public: - Keycode key = 0; - int repeatCount = 0; + Keycode key = 0; + int repeatCount = 0; }; // KeyReleasedEvent class class KeyReleasedEvent : public Event { public: - KeyReleasedEvent(int keyCode); + KeyReleasedEvent(int keyCode); - REGISTER_EVENT_TYPE(KeyReleasedEvent); + REGISTER_EVENT_TYPE(KeyReleasedEvent); - Keycode getKeyCode() const; + Keycode getKeyCode() const; private: - Keycode key = 0; + Keycode key = 0; }; // MousePressedEvent class class MousePressedEvent : public Event { public: - MousePressedEvent(int mouseX, int mouseY); + MousePressedEvent(int mouseX, int mouseY); - REGISTER_EVENT_TYPE(MousePressedEvent) + REGISTER_EVENT_TYPE(MousePressedEvent) - std::pair getMousePosition() const; + std::pair getMousePosition() const; private: - int mouseX = 0; - int mouseY = 0; + int mouseX = 0; + int mouseY = 0; }; diff --git a/mwe/events/include/eventHandler.h b/mwe/events/include/eventHandler.h index e5b99d6..7414801 100644 --- a/mwe/events/include/eventHandler.h +++ b/mwe/events/include/eventHandler.h @@ -4,45 +4,43 @@ #include #include -template -using EventHandler = std::function; +template +using EventHandler = std::function; class IEventHandlerWrapper { public: - virtual ~IEventHandlerWrapper() = default; + virtual ~IEventHandlerWrapper() = default; - void exec(const Event& e); + void exec(const Event & e); - virtual std::string getType() const = 0; - virtual bool isDestroyOnSuccess() const = 0; + virtual std::string getType() const = 0; + virtual bool isDestroyOnSuccess() const = 0; private: - virtual void call(const Event& e) = 0; + virtual void call(const Event & e) = 0; }; -template +template class EventHandlerWrapper : public IEventHandlerWrapper { public: - explicit EventHandlerWrapper(const EventHandler& handler, const bool destroyOnSuccess = false) - : m_handler(handler) - , m_handlerType(m_handler.target_type().name()) - , m_destroyOnSuccess(destroyOnSuccess) - { + explicit EventHandlerWrapper(const EventHandler & handler, + const bool destroyOnSuccess = false) + : m_handler(handler), m_handlerType(m_handler.target_type().name()), + m_destroyOnSuccess(destroyOnSuccess) { // std::cout << m_handlerType << std::endl; } private: - void call(const Event& e) override - { - if (e.getEventType() == EventType::getStaticEventType()) { - m_handler(static_cast(e)); - } - } - - std::string getType() const override { return m_handlerType; } - bool isDestroyOnSuccess() const { return m_destroyOnSuccess; } - - EventHandler m_handler; - const std::string m_handlerType; - bool m_destroyOnSuccess { false }; + void call(const Event & e) override { + if (e.getEventType() == EventType::getStaticEventType()) { + m_handler(static_cast(e)); + } + } + + std::string getType() const override { return m_handlerType; } + bool isDestroyOnSuccess() const { return m_destroyOnSuccess; } + + EventHandler m_handler; + const std::string m_handlerType; + bool m_destroyOnSuccess{false}; }; diff --git a/mwe/events/include/eventManager.h b/mwe/events/include/eventManager.h index 709796a..af41b82 100644 --- a/mwe/events/include/eventManager.h +++ b/mwe/events/include/eventManager.h @@ -1,57 +1,66 @@ #pragma once -#include -#include #include "event.h" -#include "keyCodes.h" #include "eventHandler.h" +#include "keyCodes.h" +#include +#include #include // using EventType = std::uint32_t; // using EventId = std::uint64_t; class EventManager { public: - EventManager(const EventManager&) = delete; - const EventManager& operator=(const EventManager&) = delete; - static EventManager& getInstance() { - static EventManager instance; - return instance; - } + EventManager(const EventManager &) = delete; + const EventManager & operator=(const EventManager &) = delete; + static EventManager & getInstance() { + static EventManager instance; + return instance; + } - void shutdown(); - void subscribe(int eventType, std::unique_ptr&& handler, int eventId); - void unsubscribe(int eventType, const std::string& handlerName, int eventId); - void triggerEvent(const Event& event_, int eventId); - void queueEvent(std::unique_ptr&& event_, int eventId); - void dispatchEvents(); + void shutdown(); + void subscribe(int eventType, + std::unique_ptr && handler, + int eventId); + void unsubscribe(int eventType, const std::string & handlerName, + int eventId); + void triggerEvent(const Event & event_, int eventId); + void queueEvent(std::unique_ptr && event_, int eventId); + void dispatchEvents(); private: - EventManager() = default; - std::vector, int>> m_eventsQueue; - std::unordered_map>> m_subscribers; - std::unordered_map>>> m_subscribersByEventId; + EventManager() = default; + std::vector, int>> m_eventsQueue; + std::unordered_map>> + m_subscribers; + std::unordered_map< + int, std::unordered_map< + int, std::vector>>> + m_subscribersByEventId; }; - -template -inline void subscribe(const EventHandler& callback, int eventId = 0, const bool unsubscribeOnSuccess = false) -{ - std::unique_ptr handler = std::make_unique>(callback, unsubscribeOnSuccess); - EventManager::getInstance().subscribe(EventType::getStaticEventType(), std::move(handler), eventId); +template +inline void subscribe(const EventHandler & callback, int eventId = 0, + const bool unsubscribeOnSuccess = false) { + std::unique_ptr handler + = std::make_unique>( + callback, unsubscribeOnSuccess); + EventManager::getInstance().subscribe(EventType::getStaticEventType(), + std::move(handler), eventId); } -template -inline void unsubscribe(const EventHandler& callback, int eventId = 0) -{ - const std::string handlerName = callback.target_type().name(); - EventManager::getInstance().unsubscribe(EventType::getStaticEventType(), handlerName, eventId); +template +inline void unsubscribe(const EventHandler & callback, + int eventId = 0) { + const std::string handlerName = callback.target_type().name(); + EventManager::getInstance().unsubscribe(EventType::getStaticEventType(), + handlerName, eventId); } -inline void triggerEvent(const Event& triggeredEvent, int eventId = 0) -{ - EventManager::getInstance().triggerEvent(triggeredEvent, eventId); +inline void triggerEvent(const Event & triggeredEvent, int eventId = 0) { + EventManager::getInstance().triggerEvent(triggeredEvent, eventId); } -inline void queueEvent(std::unique_ptr&& queuedEvent, int eventId = 0) -{ - EventManager::getInstance().queueEvent(std::forward>(queuedEvent), eventId); +inline void queueEvent(std::unique_ptr && queuedEvent, int eventId = 0) { + EventManager::getInstance().queueEvent( + std::forward>(queuedEvent), eventId); } diff --git a/mwe/events/include/keyCodes.h b/mwe/events/include/keyCodes.h index c3a7826..0879efc 100644 --- a/mwe/events/include/keyCodes.h +++ b/mwe/events/include/keyCodes.h @@ -1,140 +1,140 @@ #pragma once +#include #include #include -#include using Keycode = uint16_t; enum : Keycode { - // From glfw3.h - Space = 32, - Apostrophe = 39, /* ' */ - Comma = 44, /* , */ - Minus = 45, /* - */ - Period = 46, /* . */ - Slash = 47, /* / */ + // From glfw3.h + Space = 32, + Apostrophe = 39, /* ' */ + Comma = 44, /* , */ + Minus = 45, /* - */ + Period = 46, /* . */ + Slash = 47, /* / */ - D0 = 48, /* 0 */ - D1 = 49, /* 1 */ - D2 = 50, /* 2 */ - D3 = 51, /* 3 */ - D4 = 52, /* 4 */ - D5 = 53, /* 5 */ - D6 = 54, /* 6 */ - D7 = 55, /* 7 */ - D8 = 56, /* 8 */ - D9 = 57, /* 9 */ + D0 = 48, /* 0 */ + D1 = 49, /* 1 */ + D2 = 50, /* 2 */ + D3 = 51, /* 3 */ + D4 = 52, /* 4 */ + D5 = 53, /* 5 */ + D6 = 54, /* 6 */ + D7 = 55, /* 7 */ + D8 = 56, /* 8 */ + D9 = 57, /* 9 */ - Semicolon = 59, /* ; */ - Equal = 61, /* = */ + Semicolon = 59, /* ; */ + Equal = 61, /* = */ - A = 65, - B = 66, - C = 67, - D = 68, - E = 69, - F = 70, - G = 71, - H = 72, - I = 73, - J = 74, - K = 75, - L = 76, - M = 77, - N = 78, - O = 79, - P = 80, - Q = 81, - R = 82, - S = 83, - T = 84, - U = 85, - V = 86, - W = 87, - X = 88, - Y = 89, - Z = 90, + A = 65, + B = 66, + C = 67, + D = 68, + E = 69, + F = 70, + G = 71, + H = 72, + I = 73, + J = 74, + K = 75, + L = 76, + M = 77, + N = 78, + O = 79, + P = 80, + Q = 81, + R = 82, + S = 83, + T = 84, + U = 85, + V = 86, + W = 87, + X = 88, + Y = 89, + Z = 90, - LeftBracket = 91, /* [ */ - Backslash = 92, /* \ */ - RightBracket = 93, /* ] */ - GraveAccent = 96, /* ` */ + LeftBracket = 91, /* [ */ + Backslash = 92, /* \ */ + RightBracket = 93, /* ] */ + GraveAccent = 96, /* ` */ - World1 = 161, /* non-US #1 */ - World2 = 162, /* non-US #2 */ + World1 = 161, /* non-US #1 */ + World2 = 162, /* non-US #2 */ - /* Function keys */ - Escape = 256, - Enter = 257, - Tab = 258, - Backspace = 259, - Insert = 260, - Delete = 261, - Right = 262, - Left = 263, - Down = 264, - Up = 265, - PageUp = 266, - PageDown = 267, - Home = 268, - End = 269, - CapsLock = 280, - ScrollLock = 281, - NumLock = 282, - PrintScreen = 283, - Pause = 284, - F1 = 290, - F2 = 291, - F3 = 292, - F4 = 293, - F5 = 294, - F6 = 295, - F7 = 296, - F8 = 297, - F9 = 298, - F10 = 299, - F11 = 300, - F12 = 301, - F13 = 302, - F14 = 303, - F15 = 304, - F16 = 305, - F17 = 306, - F18 = 307, - F19 = 308, - F20 = 309, - F21 = 310, - F22 = 311, - F23 = 312, - F24 = 313, - F25 = 314, + /* Function keys */ + Escape = 256, + Enter = 257, + Tab = 258, + Backspace = 259, + Insert = 260, + Delete = 261, + Right = 262, + Left = 263, + Down = 264, + Up = 265, + PageUp = 266, + PageDown = 267, + Home = 268, + End = 269, + CapsLock = 280, + ScrollLock = 281, + NumLock = 282, + PrintScreen = 283, + Pause = 284, + F1 = 290, + F2 = 291, + F3 = 292, + F4 = 293, + F5 = 294, + F6 = 295, + F7 = 296, + F8 = 297, + F9 = 298, + F10 = 299, + F11 = 300, + F12 = 301, + F13 = 302, + F14 = 303, + F15 = 304, + F16 = 305, + F17 = 306, + F18 = 307, + F19 = 308, + F20 = 309, + F21 = 310, + F22 = 311, + F23 = 312, + F24 = 313, + F25 = 314, - /* Keypad */ - KP0 = 320, - KP1 = 321, - KP2 = 322, - KP3 = 323, - KP4 = 324, - KP5 = 325, - KP6 = 326, - KP7 = 327, - KP8 = 328, - KP9 = 329, - KPDecimal = 330, - KPDivide = 331, - KPMultiply = 332, - KPSubtract = 333, - KPAdd = 334, - KPEnter = 335, - KPEqual = 336, + /* Keypad */ + KP0 = 320, + KP1 = 321, + KP2 = 322, + KP3 = 323, + KP4 = 324, + KP5 = 325, + KP6 = 326, + KP7 = 327, + KP8 = 328, + KP9 = 329, + KPDecimal = 330, + KPDivide = 331, + KPMultiply = 332, + KPSubtract = 333, + KPAdd = 334, + KPEnter = 335, + KPEqual = 336, - LeftShift = 340, - LeftControl = 341, - LeftAlt = 342, - LeftSuper = 343, - RightShift = 344, - RightControl = 345, - RightAlt = 346, - RightSuper = 347, - Menu = 348 + LeftShift = 340, + LeftControl = 341, + LeftAlt = 342, + LeftSuper = 343, + RightShift = 344, + RightControl = 345, + RightAlt = 346, + RightSuper = 347, + Menu = 348 }; // Define the mapping extern const std::unordered_map sdlToCustom; diff --git a/mwe/events/include/loopManager.h b/mwe/events/include/loopManager.h index 5c519d9..baffb94 100644 --- a/mwe/events/include/loopManager.h +++ b/mwe/events/include/loopManager.h @@ -1,17 +1,18 @@ #pragma once +#include "timer.h" #include "window.h" #include -#include "timer.h" //#include "combinedEvent.h" +#include "eventHandler.h" #include "eventManager.h" #include "loopManager.h" -#include "eventHandler.h" class LoopManager { public: LoopManager(); void setup(); void loop(); void setRunning(bool running); + private: void processInput(); void update(); diff --git a/mwe/events/src/event.cpp b/mwe/events/src/event.cpp index fecae76..c0ae9ed 100644 --- a/mwe/events/src/event.cpp +++ b/mwe/events/src/event.cpp @@ -1,56 +1,44 @@ #include "event.h" #include "keyCodes.h" // Event class methods -Event::Event(std::string eventType) { - eventData["eventType"] = eventType; -} +Event::Event(std::string eventType) { eventData["eventType"] = eventType; } -void Event::addArgument(const std::string& key, const std::variant& value) { - eventData[key] = value; +void Event::addArgument(const std::string & key, + const std::variant & value) { + eventData[key] = value; } -std::variant Event::getArgument(const std::string& key) const { - return eventData.at(key); +std::variant +Event::getArgument(const std::string & key) const { + return eventData.at(key); } std::string Event::getType() const { - return std::get(eventData.at("eventType")); -} -std::string Event::toString() const { - return std::to_string(getEventType()); -} -bool Event::getHandled() const { - return isHandled; + return std::get(eventData.at("eventType")); } +std::string Event::toString() const { return std::to_string(getEventType()); } +bool Event::getHandled() const { return isHandled; } -void Event::markHandled() { - isHandled = true; -} +void Event::markHandled() { isHandled = true; } // KeyPressedEvent class methods KeyPressedEvent::KeyPressedEvent(int keycode) - : Event("KeyPressedEvent"), key(keycode), repeatCount(0) {} + : Event("KeyPressedEvent"), key(keycode), repeatCount(0) {} -Keycode KeyPressedEvent::getKeyCode() const { - return key; -} +Keycode KeyPressedEvent::getKeyCode() const { return key; } -int KeyPressedEvent::getRepeatCount() const { - return repeatCount; -} +int KeyPressedEvent::getRepeatCount() const { return repeatCount; } // KeyReleasedEvent class methods KeyReleasedEvent::KeyReleasedEvent(int keycode) - : Event("KeyReleasedEvent"), key(keycode) {} + : Event("KeyReleasedEvent"), key(keycode) {} -Keycode KeyReleasedEvent::getKeyCode() const { - return key; -} +Keycode KeyReleasedEvent::getKeyCode() const { return key; } // MousePressedEvent class methods MousePressedEvent::MousePressedEvent(int mouseX, int mouseY) - : Event("MousePressedEvent"), mouseX(mouseX), mouseY(mouseY) {} + : Event("MousePressedEvent"), mouseX(mouseX), mouseY(mouseY) {} std::pair MousePressedEvent::getMousePosition() const { - return {mouseX, mouseY}; + return {mouseX, mouseY}; } diff --git a/mwe/events/src/eventHandler.cpp b/mwe/events/src/eventHandler.cpp index 7040d8d..7fb8d70 100644 --- a/mwe/events/src/eventHandler.cpp +++ b/mwe/events/src/eventHandler.cpp @@ -1,5 +1,2 @@ #include "eventHandler.h" -void IEventHandlerWrapper::exec(const Event& e) - { - call(e); - } +void IEventHandlerWrapper::exec(const Event & e) { call(e); } diff --git a/mwe/events/src/eventManager.cpp b/mwe/events/src/eventManager.cpp index ce8e940..2aef89d 100644 --- a/mwe/events/src/eventManager.cpp +++ b/mwe/events/src/eventManager.cpp @@ -1,109 +1,152 @@ #include "eventManager.h" -void EventManager::shutdown() -{ - m_subscribers.clear(); -} +void EventManager::shutdown() { m_subscribers.clear(); } -void EventManager::subscribe(int eventType, std::unique_ptr&& handler, int eventId) -{ - if (eventId) { - std::unordered_map>>>::iterator subscribers = m_subscribersByEventId.find(eventType); +void EventManager::subscribe(int eventType, + std::unique_ptr && handler, + int eventId) { + if (eventId) { + std::unordered_map< + int, std::unordered_map< + int, std::vector>>>:: + iterator subscribers + = m_subscribersByEventId.find(eventType); - if (subscribers != m_subscribersByEventId.end()) { - std::unordered_map>>& handlersMap = subscribers->second; - std::unordered_map>>::iterator handlers = handlersMap.find(eventId); - if (handlers != handlersMap.end()) { - handlers->second.emplace_back(std::move(handler)); - return; - } - } - m_subscribersByEventId[eventType][eventId].emplace_back(std::move(handler)); + if (subscribers != m_subscribersByEventId.end()) { + std::unordered_map< + int, std::vector>> & + handlersMap + = subscribers->second; + std::unordered_map< + int, + std::vector>>::iterator + handlers + = handlersMap.find(eventId); + if (handlers != handlersMap.end()) { + handlers->second.emplace_back(std::move(handler)); + return; + } + } + m_subscribersByEventId[eventType][eventId].emplace_back( + std::move(handler)); - } else { - std::unordered_map>>::iterator subscribers = m_subscribers.find(eventType); - if (subscribers != m_subscribers.end()) { - std::vector>& handlers = subscribers->second; - for (std::unique_ptr& it : handlers) { - if (it->getType() == handler->getType()) { - // log for double register - return; - } - } - handlers.emplace_back(std::move(handler)); - } else { - m_subscribers[eventType].emplace_back(std::move(handler)); - } - } + } else { + std::unordered_map< + int, std::vector>>::iterator + subscribers + = m_subscribers.find(eventType); + if (subscribers != m_subscribers.end()) { + std::vector> & handlers + = subscribers->second; + for (std::unique_ptr & it : handlers) { + if (it->getType() == handler->getType()) { + // log for double register + return; + } + } + handlers.emplace_back(std::move(handler)); + } else { + m_subscribers[eventType].emplace_back(std::move(handler)); + } + } } -void EventManager::unsubscribe(int eventType, const std::string& handlerName, int eventId) -{ - if (eventId) { - std::unordered_map>>>::iterator subscribers = m_subscribersByEventId.find(eventType); - if (subscribers != m_subscribersByEventId.end()) { - std::unordered_map>>& handlersMap = subscribers->second; - std::unordered_map>>::iterator handlers = handlersMap.find(eventId); - if (handlers != handlersMap.end()) { - std::vector>& callbacks = handlers->second; - for (std::vector>::iterator it = callbacks.begin(); it != callbacks.end(); ++it) { - if (it->get()->getType() == handlerName) { - it = callbacks.erase(it); - return; - } - } - } - } - } else { - std::unordered_map>>::iterator handlersIt = m_subscribers.find(eventType); - if (handlersIt != m_subscribers.end()) { - std::vector>& handlers = handlersIt->second; - for (std::vector>::iterator it = handlers.begin(); it != handlers.end(); ++it) { - if (it->get()->getType() == handlerName) { - it = handlers.erase(it); - return; - } - } - } - } +void EventManager::unsubscribe(int eventType, const std::string & handlerName, + int eventId) { + if (eventId) { + std::unordered_map< + int, std::unordered_map< + int, std::vector>>>:: + iterator subscribers + = m_subscribersByEventId.find(eventType); + if (subscribers != m_subscribersByEventId.end()) { + std::unordered_map< + int, std::vector>> & + handlersMap + = subscribers->second; + std::unordered_map< + int, + std::vector>>::iterator + handlers + = handlersMap.find(eventId); + if (handlers != handlersMap.end()) { + std::vector> & callbacks + = handlers->second; + for (std::vector< + std::unique_ptr>::iterator it + = callbacks.begin(); + it != callbacks.end(); ++it) { + if (it->get()->getType() == handlerName) { + it = callbacks.erase(it); + return; + } + } + } + } + } else { + std::unordered_map< + int, std::vector>>::iterator + handlersIt + = m_subscribers.find(eventType); + if (handlersIt != m_subscribers.end()) { + std::vector> & handlers + = handlersIt->second; + for (std::vector>::iterator it + = handlers.begin(); + it != handlers.end(); ++it) { + if (it->get()->getType() == handlerName) { + it = handlers.erase(it); + return; + } + } + } + } } -void EventManager::triggerEvent(const Event& event_, int eventId) -{ - std::vector>& handlers = m_subscribers[event_.getEventType()]; - for (std::unique_ptr& handler : handlers) { - handler->exec(event_); - } +void EventManager::triggerEvent(const Event & event_, int eventId) { + std::vector> & handlers + = m_subscribers[event_.getEventType()]; + for (std::unique_ptr & handler : handlers) { + handler->exec(event_); + } - std::unordered_map>>& handlersMap = m_subscribersByEventId[event_.getEventType()]; - std::unordered_map>>::iterator handlersIt = handlersMap.find(eventId); - if (handlersIt != handlersMap.end()) { - std::vector>& callbacks = handlersIt->second; - for (std::vector>::iterator it = callbacks.begin(); it != callbacks.end();) { - std::unique_ptr& handler = *it; - handler->exec(event_); - if (handler->isDestroyOnSuccess()) { - it = callbacks.erase(it); - } else { - ++it; - } - } - } + std::unordered_map< + int, std::vector>> & handlersMap + = m_subscribersByEventId[event_.getEventType()]; + std::unordered_map< + int, std::vector>>::iterator + handlersIt + = handlersMap.find(eventId); + if (handlersIt != handlersMap.end()) { + std::vector> & callbacks + = handlersIt->second; + for (std::vector>::iterator it + = callbacks.begin(); + it != callbacks.end();) { + std::unique_ptr & handler = *it; + handler->exec(event_); + if (handler->isDestroyOnSuccess()) { + it = callbacks.erase(it); + } else { + ++it; + } + } + } } -void EventManager::queueEvent(std::unique_ptr&& event_, int eventId) -{ - m_eventsQueue.emplace_back(std::move(event_), eventId); +void EventManager::queueEvent(std::unique_ptr && event_, int eventId) { + m_eventsQueue.emplace_back(std::move(event_), eventId); } -void EventManager::dispatchEvents() -{ - for (std::vector, int>>::iterator eventIt = m_eventsQueue.begin(); eventIt != m_eventsQueue.end();) { - if (!eventIt->first.get()->getHandled()) { - triggerEvent(*eventIt->first.get(), eventIt->second); - eventIt = m_eventsQueue.erase(eventIt); - } else { - ++eventIt; - } - } +void EventManager::dispatchEvents() { + for (std::vector, int>>::iterator eventIt + = m_eventsQueue.begin(); + eventIt != m_eventsQueue.end();) { + if (!eventIt->first.get()->getHandled()) { + triggerEvent(*eventIt->first.get(), eventIt->second); + eventIt = m_eventsQueue.erase(eventIt); + } else { + ++eventIt; + } + } } diff --git a/mwe/events/src/keyCodes.cpp b/mwe/events/src/keyCodes.cpp index 6f35d11..5f3aa96 100644 --- a/mwe/events/src/keyCodes.cpp +++ b/mwe/events/src/keyCodes.cpp @@ -1,140 +1,139 @@ #include "keyCodes.h" -const std::unordered_map sdlToCustom = { - { SDLK_SPACE, Space }, - { SDLK_QUOTE, Apostrophe }, - { SDLK_COMMA, Comma }, - { SDLK_MINUS, Minus }, - { SDLK_PERIOD, Period }, - { SDLK_SLASH, Slash }, +const std::unordered_map sdlToCustom + = {{SDLK_SPACE, Space}, + {SDLK_QUOTE, Apostrophe}, + {SDLK_COMMA, Comma}, + {SDLK_MINUS, Minus}, + {SDLK_PERIOD, Period}, + {SDLK_SLASH, Slash}, - { SDLK_0, D0 }, - { SDLK_1, D1 }, - { SDLK_2, D2 }, - { SDLK_3, D3 }, - { SDLK_4, D4 }, - { SDLK_5, D5 }, - { SDLK_6, D6 }, - { SDLK_7, D7 }, - { SDLK_8, D8 }, - { SDLK_9, D9 }, + {SDLK_0, D0}, + {SDLK_1, D1}, + {SDLK_2, D2}, + {SDLK_3, D3}, + {SDLK_4, D4}, + {SDLK_5, D5}, + {SDLK_6, D6}, + {SDLK_7, D7}, + {SDLK_8, D8}, + {SDLK_9, D9}, - { SDLK_SEMICOLON, Semicolon }, - { SDLK_EQUALS, Equal }, + {SDLK_SEMICOLON, Semicolon}, + {SDLK_EQUALS, Equal}, - { SDLK_a, A }, - { SDLK_b, B }, - { SDLK_c, C }, - { SDLK_d, D }, - { SDLK_e, E }, - { SDLK_f, F }, - { SDLK_g, G }, - { SDLK_h, H }, - { SDLK_i, I }, - { SDLK_j, J }, - { SDLK_k, K }, - { SDLK_l, L }, - { SDLK_m, M }, - { SDLK_n, N }, - { SDLK_o, O }, - { SDLK_p, P }, - { SDLK_q, Q }, - { SDLK_r, R }, - { SDLK_s, S }, - { SDLK_t, T }, - { SDLK_u, U }, - { SDLK_v, V }, - { SDLK_w, W }, - { SDLK_x, X }, - { SDLK_y, Y }, - { SDLK_z, Z }, + {SDLK_a, A}, + {SDLK_b, B}, + {SDLK_c, C}, + {SDLK_d, D}, + {SDLK_e, E}, + {SDLK_f, F}, + {SDLK_g, G}, + {SDLK_h, H}, + {SDLK_i, I}, + {SDLK_j, J}, + {SDLK_k, K}, + {SDLK_l, L}, + {SDLK_m, M}, + {SDLK_n, N}, + {SDLK_o, O}, + {SDLK_p, P}, + {SDLK_q, Q}, + {SDLK_r, R}, + {SDLK_s, S}, + {SDLK_t, T}, + {SDLK_u, U}, + {SDLK_v, V}, + {SDLK_w, W}, + {SDLK_x, X}, + {SDLK_y, Y}, + {SDLK_z, Z}, - { SDLK_LEFTBRACKET, LeftBracket }, - { SDLK_BACKSLASH, Backslash }, - { SDLK_RIGHTBRACKET, RightBracket }, - { SDLK_BACKQUOTE, GraveAccent }, + {SDLK_LEFTBRACKET, LeftBracket}, + {SDLK_BACKSLASH, Backslash}, + {SDLK_RIGHTBRACKET, RightBracket}, + {SDLK_BACKQUOTE, GraveAccent}, - { SDLK_ESCAPE, Escape }, - { SDLK_RETURN, Enter }, - { SDLK_TAB, Tab }, - { SDLK_BACKSPACE, Backspace }, - { SDLK_INSERT, Insert }, - { SDLK_DELETE, Delete }, - { SDLK_RIGHT, Right }, - { SDLK_LEFT, Left }, - { SDLK_DOWN, Down }, - { SDLK_UP, Up }, - { SDLK_PAGEUP, PageUp }, - { SDLK_PAGEDOWN, PageDown }, - { SDLK_HOME, Home }, - { SDLK_END, End }, + {SDLK_ESCAPE, Escape}, + {SDLK_RETURN, Enter}, + {SDLK_TAB, Tab}, + {SDLK_BACKSPACE, Backspace}, + {SDLK_INSERT, Insert}, + {SDLK_DELETE, Delete}, + {SDLK_RIGHT, Right}, + {SDLK_LEFT, Left}, + {SDLK_DOWN, Down}, + {SDLK_UP, Up}, + {SDLK_PAGEUP, PageUp}, + {SDLK_PAGEDOWN, PageDown}, + {SDLK_HOME, Home}, + {SDLK_END, End}, - { SDLK_CAPSLOCK, CapsLock }, - { SDLK_SCROLLLOCK, ScrollLock }, - { SDLK_NUMLOCKCLEAR, NumLock }, - { SDLK_PRINTSCREEN, PrintScreen }, - { SDLK_PAUSE, Pause }, + {SDLK_CAPSLOCK, CapsLock}, + {SDLK_SCROLLLOCK, ScrollLock}, + {SDLK_NUMLOCKCLEAR, NumLock}, + {SDLK_PRINTSCREEN, PrintScreen}, + {SDLK_PAUSE, Pause}, - { SDLK_F1, F1 }, - { SDLK_F2, F2 }, - { SDLK_F3, F3 }, - { SDLK_F4, F4 }, - { SDLK_F5, F5 }, - { SDLK_F6, F6 }, - { SDLK_F7, F7 }, - { SDLK_F8, F8 }, - { SDLK_F9, F9 }, - { SDLK_F10, F10 }, - { SDLK_F11, F11 }, - { SDLK_F12, F12 }, - { SDLK_F13, F13 }, - { SDLK_F14, F14 }, - { SDLK_F15, F15 }, - { SDLK_F16, F16 }, - { SDLK_F17, F17 }, - { SDLK_F18, F18 }, - { SDLK_F19, F19 }, - { SDLK_F20, F20 }, - { SDLK_F21, F21 }, - { SDLK_F22, F22 }, - { SDLK_F23, F23 }, - { SDLK_F24, F24 }, + {SDLK_F1, F1}, + {SDLK_F2, F2}, + {SDLK_F3, F3}, + {SDLK_F4, F4}, + {SDLK_F5, F5}, + {SDLK_F6, F6}, + {SDLK_F7, F7}, + {SDLK_F8, F8}, + {SDLK_F9, F9}, + {SDLK_F10, F10}, + {SDLK_F11, F11}, + {SDLK_F12, F12}, + {SDLK_F13, F13}, + {SDLK_F14, F14}, + {SDLK_F15, F15}, + {SDLK_F16, F16}, + {SDLK_F17, F17}, + {SDLK_F18, F18}, + {SDLK_F19, F19}, + {SDLK_F20, F20}, + {SDLK_F21, F21}, + {SDLK_F22, F22}, + {SDLK_F23, F23}, + {SDLK_F24, F24}, - { SDLK_KP_0, KP0 }, - { SDLK_KP_1, KP1 }, - { SDLK_KP_2, KP2 }, - { SDLK_KP_3, KP3 }, - { SDLK_KP_4, KP4 }, - { SDLK_KP_5, KP5 }, - { SDLK_KP_6, KP6 }, - { SDLK_KP_7, KP7 }, - { SDLK_KP_8, KP8 }, - { SDLK_KP_9, KP9 }, + {SDLK_KP_0, KP0}, + {SDLK_KP_1, KP1}, + {SDLK_KP_2, KP2}, + {SDLK_KP_3, KP3}, + {SDLK_KP_4, KP4}, + {SDLK_KP_5, KP5}, + {SDLK_KP_6, KP6}, + {SDLK_KP_7, KP7}, + {SDLK_KP_8, KP8}, + {SDLK_KP_9, KP9}, - { SDLK_KP_DECIMAL, KPDecimal }, - { SDLK_KP_DIVIDE, KPDivide }, - { SDLK_KP_MULTIPLY, KPMultiply }, - { SDLK_KP_MINUS, KPSubtract }, - { SDLK_KP_PLUS, KPAdd }, - { SDLK_KP_ENTER, KPEnter }, - { SDLK_KP_EQUALS, KPEqual }, + {SDLK_KP_DECIMAL, KPDecimal}, + {SDLK_KP_DIVIDE, KPDivide}, + {SDLK_KP_MULTIPLY, KPMultiply}, + {SDLK_KP_MINUS, KPSubtract}, + {SDLK_KP_PLUS, KPAdd}, + {SDLK_KP_ENTER, KPEnter}, + {SDLK_KP_EQUALS, KPEqual}, - { SDLK_LSHIFT, LeftShift }, - { SDLK_LCTRL, LeftControl }, - { SDLK_LALT, LeftAlt }, - { SDLK_LGUI, LeftSuper }, + {SDLK_LSHIFT, LeftShift}, + {SDLK_LCTRL, LeftControl}, + {SDLK_LALT, LeftAlt}, + {SDLK_LGUI, LeftSuper}, - { SDLK_RSHIFT, RightShift }, - { SDLK_RCTRL, RightControl }, - { SDLK_RALT, RightAlt }, - { SDLK_RGUI, RightSuper }, + {SDLK_RSHIFT, RightShift}, + {SDLK_RCTRL, RightControl}, + {SDLK_RALT, RightAlt}, + {SDLK_RGUI, RightSuper}, - { SDLK_MENU, Menu } -}; + {SDLK_MENU, Menu}}; Keycode getCustomKey(SDL_Keycode sdlKey) { - auto it = sdlToCustom.find(sdlKey); - if (it != sdlToCustom.end()) { - return it->second; - } - return 0; + auto it = sdlToCustom.find(sdlKey); + if (it != sdlToCustom.end()) { + return it->second; + } + return 0; } diff --git a/mwe/events/src/loopManager.cpp b/mwe/events/src/loopManager.cpp index 6defda0..8ecb932 100644 --- a/mwe/events/src/loopManager.cpp +++ b/mwe/events/src/loopManager.cpp @@ -12,17 +12,15 @@ void LoopManager::processInput() { triggerEvent(KeyPressedEvent(getCustomKey(event.key.keysym.sym))); break; case SDL_MOUSEBUTTONDOWN: - int x, y; - SDL_GetMouseState(&x, &y); - triggerEvent(MousePressedEvent(x, y)); - break; + int x, y; + SDL_GetMouseState(&x, &y); + triggerEvent(MousePressedEvent(x, y)); + break; } } -void LoopManager::setRunning(bool running){ - this->gameRunning = running; -} -void LoopManager::fixedUpdate() { - //fprintf(stderr, "fixed update\n"); +void LoopManager::setRunning(bool running) { this->gameRunning = running; } +void LoopManager::fixedUpdate() { + //fprintf(stderr, "fixed update\n"); } void LoopManager::loop() { LoopTimer & timer = LoopTimer::getInstance(); @@ -45,30 +43,29 @@ void LoopManager::loop() { window.destroyWindow(); } -void onKey(const KeyPressedEvent& e) -{ - int keyCode = e.getKeyCode(); +void onKey(const KeyPressedEvent & e) { + int keyCode = e.getKeyCode(); std::cout << "keycode pressed: " << keyCode << std::endl; - } -void onMouse(const MousePressedEvent& e){ - fprintf(stderr, "mouse Position X: %d Y: %d\n", e.getMousePosition().first, e.getMousePosition().second); +void onMouse(const MousePressedEvent & e) { + fprintf(stderr, "mouse Position X: %d Y: %d\n", e.getMousePosition().first, + e.getMousePosition().second); } void LoopManager::setup() { gameRunning = window.initWindow(); LoopTimer::getInstance().start(); LoopTimer::getInstance().setFPS(50); EventHandler callback = onKey; - subscribe(callback,false); + subscribe(callback, false); EventHandler mouseCallback = onMouse; - subscribe(mouseCallback ,false); - EventHandler closeWindowCallback = [this](const KeyPressedEvent& e) { - if(e.getKeyCode() == Escape){ - this->setRunning(false); - } - }; - subscribe(closeWindowCallback,false); - + subscribe(mouseCallback, false); + EventHandler closeWindowCallback + = [this](const KeyPressedEvent & e) { + if (e.getKeyCode() == Escape) { + this->setRunning(false); + } + }; + subscribe(closeWindowCallback, false); } void LoopManager::render() { //fprintf(stderr, "**********render********** \n"); diff --git a/mwe/events/src/main.cpp b/mwe/events/src/main.cpp index 3940c60..55c562f 100644 --- a/mwe/events/src/main.cpp +++ b/mwe/events/src/main.cpp @@ -1,50 +1,51 @@ +#include "event.h" +#include "loopManager.h" #include #include #include -#include "loopManager.h" -#include "event.h" class PlayerDamagedEvent : public Event { public: - PlayerDamagedEvent(int damage, int playerID) - : Event("PlayerDamaged"), damage(damage), playerID(playerID) {} + PlayerDamagedEvent(int damage, int playerID) + : Event("PlayerDamaged"), damage(damage), playerID(playerID) {} - REGISTER_EVENT_TYPE(PlayerDamagedEvent); + REGISTER_EVENT_TYPE(PlayerDamagedEvent); - int getDamage() const { return damage; } - int getPlayerID() const { return playerID; } + int getDamage() const { return damage; } + int getPlayerID() const { return playerID; } private: - int damage; - int playerID; + int damage; + int playerID; }; -void onPlayerDamaged(const PlayerDamagedEvent& e) { - std::cout << "Player " << e.getPlayerID() << " took " << e.getDamage() << " damage." << std::endl; +void onPlayerDamaged(const PlayerDamagedEvent & e) { + std::cout << "Player " << e.getPlayerID() << " took " << e.getDamage() + << " damage." << std::endl; } -void onKeyPressed(const KeyPressedEvent& e) -{ - const int keyCode = e.getKeyCode(); - fprintf(stderr,"KeyCode %d\n",keyCode); +void onKeyPressed(const KeyPressedEvent & e) { + const int keyCode = e.getKeyCode(); + fprintf(stderr, "KeyCode %d\n", keyCode); } -int main(int argc, char* args[]) { +int main(int argc, char * args[]) { LoopManager gameLoop; // Create an event handler for KeyPressedEvent - // EventHandler callback = [](const KeyPressedEvent& e) { - // onKeyPressed(e); - // }; + // EventHandler callback = [](const KeyPressedEvent& e) { + // onKeyPressed(e); + // }; // custom event class poc EventHandler playerDamagedHandler = onPlayerDamaged; subscribe(playerDamagedHandler); triggerEvent(PlayerDamagedEvent(50, 1)); //EventHandler callback = onKeyPressed; - //subscribe(callback,false); - std::unique_ptr anotherKeyPressEvent = std::make_unique(65); - queueEvent(std::move(anotherKeyPressEvent)); - triggerEvent(KeyPressedEvent(42)); + //subscribe(callback,false); + std::unique_ptr anotherKeyPressEvent + = std::make_unique(65); + queueEvent(std::move(anotherKeyPressEvent)); + triggerEvent(KeyPressedEvent(42)); EventManager::getInstance().dispatchEvents(); gameLoop.setup(); gameLoop.loop(); - return 0; + return 0; } diff --git a/mwe/events/src/timer.cpp b/mwe/events/src/timer.cpp index f4fee23..0b89bf5 100644 --- a/mwe/events/src/timer.cpp +++ b/mwe/events/src/timer.cpp @@ -16,8 +16,7 @@ void LoopTimer::start() { // Update the timer, calculate deltaTime void LoopTimer::update() { uint64_t currentFrameTime = SDL_GetTicks64(); - deltaTime - = (currentFrameTime - lastFrameTime) / 1000.0; + deltaTime = (currentFrameTime - lastFrameTime) / 1000.0; if (deltaTime > maximumDeltaTime) { deltaTime = maximumDeltaTime; diff --git a/mwe/events/src/window.cpp b/mwe/events/src/window.cpp index 9cafd57..41eb85f 100644 --- a/mwe/events/src/window.cpp +++ b/mwe/events/src/window.cpp @@ -1,6 +1,5 @@ #include "window.h" -WindowManager::WindowManager() { -} +WindowManager::WindowManager() {} WindowManager::~WindowManager() { destroyWindow(); } SDL_Renderer * WindowManager::getRenderer() { return renderer; } diff --git a/mwe/gameloop/include/eventManager.h b/mwe/gameloop/include/eventManager.h index ba1ca32..a1b9f92 100644 --- a/mwe/gameloop/include/eventManager.h +++ b/mwe/gameloop/include/eventManager.h @@ -1,5 +1,5 @@ #pragma once class EventManager { - public: - EventManager(); +public: + EventManager(); }; diff --git a/mwe/gameloop/include/loopManager.h b/mwe/gameloop/include/loopManager.h index dcbfedc..1befb69 100644 --- a/mwe/gameloop/include/loopManager.h +++ b/mwe/gameloop/include/loopManager.h @@ -1,8 +1,8 @@ #pragma once +#include "event.h" #include "gameObject.h" #include "window.h" #include -#include "event.h" class LoopManager { public: LoopManager(); diff --git a/src/crepe/api/AssetManager.h b/src/crepe/api/AssetManager.h index a53ace5..3e72a49 100644 --- a/src/crepe/api/AssetManager.h +++ b/src/crepe/api/AssetManager.h @@ -26,10 +26,10 @@ public: public: template - std::shared_ptr cache(const std::string & file_path, bool reload = false); + std::shared_ptr cache(const std::string & file_path, + bool reload = false); }; } // namespace crepe::api #include "AssetManager.hpp" - diff --git a/src/crepe/api/AssetManager.hpp b/src/crepe/api/AssetManager.hpp index 083fd9d..468724c 100644 --- a/src/crepe/api/AssetManager.hpp +++ b/src/crepe/api/AssetManager.hpp @@ -5,7 +5,8 @@ namespace crepe::api { template -std::shared_ptr AssetManager::cache(const std::string & file_path, bool reload) { +std::shared_ptr AssetManager::cache(const std::string & file_path, + bool reload) { auto it = asset_cache.find(file_path); if (!reload && it != asset_cache.end()) { diff --git a/src/crepe/api/Color.h b/src/crepe/api/Color.h index 36d91ef..e818de4 100644 --- a/src/crepe/api/Color.h +++ b/src/crepe/api/Color.h @@ -6,6 +6,7 @@ class Color { // FIXME: can't these colors be defined as a `static constexpr const Color` // instead? + public: Color(double red, double green, double blue, double alpha); static const Color & get_white(); diff --git a/src/crepe/api/Config.h b/src/crepe/api/Config.h index 24b5529..8a7f268 100644 --- a/src/crepe/api/Config.h +++ b/src/crepe/api/Config.h @@ -7,6 +7,7 @@ namespace crepe::api { class Config { private: Config() = default; + public: ~Config() = default; @@ -36,5 +37,4 @@ public: } log; }; -} - +} // namespace crepe::api diff --git a/src/crepe/api/Transform.h b/src/crepe/api/Transform.h index c17ae34..c69ec61 100644 --- a/src/crepe/api/Transform.h +++ b/src/crepe/api/Transform.h @@ -12,6 +12,7 @@ class Transform : public Component { // FIXME: What's the difference between the `Point` and `Position` // classes/structs? How about we replace both with a universal `Vec2` that // works similar (or the same) as those found in GLSL? + public: Transform(uint32_t id, Point &, double, double); ~Transform(); diff --git a/src/crepe/util/color.cpp b/src/crepe/util/color.cpp index bdf5809..a7bbc81 100644 --- a/src/crepe/util/color.cpp +++ b/src/crepe/util/color.cpp @@ -1,8 +1,8 @@ #include +#include "../api/Config.h" #include "color.h" #include "fmt.h" -#include "../api/Config.h" using namespace crepe::util; using namespace std; @@ -41,20 +41,51 @@ LogColor & LogColor::reset() { return *this; } -LogColor & LogColor::fg_black(bool bright) { return this->add_code(bright ? 90 : 30); } -LogColor & LogColor::fg_red(bool bright) { return this->add_code(bright ? 91 : 31); } -LogColor & LogColor::fg_green(bool bright) { return this->add_code(bright ? 92 : 32); } -LogColor & LogColor::fg_yellow(bool bright) { return this->add_code(bright ? 93 : 33); } -LogColor & LogColor::fg_blue(bool bright) { return this->add_code(bright ? 94 : 34); } -LogColor & LogColor::fg_magenta(bool bright) { return this->add_code(bright ? 95 : 35); } -LogColor & LogColor::fg_cyan(bool bright) { return this->add_code(bright ? 96 : 36); } -LogColor & LogColor::fg_white(bool bright) { return this->add_code(bright ? 97 : 37); } -LogColor & LogColor::bg_black(bool bright) { return this->add_code(bright ? 100 : 40); } -LogColor & LogColor::bg_red(bool bright) { return this->add_code(bright ? 101 : 41); } -LogColor & LogColor::bg_green(bool bright) { return this->add_code(bright ? 102 : 42); } -LogColor & LogColor::bg_yellow(bool bright) { return this->add_code(bright ? 103 : 43); } -LogColor & LogColor::bg_blue(bool bright) { return this->add_code(bright ? 104 : 44); } -LogColor & LogColor::bg_magenta(bool bright) { return this->add_code(bright ? 105 : 45); } -LogColor & LogColor::bg_cyan(bool bright) { return this->add_code(bright ? 106 : 46); } -LogColor & LogColor::bg_white(bool bright) { return this->add_code(bright ? 107 : 47); } - +LogColor & LogColor::fg_black(bool bright) { + return this->add_code(bright ? 90 : 30); +} +LogColor & LogColor::fg_red(bool bright) { + return this->add_code(bright ? 91 : 31); +} +LogColor & LogColor::fg_green(bool bright) { + return this->add_code(bright ? 92 : 32); +} +LogColor & LogColor::fg_yellow(bool bright) { + return this->add_code(bright ? 93 : 33); +} +LogColor & LogColor::fg_blue(bool bright) { + return this->add_code(bright ? 94 : 34); +} +LogColor & LogColor::fg_magenta(bool bright) { + return this->add_code(bright ? 95 : 35); +} +LogColor & LogColor::fg_cyan(bool bright) { + return this->add_code(bright ? 96 : 36); +} +LogColor & LogColor::fg_white(bool bright) { + return this->add_code(bright ? 97 : 37); +} +LogColor & LogColor::bg_black(bool bright) { + return this->add_code(bright ? 100 : 40); +} +LogColor & LogColor::bg_red(bool bright) { + return this->add_code(bright ? 101 : 41); +} +LogColor & LogColor::bg_green(bool bright) { + return this->add_code(bright ? 102 : 42); +} +LogColor & LogColor::bg_yellow(bool bright) { + return this->add_code(bright ? 103 : 43); +} +LogColor & LogColor::bg_blue(bool bright) { + return this->add_code(bright ? 104 : 44); +} +LogColor & LogColor::bg_magenta(bool bright) { + return this->add_code(bright ? 105 : 45); +} +LogColor & LogColor::bg_cyan(bool bright) { + return this->add_code(bright ? 106 : 46); +} +LogColor & LogColor::bg_white(bool bright) { + return this->add_code(bright ? 107 : 47); +} diff --git a/src/crepe/util/color.h b/src/crepe/util/color.h index 66f3a28..91e1abe 100644 --- a/src/crepe/util/color.h +++ b/src/crepe/util/color.h @@ -48,4 +48,4 @@ private: std::string final = ""; }; -} // namespace crepe::util::color +} // namespace crepe::util diff --git a/src/crepe/util/log.cpp b/src/crepe/util/log.cpp index 5ff2ad4..6bcc4ae 100644 --- a/src/crepe/util/log.cpp +++ b/src/crepe/util/log.cpp @@ -3,20 +3,25 @@ #include #include +#include "../api/Config.h" #include "fmt.h" #include "log.h" -#include "../api/Config.h" using namespace crepe::util; using namespace std; string log_prefix(LogLevel level) { switch (level) { - case LogLevel::TRACE: return LogColor().fg_white().str("[TRACE]") + " "; - case LogLevel::DEBUG: return LogColor().fg_magenta().str("[DEBUG]") + " "; - case LogLevel::INFO: return LogColor().fg_blue().str("[INFO]") + " "; - case LogLevel::WARNING: return LogColor().fg_yellow().str("[WARN]") + " "; - case LogLevel::ERROR: return LogColor().fg_red().str("[ERROR]") + " "; + case LogLevel::TRACE: + return LogColor().fg_white().str("[TRACE]") + " "; + case LogLevel::DEBUG: + return LogColor().fg_magenta().str("[DEBUG]") + " "; + case LogLevel::INFO: + return LogColor().fg_blue().str("[INFO]") + " "; + case LogLevel::WARNING: + return LogColor().fg_yellow().str("[WARN]") + " "; + case LogLevel::ERROR: + return LogColor().fg_red().str("[ERROR]") + " "; } return ""; } @@ -46,4 +51,3 @@ void crepe::util::logf(LogLevel level, const char * fmt, ...) { log(level, va_stringf(args, fmt)); va_end(args); } - diff --git a/src/crepe/util/log.h b/src/crepe/util/log.h index 5ee67eb..308ba96 100644 --- a/src/crepe/util/log.h +++ b/src/crepe/util/log.h @@ -6,12 +6,19 @@ #include "color.h" // utility macros -#define _crepe_logf_here(level, format, ...) crepe::util::logf(level, "%s" format, crepe::util::LogColor().fg_white(false).fmt("%s (%s:%d)", __PRETTY_FUNCTION__, __FILE_NAME__, __LINE__), __VA_ARGS__) +#define _crepe_logf_here(level, format, ...) \ + crepe::util::logf( \ + level, "%s" format, \ + crepe::util::LogColor().fg_white(false).fmt( \ + "%s (%s:%d)", __PRETTY_FUNCTION__, __FILE_NAME__, __LINE__), \ + __VA_ARGS__) // very illegal global function-style macros // NOLINTBEGIN -#define dbg_logf(fmt, ...) _crepe_logf_here(crepe::util::LogLevel::DEBUG, ": " fmt, __VA_ARGS__) -#define dbg_log(str) _crepe_logf_here(crepe::util::LogLevel::DEBUG, "%s: " str, "") +#define dbg_logf(fmt, ...) \ + _crepe_logf_here(crepe::util::LogLevel::DEBUG, ": " fmt, __VA_ARGS__) +#define dbg_log(str) \ + _crepe_logf_here(crepe::util::LogLevel::DEBUG, "%s: " str, "") #define dbg_trace() _crepe_logf_here(crepe::util::LogLevel::TRACE, "%s", "") // NOLINTEND diff --git a/src/example/log.cpp b/src/example/log.cpp index 86ef193..3bc6d80 100644 --- a/src/example/log.cpp +++ b/src/example/log.cpp @@ -3,8 +3,8 @@ * Standalone example for usage of the logging functions */ -#include #include +#include using namespace crepe; using namespace crepe::util; @@ -22,4 +22,3 @@ int main() { return 0; } - diff --git a/src/example/script.cpp b/src/example/script.cpp index f737a90..d0cc121 100644 --- a/src/example/script.cpp +++ b/src/example/script.cpp @@ -7,8 +7,8 @@ #include #include -#include #include +#include #include #include diff --git a/src/makefile b/src/makefile index c1ef601..3f74a2a 100644 --- a/src/makefile +++ b/src/makefile @@ -2,5 +2,7 @@ FMT += $(shell git ls-files '*.c' '*.cpp' '*.h' '*.hpp') format: FORCE - clang-tidy -p build/compile_commands.json --fix-errors $(FMT) + # clang-tidy -p build/compile_commands.json --fix-errors $(FMT) + +# TODO: re-enable linter after 2024-11-10 -- cgit v1.2.3 From ebd163e3aacac74df1772d5bd794d2691918d324 Mon Sep 17 00:00:00 2001 From: WBoerenkamps Date: Fri, 25 Oct 2024 20:57:31 +0200 Subject: collision event added, multiple callbacks working, id trigger working --- mwe/events/include/customTypes.h | 39 +++++++++++++++++++++ mwe/events/include/event.h | 13 +++++++ mwe/events/include/eventManager.h | 6 ++-- mwe/events/include/userevent.h | 0 mwe/events/src/event.cpp | 10 ++++++ mwe/events/src/eventManager.cpp | 71 +++++++++++++++++---------------------- mwe/events/src/main.cpp | 55 +++++++++++++++++++++++------- 7 files changed, 138 insertions(+), 56 deletions(-) create mode 100644 mwe/events/include/customTypes.h create mode 100644 mwe/events/include/userevent.h (limited to 'mwe/events/src') diff --git a/mwe/events/include/customTypes.h b/mwe/events/include/customTypes.h new file mode 100644 index 0000000..7217f8a --- /dev/null +++ b/mwe/events/include/customTypes.h @@ -0,0 +1,39 @@ +#pragma once +#include +struct Vector2 { + float x; // X component of the vector + float y; // Y component of the vector + + // Vector subtraction + Vector2 operator-(const Vector2& other) const { + return {x - other.x, y - other.y}; + } + + // Vector addition + Vector2 operator+(const Vector2& other) const { + return {x + other.x, y + other.y}; + } + + // Scalar multiplication + Vector2 operator*(float scalar) const { + return {x * scalar, y * scalar}; + } + + // Normalize the vector + Vector2 normalize() const { + float length = std::sqrt(x * x + y * y); + if (length == 0) return {0, 0}; // Prevent division by zero + return {x / length, y / length}; + } +}; +struct Collision { + int objectIdA; // ID of the first object + int objectIdB; // ID of the second object + Vector2 contactPoint; // Point of contact + Vector2 contactNormal; // Normal vector at the contact point + + // Constructor to initialize a Collision + Collision(int idA, int idB, const Vector2& point, const Vector2& normal, float depth) + : objectIdA(idA), objectIdB(idB), contactPoint(point), contactNormal(normal) {} + +}; diff --git a/mwe/events/include/event.h b/mwe/events/include/event.h index 802140c..d060faa 100644 --- a/mwe/events/include/event.h +++ b/mwe/events/include/event.h @@ -5,6 +5,7 @@ #include #include #include "keyCodes.h" +#include "customTypes.h" class UUIDGenerator { public: @@ -85,3 +86,15 @@ private: int mouseX = 0; int mouseY = 0; }; +class CollisionEvent : public Event { +public: + CollisionEvent(Collision); + + REGISTER_EVENT_TYPE(CollisionEvent) + + Collision getCollisionData() const; + +private: + Collision collisionData; + +}; diff --git a/mwe/events/include/eventManager.h b/mwe/events/include/eventManager.h index 709796a..b8abccc 100644 --- a/mwe/events/include/eventManager.h +++ b/mwe/events/include/eventManager.h @@ -26,9 +26,9 @@ public: private: EventManager() = default; - std::vector, int>> m_eventsQueue; - std::unordered_map>> m_subscribers; - std::unordered_map>>> m_subscribersByEventId; + std::vector, int>> eventsQueue; + std::unordered_map>> subscribers; + std::unordered_map>>> subscribersByEventId; }; diff --git a/mwe/events/include/userevent.h b/mwe/events/include/userevent.h new file mode 100644 index 0000000..e69de29 diff --git a/mwe/events/src/event.cpp b/mwe/events/src/event.cpp index fecae76..e4c046f 100644 --- a/mwe/events/src/event.cpp +++ b/mwe/events/src/event.cpp @@ -54,3 +54,13 @@ MousePressedEvent::MousePressedEvent(int mouseX, int mouseY) std::pair MousePressedEvent::getMousePosition() const { return {mouseX, mouseY}; } + +//Collision event +CollisionEvent::CollisionEvent(Collision collision) : collisionData(collision), Event("CollisionEvent") { + +} + +Collision CollisionEvent::getCollisionData() const +{ + return this->collisionData; +} diff --git a/mwe/events/src/eventManager.cpp b/mwe/events/src/eventManager.cpp index ce8e940..c37dcb0 100644 --- a/mwe/events/src/eventManager.cpp +++ b/mwe/events/src/eventManager.cpp @@ -2,15 +2,15 @@ void EventManager::shutdown() { - m_subscribers.clear(); + subscribers.clear(); } void EventManager::subscribe(int eventType, std::unique_ptr&& handler, int eventId) { if (eventId) { - std::unordered_map>>>::iterator subscribers = m_subscribersByEventId.find(eventType); + std::unordered_map>>>::iterator subscribers = subscribersByEventId.find(eventType); - if (subscribers != m_subscribersByEventId.end()) { + if (subscribers != subscribersByEventId.end()) { std::unordered_map>>& handlersMap = subscribers->second; std::unordered_map>>::iterator handlers = handlersMap.find(eventId); if (handlers != handlersMap.end()) { @@ -18,31 +18,20 @@ void EventManager::subscribe(int eventType, std::unique_ptr>>::iterator subscribers = m_subscribers.find(eventType); - if (subscribers != m_subscribers.end()) { - std::vector>& handlers = subscribers->second; - for (std::unique_ptr& it : handlers) { - if (it->getType() == handler->getType()) { - // log for double register - return; - } - } - handlers.emplace_back(std::move(handler)); - } else { - m_subscribers[eventType].emplace_back(std::move(handler)); - } + auto& handlers = subscribers[eventType]; + handlers.emplace_back(std::move(handler)); } } void EventManager::unsubscribe(int eventType, const std::string& handlerName, int eventId) { if (eventId) { - std::unordered_map>>>::iterator subscribers = m_subscribersByEventId.find(eventType); - if (subscribers != m_subscribersByEventId.end()) { - std::unordered_map>>& handlersMap = subscribers->second; + std::unordered_map>>>::iterator subscriberList = subscribersByEventId.find(eventType); + if (subscriberList != subscribersByEventId.end()) { + std::unordered_map>>& handlersMap = subscriberList->second; std::unordered_map>>::iterator handlers = handlersMap.find(eventId); if (handlers != handlersMap.end()) { std::vector>& callbacks = handlers->second; @@ -55,8 +44,8 @@ void EventManager::unsubscribe(int eventType, const std::string& handlerName, in } } } else { - std::unordered_map>>::iterator handlersIt = m_subscribers.find(eventType); - if (handlersIt != m_subscribers.end()) { + std::unordered_map>>::iterator handlersIt = subscribers.find(eventType); + if (handlersIt != subscribers.end()) { std::vector>& handlers = handlersIt->second; for (std::vector>::iterator it = handlers.begin(); it != handlers.end(); ++it) { if (it->get()->getType() == handlerName) { @@ -70,38 +59,38 @@ void EventManager::unsubscribe(int eventType, const std::string& handlerName, in void EventManager::triggerEvent(const Event& event_, int eventId) { - std::vector>& handlers = m_subscribers[event_.getEventType()]; - for (std::unique_ptr& handler : handlers) { - handler->exec(event_); - } - - std::unordered_map>>& handlersMap = m_subscribersByEventId[event_.getEventType()]; - std::unordered_map>>::iterator handlersIt = handlersMap.find(eventId); - if (handlersIt != handlersMap.end()) { - std::vector>& callbacks = handlersIt->second; - for (std::vector>::iterator it = callbacks.begin(); it != callbacks.end();) { - std::unique_ptr& handler = *it; - handler->exec(event_); - if (handler->isDestroyOnSuccess()) { - it = callbacks.erase(it); - } else { - ++it; + if (eventId > 0) { + auto handlersIt = subscribersByEventId[event_.getEventType()].find(eventId); + if (handlersIt != subscribersByEventId[event_.getEventType()].end()) { + std::vector>& callbacks = handlersIt->second; + for (auto it = callbacks.begin(); it != callbacks.end();) { + (*it)->exec(event_); + if ((*it)->isDestroyOnSuccess()) { + it = callbacks.erase(it); + } else { + ++it; + } } } + } else { + auto& handlers = subscribers[event_.getEventType()]; + for (std::unique_ptr& handler : handlers) { + handler->exec(event_); + } } } void EventManager::queueEvent(std::unique_ptr&& event_, int eventId) { - m_eventsQueue.emplace_back(std::move(event_), eventId); + eventsQueue.emplace_back(std::move(event_), eventId); } void EventManager::dispatchEvents() { - for (std::vector, int>>::iterator eventIt = m_eventsQueue.begin(); eventIt != m_eventsQueue.end();) { + for (std::vector, int>>::iterator eventIt = eventsQueue.begin(); eventIt != eventsQueue.end();) { if (!eventIt->first.get()->getHandled()) { triggerEvent(*eventIt->first.get(), eventIt->second); - eventIt = m_eventsQueue.erase(eventIt); + eventIt = eventsQueue.erase(eventIt); } else { ++eventIt; } diff --git a/mwe/events/src/main.cpp b/mwe/events/src/main.cpp index 3940c60..21f2dbf 100644 --- a/mwe/events/src/main.cpp +++ b/mwe/events/src/main.cpp @@ -3,7 +3,7 @@ #include #include "loopManager.h" #include "event.h" - +#include "customTypes.h" class PlayerDamagedEvent : public Event { public: PlayerDamagedEvent(int damage, int playerID) @@ -13,7 +13,7 @@ public: int getDamage() const { return damage; } int getPlayerID() const { return playerID; } - + private: int damage; int playerID; @@ -22,10 +22,24 @@ void onPlayerDamaged(const PlayerDamagedEvent& e) { std::cout << "Player " << e.getPlayerID() << " took " << e.getDamage() << " damage." << std::endl; } +void onKeyPressed1(const KeyPressedEvent& e) +{ + int keyCode = e.getKeyCode(); + fprintf(stderr,"first function KeyCode %d\n",keyCode); +} void onKeyPressed(const KeyPressedEvent& e) { - const int keyCode = e.getKeyCode(); - fprintf(stderr,"KeyCode %d\n",keyCode); + int keyCode = e.getKeyCode(); + fprintf(stderr,"second function KeyCode %d\n",keyCode); +} +void CollisionHandler(const CollisionEvent& e){ + std::cout << "collision betwee object id: "<< e.getCollisionData().objectIdA << " and id: " << e.getCollisionData().objectIdB << std::endl; +} +void testCollisionEvent() { + Collision testCollision(1, 2, {3, 4}, {5, 6}, 7.8f); + subscribe(CollisionHandler,1); + // EventHandler + triggerEvent(CollisionEvent(testCollision), 1); } int main(int argc, char* args[]) { LoopManager gameLoop; @@ -34,17 +48,34 @@ int main(int argc, char* args[]) { // onKeyPressed(e); // }; // custom event class poc - EventHandler playerDamagedHandler = onPlayerDamaged; - subscribe(playerDamagedHandler); - + subscribe(onPlayerDamaged); triggerEvent(PlayerDamagedEvent(50, 1)); - //EventHandler callback = onKeyPressed; - //subscribe(callback,false); - std::unique_ptr anotherKeyPressEvent = std::make_unique(65); - queueEvent(std::move(anotherKeyPressEvent)); - triggerEvent(KeyPressedEvent(42)); + subscribe(onKeyPressed,1,false); + subscribe(onKeyPressed1,false); + // std::unique_ptr anotherKeyPressEvent = std::make_unique(65); + // queueEvent(std::move(anotherKeyPressEvent)); + triggerEvent(KeyPressedEvent(42), 1); + EventManager::getInstance().dispatchEvents(); + //collision event call + testCollisionEvent(); gameLoop.setup(); gameLoop.loop(); return 0; } +// void collisionUpdate(){ +// int count; +// //iedere collision +// for (int i = 0; i < count; i++) +// { +// //trigger object 1 +// //triger object 2 +// triggerEvent(CollisionEvent(1,2),1); +// triggerEvent(CollisionEvent(1,2),2); +// } + +// } +// int main(){ + +// return 0; +// } -- cgit v1.2.3 From f472e0ba3bf54fc5055cf9f08925bed3f98a1dbc Mon Sep 17 00:00:00 2001 From: WBoerenkamps Date: Fri, 25 Oct 2024 20:58:26 +0200 Subject: removed comment --- mwe/events/src/main.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'mwe/events/src') diff --git a/mwe/events/src/main.cpp b/mwe/events/src/main.cpp index 21f2dbf..6b22008 100644 --- a/mwe/events/src/main.cpp +++ b/mwe/events/src/main.cpp @@ -52,13 +52,13 @@ int main(int argc, char* args[]) { triggerEvent(PlayerDamagedEvent(50, 1)); subscribe(onKeyPressed,1,false); subscribe(onKeyPressed1,false); - // std::unique_ptr anotherKeyPressEvent = std::make_unique(65); // queueEvent(std::move(anotherKeyPressEvent)); triggerEvent(KeyPressedEvent(42), 1); EventManager::getInstance().dispatchEvents(); //collision event call testCollisionEvent(); + gameLoop.setup(); gameLoop.loop(); return 0; -- cgit v1.2.3 From 26bb39991aaebe3b7ef8869f217db490143bc0e6 Mon Sep 17 00:00:00 2001 From: WBoerenkamps Date: Fri, 25 Oct 2024 21:14:09 +0200 Subject: merge conflicts fixed --- .vscode/settings.json | 6 +- mwe/events/src/eventManager.cpp | 152 ---------------------------------------- mwe/events/src/main.cpp | 25 ------- 3 files changed, 5 insertions(+), 178 deletions(-) (limited to 'mwe/events/src') diff --git a/.vscode/settings.json b/.vscode/settings.json index 936b057..1ea4738 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -62,6 +62,10 @@ "cinttypes": "cpp", "typeinfo": "cpp", "valarray": "cpp", - "variant": "cpp" + "variant": "cpp", + "forward_list": "cpp", + "codecvt": "cpp", + "fstream": "cpp", + "typeindex": "cpp" } } diff --git a/mwe/events/src/eventManager.cpp b/mwe/events/src/eventManager.cpp index e022849..c37dcb0 100644 --- a/mwe/events/src/eventManager.cpp +++ b/mwe/events/src/eventManager.cpp @@ -1,6 +1,5 @@ #include "eventManager.h" -<<<<<<< HEAD void EventManager::shutdown() { subscribers.clear(); @@ -96,155 +95,4 @@ void EventManager::dispatchEvents() ++eventIt; } } -======= -void EventManager::shutdown() { m_subscribers.clear(); } - -void EventManager::subscribe(int eventType, - std::unique_ptr && handler, - int eventId) { - if (eventId) { - std::unordered_map< - int, std::unordered_map< - int, std::vector>>>:: - iterator subscribers - = m_subscribersByEventId.find(eventType); - - if (subscribers != m_subscribersByEventId.end()) { - std::unordered_map< - int, std::vector>> & - handlersMap - = subscribers->second; - std::unordered_map< - int, - std::vector>>::iterator - handlers - = handlersMap.find(eventId); - if (handlers != handlersMap.end()) { - handlers->second.emplace_back(std::move(handler)); - return; - } - } - m_subscribersByEventId[eventType][eventId].emplace_back( - std::move(handler)); - - } else { - std::unordered_map< - int, std::vector>>::iterator - subscribers - = m_subscribers.find(eventType); - if (subscribers != m_subscribers.end()) { - std::vector> & handlers - = subscribers->second; - for (std::unique_ptr & it : handlers) { - if (it->getType() == handler->getType()) { - // log for double register - return; - } - } - handlers.emplace_back(std::move(handler)); - } else { - m_subscribers[eventType].emplace_back(std::move(handler)); - } - } -} - -void EventManager::unsubscribe(int eventType, const std::string & handlerName, - int eventId) { - if (eventId) { - std::unordered_map< - int, std::unordered_map< - int, std::vector>>>:: - iterator subscribers - = m_subscribersByEventId.find(eventType); - if (subscribers != m_subscribersByEventId.end()) { - std::unordered_map< - int, std::vector>> & - handlersMap - = subscribers->second; - std::unordered_map< - int, - std::vector>>::iterator - handlers - = handlersMap.find(eventId); - if (handlers != handlersMap.end()) { - std::vector> & callbacks - = handlers->second; - for (std::vector< - std::unique_ptr>::iterator it - = callbacks.begin(); - it != callbacks.end(); ++it) { - if (it->get()->getType() == handlerName) { - it = callbacks.erase(it); - return; - } - } - } - } - } else { - std::unordered_map< - int, std::vector>>::iterator - handlersIt - = m_subscribers.find(eventType); - if (handlersIt != m_subscribers.end()) { - std::vector> & handlers - = handlersIt->second; - for (std::vector>::iterator it - = handlers.begin(); - it != handlers.end(); ++it) { - if (it->get()->getType() == handlerName) { - it = handlers.erase(it); - return; - } - } - } - } -} - -void EventManager::triggerEvent(const Event & event_, int eventId) { - std::vector> & handlers - = m_subscribers[event_.getEventType()]; - for (std::unique_ptr & handler : handlers) { - handler->exec(event_); - } - - std::unordered_map< - int, std::vector>> & handlersMap - = m_subscribersByEventId[event_.getEventType()]; - std::unordered_map< - int, std::vector>>::iterator - handlersIt - = handlersMap.find(eventId); - if (handlersIt != handlersMap.end()) { - std::vector> & callbacks - = handlersIt->second; - for (std::vector>::iterator it - = callbacks.begin(); - it != callbacks.end();) { - std::unique_ptr & handler = *it; - handler->exec(event_); - if (handler->isDestroyOnSuccess()) { - it = callbacks.erase(it); - } else { - ++it; - } - } - } -} - -void EventManager::queueEvent(std::unique_ptr && event_, int eventId) { - m_eventsQueue.emplace_back(std::move(event_), eventId); -} - -void EventManager::dispatchEvents() { - for (std::vector, int>>::iterator eventIt - = m_eventsQueue.begin(); - eventIt != m_eventsQueue.end();) { - if (!eventIt->first.get()->getHandled()) { - triggerEvent(*eventIt->first.get(), eventIt->second); - eventIt = m_eventsQueue.erase(eventIt); - } else { - ++eventIt; - } - } ->>>>>>> b3b762a34e7ccb4a0dcd041a693ac7180af16002 } diff --git a/mwe/events/src/main.cpp b/mwe/events/src/main.cpp index 971ca35..d056f85 100644 --- a/mwe/events/src/main.cpp +++ b/mwe/events/src/main.cpp @@ -3,13 +3,9 @@ #include #include #include -<<<<<<< HEAD #include "loopManager.h" #include "event.h" #include "customTypes.h" -======= - ->>>>>>> b3b762a34e7ccb4a0dcd041a693ac7180af16002 class PlayerDamagedEvent : public Event { public: PlayerDamagedEvent(int damage, int playerID) @@ -17,15 +13,9 @@ public: REGISTER_EVENT_TYPE(PlayerDamagedEvent); -<<<<<<< HEAD int getDamage() const { return damage; } int getPlayerID() const { return playerID; } -======= - int getDamage() const { return damage; } - int getPlayerID() const { return playerID; } - ->>>>>>> b3b762a34e7ccb4a0dcd041a693ac7180af16002 private: int damage; int playerID; @@ -35,7 +25,6 @@ void onPlayerDamaged(const PlayerDamagedEvent & e) { << " damage." << std::endl; } -<<<<<<< HEAD void onKeyPressed1(const KeyPressedEvent& e) { int keyCode = e.getKeyCode(); @@ -54,11 +43,6 @@ void testCollisionEvent() { subscribe(CollisionHandler,1); // EventHandler triggerEvent(CollisionEvent(testCollision), 1); -======= -void onKeyPressed(const KeyPressedEvent & e) { - const int keyCode = e.getKeyCode(); - fprintf(stderr, "KeyCode %d\n", keyCode); ->>>>>>> b3b762a34e7ccb4a0dcd041a693ac7180af16002 } int main(int argc, char * args[]) { LoopManager gameLoop; @@ -69,20 +53,11 @@ int main(int argc, char * args[]) { // custom event class poc subscribe(onPlayerDamaged); triggerEvent(PlayerDamagedEvent(50, 1)); -<<<<<<< HEAD subscribe(onKeyPressed,1,false); subscribe(onKeyPressed1,false); // queueEvent(std::move(anotherKeyPressEvent)); triggerEvent(KeyPressedEvent(42), 1); -======= - //EventHandler callback = onKeyPressed; - //subscribe(callback,false); - std::unique_ptr anotherKeyPressEvent - = std::make_unique(65); - queueEvent(std::move(anotherKeyPressEvent)); - triggerEvent(KeyPressedEvent(42)); ->>>>>>> b3b762a34e7ccb4a0dcd041a693ac7180af16002 EventManager::getInstance().dispatchEvents(); //collision event call testCollisionEvent(); -- cgit v1.2.3 From 7d8af5f56f9359fff792470fbb55154268b36458 Mon Sep 17 00:00:00 2001 From: Loek Le Blansch Date: Fri, 25 Oct 2024 21:21:27 +0200 Subject: `make format` --- mwe/events/include/customTypes.h | 55 +++++------ mwe/events/include/event.h | 12 +-- mwe/events/include/eventManager.h | 12 ++- mwe/events/src/event.cpp | 8 +- mwe/events/src/eventManager.cpp | 200 ++++++++++++++++++++++---------------- mwe/events/src/main.cpp | 48 +++++---- 6 files changed, 182 insertions(+), 153 deletions(-) (limited to 'mwe/events/src') diff --git a/mwe/events/include/customTypes.h b/mwe/events/include/customTypes.h index 7217f8a..a5d8dc9 100644 --- a/mwe/events/include/customTypes.h +++ b/mwe/events/include/customTypes.h @@ -1,39 +1,38 @@ #pragma once #include struct Vector2 { - float x; // X component of the vector - float y; // Y component of the vector + float x; // X component of the vector + float y; // Y component of the vector - // Vector subtraction - Vector2 operator-(const Vector2& other) const { - return {x - other.x, y - other.y}; - } + // Vector subtraction + Vector2 operator-(const Vector2 & other) const { + return {x - other.x, y - other.y}; + } - // Vector addition - Vector2 operator+(const Vector2& other) const { - return {x + other.x, y + other.y}; - } + // Vector addition + Vector2 operator+(const Vector2 & other) const { + return {x + other.x, y + other.y}; + } - // Scalar multiplication - Vector2 operator*(float scalar) const { - return {x * scalar, y * scalar}; - } + // Scalar multiplication + Vector2 operator*(float scalar) const { return {x * scalar, y * scalar}; } - // Normalize the vector - Vector2 normalize() const { - float length = std::sqrt(x * x + y * y); - if (length == 0) return {0, 0}; // Prevent division by zero - return {x / length, y / length}; - } + // Normalize the vector + Vector2 normalize() const { + float length = std::sqrt(x * x + y * y); + if (length == 0) return {0, 0}; // Prevent division by zero + return {x / length, y / length}; + } }; struct Collision { - int objectIdA; // ID of the first object - int objectIdB; // ID of the second object - Vector2 contactPoint; // Point of contact - Vector2 contactNormal; // Normal vector at the contact point - - // Constructor to initialize a Collision - Collision(int idA, int idB, const Vector2& point, const Vector2& normal, float depth) - : objectIdA(idA), objectIdB(idB), contactPoint(point), contactNormal(normal) {} + int objectIdA; // ID of the first object + int objectIdB; // ID of the second object + Vector2 contactPoint; // Point of contact + Vector2 contactNormal; // Normal vector at the contact point + // Constructor to initialize a Collision + Collision(int idA, int idB, const Vector2 & point, const Vector2 & normal, + float depth) + : objectIdA(idA), objectIdB(idB), contactPoint(point), + contactNormal(normal) {} }; diff --git a/mwe/events/include/event.h b/mwe/events/include/event.h index 0208085..730ee4b 100644 --- a/mwe/events/include/event.h +++ b/mwe/events/include/event.h @@ -1,12 +1,11 @@ #pragma once +#include "customTypes.h" #include "keyCodes.h" #include #include #include #include #include -#include "keyCodes.h" -#include "customTypes.h" class UUIDGenerator { public: @@ -93,13 +92,12 @@ private: }; class CollisionEvent : public Event { public: - CollisionEvent(Collision); + CollisionEvent(Collision); - REGISTER_EVENT_TYPE(CollisionEvent) + REGISTER_EVENT_TYPE(CollisionEvent) - Collision getCollisionData() const; + Collision getCollisionData() const; private: - Collision collisionData; - + Collision collisionData; }; diff --git a/mwe/events/include/eventManager.h b/mwe/events/include/eventManager.h index 61e8c01..508a5e2 100644 --- a/mwe/events/include/eventManager.h +++ b/mwe/events/include/eventManager.h @@ -28,10 +28,14 @@ public: void dispatchEvents(); private: - EventManager() = default; - std::vector, int>> eventsQueue; - std::unordered_map>> subscribers; - std::unordered_map>>> subscribersByEventId; + EventManager() = default; + std::vector, int>> eventsQueue; + std::unordered_map>> + subscribers; + std::unordered_map< + int, std::unordered_map< + int, std::vector>>> + subscribersByEventId; }; template diff --git a/mwe/events/src/event.cpp b/mwe/events/src/event.cpp index 38ff62a..c9201d0 100644 --- a/mwe/events/src/event.cpp +++ b/mwe/events/src/event.cpp @@ -44,11 +44,9 @@ std::pair MousePressedEvent::getMousePosition() const { } //Collision event -CollisionEvent::CollisionEvent(Collision collision) : collisionData(collision), Event("CollisionEvent") { +CollisionEvent::CollisionEvent(Collision collision) + : collisionData(collision), Event("CollisionEvent") {} -} - -Collision CollisionEvent::getCollisionData() const -{ +Collision CollisionEvent::getCollisionData() const { return this->collisionData; } diff --git a/mwe/events/src/eventManager.cpp b/mwe/events/src/eventManager.cpp index c37dcb0..34a093d 100644 --- a/mwe/events/src/eventManager.cpp +++ b/mwe/events/src/eventManager.cpp @@ -1,98 +1,130 @@ #include "eventManager.h" -void EventManager::shutdown() -{ - subscribers.clear(); -} +void EventManager::shutdown() { subscribers.clear(); } -void EventManager::subscribe(int eventType, std::unique_ptr&& handler, int eventId) -{ - if (eventId) { - std::unordered_map>>>::iterator subscribers = subscribersByEventId.find(eventType); +void EventManager::subscribe(int eventType, + std::unique_ptr && handler, + int eventId) { + if (eventId) { + std::unordered_map< + int, std::unordered_map< + int, std::vector>>>:: + iterator subscribers + = subscribersByEventId.find(eventType); - if (subscribers != subscribersByEventId.end()) { - std::unordered_map>>& handlersMap = subscribers->second; - std::unordered_map>>::iterator handlers = handlersMap.find(eventId); - if (handlers != handlersMap.end()) { - handlers->second.emplace_back(std::move(handler)); - return; - } - } - subscribersByEventId[eventType][eventId].emplace_back(std::move(handler)); + if (subscribers != subscribersByEventId.end()) { + std::unordered_map< + int, std::vector>> & + handlersMap + = subscribers->second; + std::unordered_map< + int, + std::vector>>::iterator + handlers + = handlersMap.find(eventId); + if (handlers != handlersMap.end()) { + handlers->second.emplace_back(std::move(handler)); + return; + } + } + subscribersByEventId[eventType][eventId].emplace_back( + std::move(handler)); - } else { - auto& handlers = subscribers[eventType]; - handlers.emplace_back(std::move(handler)); - } + } else { + auto & handlers = subscribers[eventType]; + handlers.emplace_back(std::move(handler)); + } } -void EventManager::unsubscribe(int eventType, const std::string& handlerName, int eventId) -{ - if (eventId) { - std::unordered_map>>>::iterator subscriberList = subscribersByEventId.find(eventType); - if (subscriberList != subscribersByEventId.end()) { - std::unordered_map>>& handlersMap = subscriberList->second; - std::unordered_map>>::iterator handlers = handlersMap.find(eventId); - if (handlers != handlersMap.end()) { - std::vector>& callbacks = handlers->second; - for (std::vector>::iterator it = callbacks.begin(); it != callbacks.end(); ++it) { - if (it->get()->getType() == handlerName) { - it = callbacks.erase(it); - return; - } - } - } - } - } else { - std::unordered_map>>::iterator handlersIt = subscribers.find(eventType); - if (handlersIt != subscribers.end()) { - std::vector>& handlers = handlersIt->second; - for (std::vector>::iterator it = handlers.begin(); it != handlers.end(); ++it) { - if (it->get()->getType() == handlerName) { - it = handlers.erase(it); - return; - } - } - } - } +void EventManager::unsubscribe(int eventType, const std::string & handlerName, + int eventId) { + if (eventId) { + std::unordered_map< + int, std::unordered_map< + int, std::vector>>>:: + iterator subscriberList + = subscribersByEventId.find(eventType); + if (subscriberList != subscribersByEventId.end()) { + std::unordered_map< + int, std::vector>> & + handlersMap + = subscriberList->second; + std::unordered_map< + int, + std::vector>>::iterator + handlers + = handlersMap.find(eventId); + if (handlers != handlersMap.end()) { + std::vector> & callbacks + = handlers->second; + for (std::vector< + std::unique_ptr>::iterator it + = callbacks.begin(); + it != callbacks.end(); ++it) { + if (it->get()->getType() == handlerName) { + it = callbacks.erase(it); + return; + } + } + } + } + } else { + std::unordered_map< + int, std::vector>>::iterator + handlersIt + = subscribers.find(eventType); + if (handlersIt != subscribers.end()) { + std::vector> & handlers + = handlersIt->second; + for (std::vector>::iterator it + = handlers.begin(); + it != handlers.end(); ++it) { + if (it->get()->getType() == handlerName) { + it = handlers.erase(it); + return; + } + } + } + } } -void EventManager::triggerEvent(const Event& event_, int eventId) -{ - if (eventId > 0) { - auto handlersIt = subscribersByEventId[event_.getEventType()].find(eventId); - if (handlersIt != subscribersByEventId[event_.getEventType()].end()) { - std::vector>& callbacks = handlersIt->second; - for (auto it = callbacks.begin(); it != callbacks.end();) { - (*it)->exec(event_); - if ((*it)->isDestroyOnSuccess()) { - it = callbacks.erase(it); - } else { - ++it; - } - } - } - } else { - auto& handlers = subscribers[event_.getEventType()]; - for (std::unique_ptr& handler : handlers) { - handler->exec(event_); - } - } +void EventManager::triggerEvent(const Event & event_, int eventId) { + if (eventId > 0) { + auto handlersIt + = subscribersByEventId[event_.getEventType()].find(eventId); + if (handlersIt != subscribersByEventId[event_.getEventType()].end()) { + std::vector> & callbacks + = handlersIt->second; + for (auto it = callbacks.begin(); it != callbacks.end();) { + (*it)->exec(event_); + if ((*it)->isDestroyOnSuccess()) { + it = callbacks.erase(it); + } else { + ++it; + } + } + } + } else { + auto & handlers = subscribers[event_.getEventType()]; + for (std::unique_ptr & handler : handlers) { + handler->exec(event_); + } + } } -void EventManager::queueEvent(std::unique_ptr&& event_, int eventId) -{ - eventsQueue.emplace_back(std::move(event_), eventId); +void EventManager::queueEvent(std::unique_ptr && event_, int eventId) { + eventsQueue.emplace_back(std::move(event_), eventId); } -void EventManager::dispatchEvents() -{ - for (std::vector, int>>::iterator eventIt = eventsQueue.begin(); eventIt != eventsQueue.end();) { - if (!eventIt->first.get()->getHandled()) { - triggerEvent(*eventIt->first.get(), eventIt->second); - eventIt = eventsQueue.erase(eventIt); - } else { - ++eventIt; - } - } +void EventManager::dispatchEvents() { + for (std::vector, int>>::iterator eventIt + = eventsQueue.begin(); + eventIt != eventsQueue.end();) { + if (!eventIt->first.get()->getHandled()) { + triggerEvent(*eventIt->first.get(), eventIt->second); + eventIt = eventsQueue.erase(eventIt); + } else { + ++eventIt; + } + } } diff --git a/mwe/events/src/main.cpp b/mwe/events/src/main.cpp index d056f85..f7e0766 100644 --- a/mwe/events/src/main.cpp +++ b/mwe/events/src/main.cpp @@ -1,11 +1,9 @@ +#include "customTypes.h" #include "event.h" #include "loopManager.h" #include #include #include -#include "loopManager.h" -#include "event.h" -#include "customTypes.h" class PlayerDamagedEvent : public Event { public: PlayerDamagedEvent(int damage, int playerID) @@ -13,9 +11,9 @@ public: REGISTER_EVENT_TYPE(PlayerDamagedEvent); - int getDamage() const { return damage; } - int getPlayerID() const { return playerID; } - + int getDamage() const { return damage; } + int getPlayerID() const { return playerID; } + private: int damage; int playerID; @@ -25,22 +23,22 @@ void onPlayerDamaged(const PlayerDamagedEvent & e) { << " damage." << std::endl; } -void onKeyPressed1(const KeyPressedEvent& e) -{ - int keyCode = e.getKeyCode(); - fprintf(stderr,"first function KeyCode %d\n",keyCode); +void onKeyPressed1(const KeyPressedEvent & e) { + int keyCode = e.getKeyCode(); + fprintf(stderr, "first function KeyCode %d\n", keyCode); } -void onKeyPressed(const KeyPressedEvent& e) -{ - int keyCode = e.getKeyCode(); - fprintf(stderr,"second function KeyCode %d\n",keyCode); +void onKeyPressed(const KeyPressedEvent & e) { + int keyCode = e.getKeyCode(); + fprintf(stderr, "second function KeyCode %d\n", keyCode); } -void CollisionHandler(const CollisionEvent& e){ - std::cout << "collision betwee object id: "<< e.getCollisionData().objectIdA << " and id: " << e.getCollisionData().objectIdB << std::endl; +void CollisionHandler(const CollisionEvent & e) { + std::cout << "collision betwee object id: " + << e.getCollisionData().objectIdA + << " and id: " << e.getCollisionData().objectIdB << std::endl; } void testCollisionEvent() { Collision testCollision(1, 2, {3, 4}, {5, 6}, 7.8f); - subscribe(CollisionHandler,1); + subscribe(CollisionHandler, 1); // EventHandler triggerEvent(CollisionEvent(testCollision), 1); } @@ -53,15 +51,15 @@ int main(int argc, char * args[]) { // custom event class poc subscribe(onPlayerDamaged); triggerEvent(PlayerDamagedEvent(50, 1)); - subscribe(onKeyPressed,1,false); - subscribe(onKeyPressed1,false); - // queueEvent(std::move(anotherKeyPressEvent)); - triggerEvent(KeyPressedEvent(42), 1); - + subscribe(onKeyPressed, 1, false); + subscribe(onKeyPressed1, false); + // queueEvent(std::move(anotherKeyPressEvent)); + triggerEvent(KeyPressedEvent(42), 1); + EventManager::getInstance().dispatchEvents(); //collision event call testCollisionEvent(); - + gameLoop.setup(); gameLoop.loop(); return 0; @@ -76,9 +74,9 @@ int main(int argc, char * args[]) { // triggerEvent(CollisionEvent(1,2),1); // triggerEvent(CollisionEvent(1,2),2); // } - + // } // int main(){ - + // return 0; // } -- cgit v1.2.3