I am making a c++ sdl based game engine, and I just made the event manager but I don't…
- User
I am making a c++ sdl based game engine, and I just made the event manager but I don't know how to use the Subscribe method, can you show me the usage on how would be do for for example a KeyboardKeyDownEvent using a HandleKeyboardKeyDownEvent function?
InputManager::InputManager() { // TODO: Should subscribe using EventManager::GetInstance().Subscribe(...) calling this->HandleKeyboardKeyDownEvent receiving a KeyboardKeyDownEvent. }
class EventManager { public: static EventManager& GetInstance() noexcept; template void Subscribe(std::function<void(std::shared_ptr)> handler); ... }
/** @brief Subscribe *
-
@todo: document this function */ template void EventManager::Subscribe(std::function<void(std::shared_ptr)>handler) { static_assert(std::is_base_of<Event, T>::value, "ERROR: T must be a subclass of Event");
auto wrapper = [handler](std::shared_ptr event) { handler(std::static_pointer_cast(event)); }; subscribers[std::type_index(typeid(T))].push_back(wrapper); }
class KeyboardKeyDownEvent : public KeyboardKeyBaseEvent { public: KeyboardKeyDownEvent(uint32_t windowID, Input::KeyCode keyCode); ~KeyboardKeyDownEvent() override = default; };
KeyboardKeyDownEvent::KeyboardKeyDownEvent(uint32_t windowID, Input::KeyCode keyCode) : KeyboardKeyBaseEvent(windowID, keyCode) { priority = 245; }
-
- Assistant
- User
I don't understand the std::placeholders::_1 part and why that has to be in this part. My first idea was doing something like this instead of using a bind function:
EventManager::GetInstance().Subscribe([this](std::shared_ptr event){ this->HandleKeyboardKeyDownEvent(std::static_pointer_cast(event)); });
- Assistant
- User
I see, but it is giving errors:
/src/InputManager.cpp: In constructor ‘InputManager::InputManager()’: /src/InputManager.cpp:16:42: error: no matching function for call to ‘EventManager::Subscribe(InputManager::InputManager()::<lambda(std::shared_ptr)>)’ 16 | EventManager::GetInstance().Subscribe([this](std::shared_ptr event){ | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 17 | this->HandleKeyboardKeyDownEvent(std::static_pointer_cast(event)); | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 18 | }); | ~~
In file included from /src/InputManager.cpp:7: include/EventManager.h:24:14: note: candidate: ‘template void EventManager::Subscribe(std::function<void(std::shared_ptr<_Tp>)>)’ 24 | void Subscribe(std::function<void(std::shared_ptr)> handler); | ^~~~~~~~~ include/EventManager.h:24:14: note: template argument deduction/substitution failed: /src/InputManager.cpp:16:42: note: ‘InputManager::InputManager()::<lambda(std::shared_ptr)>’ is not derived from ‘std::function<void(std::shared_ptr<_Tp>)>’ 16 | EventManager::GetInstance().Subscribe([this](std::shared_ptr event){ | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 17 | this->HandleKeyboardKeyDownEvent(std::static_pointer_cast(event)); | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 18 | }); | ~~ - Assistant
The error you're encountering stems from a type mismatch issue between the lambda function you're trying to pass to the
Subscribemethod and what theSubscribemethod expects. TheSubscribemethod is templated to take astd::function<void(std::shared_ptr<T>)>whereTshould inherit fromEvent. However, due to the way C++ templates work, the compiler is unable to automatically deduceTfrom the lambda because it doesn't match directly due to the lambda accepting a instead of a . - User
It works, now from a design perspective, should I send the event to the Handle method or should I just send the data of the event in this case the button pressed?
- void HandleKeyboardKeyDownEvent(std::shared_ptr event); or
- void HandleKeyboardKeyDownEvent(Input::KeyCode key);
What is the best approach? Also take into account that I will replicate this for every other event in all the subscribers.
- Assistant
- User
I think the flexibility is important and as you say, it could be the best default and then if something is slow I can just refactor it later, also it will help me to keep it like that because I could receive and event and publish it again, if that makes sense. Also, since it is a std::shared_ptr, there is no need for delete the pointer or anything like that, right?
- Assistant
Yes, your reasoning is sound. Opting for flexibility, especially during the initial phases of development, can indeed prove beneficial. Designing your system to handle entire event objects provides the versatility needed to expand or modify your event structure without necessitating widespread changes across your event handlers. This approach grants you the leeway to adapt as the requirements of your game engine evolve.
- User
Ok perfect, i like how this is working out, now my old update method won't be needed anymore, right? ANd not only that, every other Update method that receives an event is going to dissapear in favor for these Handle functions, right?
void InputManager::Update() { previousKeyboardState = currentKeyboardState;
SDL_Event event; while (SDL_PollEvent(&event)) { switch (event.type) { case SDL_MOUSEBUTTONUP: { SetMouseState(event.button.button, false); break; } case SDL_MOUSEBUTTONDOWN: { SetMouseState(event.button.button, true); break; } case SDL_CONTROLLERDEVICEADDED: { int instanceID = SDL_JoystickGetDeviceInstanceID(event.cdevice.which); try { Gamepad newGamepad(instanceID); gamepads.insert({ instanceID, std::move(newGamepad) }); } catch (std::runtime_error& e) { std::string errorMsg = "ERROR: Gamepad " + std::to_string(instanceID) + " could not be open: " + e.what(); SDL_LogError(SDL_LOG_CATEGORY_ERROR, errorMsg.c_str()); } break; } case SDL_CONTROLLERDEVICEREMOVED: { int instanceID = event.cdevice.which; gamepads.erase(instanceID); break; } case SDL_CONTROLLERBUTTONDOWN: case SDL_CONTROLLERBUTTONUP: { int instanceID = event.cdevice.which; auto it = gamepads.find(instanceID); if (it != gamepads.end()) { it->second.Update(event); } break; } } } UpdateKeyboardState(); - Assistant
- User
I understood, and yeah I will keep Update methods when needed, but in this case it is not, I could do two things here,
- Handle all the events in each Handle function (my prefered option, makes more sense to me.)
- Keep the Update function that will be called by every other Handle function with their own Event and then use a switch to decide that to do (I don't like this option).
which one of this is the best in this use case?
also I will have to move the
previousKeyboardState = currentKeyboardState; // event handling UpdateKeyboardState();
to keyboardkeydown and keyboardkeyup hanlding, right?
- Assistant
- User
Ok I found out that both of the keyboard events will be handled with the same code, in this case should I point both to the same Handle function or make it separated even though they would end up doing the same? I am not even using the event information, I just calculate the keyboard state without taking the key into account, this is the way I had before but seems like too much overhead, or not, but at least it keeps all the states consistently, what do you think?
std::unordered_map<Input::KeyCode, bool> currentKeyboardState; std::unordered_map<Input::KeyCode, bool> previousKeyboardState;
void InputManager::UpdateKeyboardState() { int numKeys; const Uint8* keyStates = SDL_GetKeyboardState(&numKeys);
for (int i = 0; i < numKeys; ++i) { Input::KeyCode code = KeyFromSDL(i); currentKeyboardState[code] = keyStates[i] != 0; }}
void InputManager::SetMouseState(uint8_t mouseButton, bool pressed) { mouseButtonsState[MouseButtonFromSDL(mouseButton)] = pressed; }
void InputManager::HandleKeyboardKeyDownEvent(std::shared_ptrevent) { previousKeyboardState = currentKeyboardState; UpdateKeyboardState(); }
void InputManager::HandleKeyboardKeyUpEvent(std::shared_ptrevent) { previousKeyboardState = currentKeyboardState; UpdateKeyboardState(); }
- Assistant
- User
What about my second concern: "I am not even using the event information, I just calculate the keyboard state without taking the key into account, this is the way I had before but seems like too much overhead, or not, but at least it keeps all the states consistently, what do you think?"
- Assistant
- User
OK I will leave it like that, and call it a day. but now another problem arised, My InputManager has a collection of Gamepads, now I can't use the subscribe event for the gamepad class since the input manager is the one that handles everything about the gamepad and has the collection of gamepads, so I don't know where should I put the subscribe in these cases.
- Should I subscribe for the gamepad events in the InputManager and call an Update method with an Event and then do a switch case to determine which event subclass is and handle them privately?
- Should I make the Handle gamepad methods public and be accesed from the InputManager, which makes them being calleable from everywhere which is not my design purpose?
- Another alternative I am missing?
- Assistant
- User
But that means making the HandleButtonPress methods in the Gamepad public or friend class private, which I will have to make friend class with the input manager right? So in the end the inputmanager will receive the event and call the handle events in the gamepad, right?
- Assistant
- User
I don't have a type for my events, so we will have to dynamically check the object class they represent, my event class hierarchy is like this:
class Event { friend class EventConverter;
public: virtual ~Event() = default; protected: uint8_t priority;};
class GamepadButtonDownEvent : public GamepadButtonBaseEvent { public: GamepadButtonDownEvent(int gamepadID, Input::GamepadButton button); ~GamepadButtonDownEvent() override = default; };
class GamepadBaseEvent : public Event { public: virtual ~GamepadBaseEvent() override = default; int GetGamepadID() const;
protected: GamepadBaseEvent(int gamepadID); int gamepadID;};
- Assistant
- User
I think this will be a much verbose option that I just make them friends and make them couple-tightly. My InputManager already controls everything about the controls. Another alternative would be making the subscribe method inside each Gamepad constructor and use the GetGamepadID to check if match their own and use them, but I don't know if this is possible since they are objects inside a map of the InputManager and I don't know if I want to give them this much freedom.
- Assistant
- User
I know what I will do, I will make a Attorney-Client pattern class, and I will expose the Handle Events functions of the Gamepad and make it friend class with InputManager, that way InputManager doesn't have the entire class as friend, and I can use their specific handle events that would be private in the gamepad class. So given this new approach, do you think this is better even thought it will be bloating the source more with more classes, or should I just make the Gamepad and InputManager friends directly so it can access the Handle event methods directly and privately?
- Assistant
- User
I got another question for you, what if I want to deal with events that has an specific ID for the object, should I check that in the lamba in the subscribe call or in the handle method?
EventManager::GetInstance().Subscribe([this](std::shared_ptr event){ if (event->GetWindowID() == GetWindowID()) { this->HandleWindowShownEvent(event); } });
void Window::HandleWindowShownEvent(std::shared_ptrevent) { if (event->GetWindowID() == GetWindowID()) { visible = true; } }
- Assistant
- User
Understood, I decided to go for the first approach, since I care more about efficiency than the other points, now another unrelated thing: Do you think I should store the windowID as a field in my Window class or the call to SDL_GetWindowID(window); function is negigible?
- Assistant