Skip to content
TheChatArchiveThe Chat Archive
gpt-4-1106-preview· OpenAIAi2 WildChat-4.8M (AI2)

I am making a C++, SDL based, game engine, and I need help to finish it and polish it.…

  1. User

    I am making a C++, SDL based, game engine, and I need help to finish it and polish it. Currently I am doing the final touches to my InputManager class, check if it is correct or if something is missing or could be improved:

    class InputManager { public: ~InputManager() = default; InputManager(const InputManager&) = delete; InputManager operator=(const InputManager&) = delete; static InputManager& GetInstance(); void Update(); bool IsKeyPressed(Input::KeyCode key) const; bool IsKeyReleased(Input::KeyCode key) const; bool IsMouseButtonPressed(Input::MouseButton button) const; Point GetMousePosition() const; bool IsGamepadButtonDown(Input::GamepadButton button, int gamepadIndex) const;

    private:
        InputManager();
        void KeyPressed(uint8_t keyPressed);
        void KeyReleased(uint8_t keyReleased);
        void SetMouseState(uint8_t mouseButton, bool pressed);
        SDL_GameController* GetGamepad();
    
        std::unordered_map<Input::KeyCode, bool> currentKeyboardState;
        std::unordered_map<Input::KeyCode, bool> previousKeyboardState;
        std::unordered_map<Input::MouseButton, bool> mouseButtonsState;
        SDL_GameController* gamepad;
    

    };

    #include "InputManager.h"

    #include #include

    uint8_t KeyToSDL(Input::KeyCode keyCode); Input::KeyCode KeyFromSDL(uint8_t sdlKeyCode); uint8_t MouseButtonToSDL(Input::MouseButton mouseButton); Input::MouseButton MouseButtonFromSDL(uint8_t sdlMouseButton); SDL_GameControllerButton GamepadButtonToSDL(Input::GamepadButton gamepadButton); Input::GamepadButton GamepadButtonFromSDL(SDL_GameControllerButton sdlGamepadButton);

    InputManager::InputManager() { }

    InputManager& InputManager::GetInstance() { static InputManager instance;

    return instance;
    

    }

    void InputManager::Update() { SDL_Event event; while (SDL_PollEvent(&event)) { switch (event.type) { case SDL_KEYDOWN: { KeyPressed(event.key.keysym.sym); break; } case SDL_KEYUP: { KeyReleased(event.key.keysym.sym); break; } case SDL_MOUSEBUTTONUP: { SetMouseState(event.button.button, false); break; } case SDL_MOUSEBUTTONDOWN: { SetMouseState(event.button.button, true); break; } case SDL_CONTROLLERDEVICEADDED: { if (!gamepad) { gamepad = SDL_GameControllerOpen(event.cdevice.which); } break; } case SDL_CONTROLLERDEVICEREMOVED: { if (gamepad && event.cdevice.which == SDL_JoystickInstanceID(SDL_GameControllerGetJoystick(gamepad))) { SDL_GameControllerClose(gamepad); gamepad = GetGamepad(); } break; } } } }

    bool InputManager::IsKeyPressed(Input::KeyCode key) const { return currentKeyboardState.at(key) && !previousKeyboardState.at(key); }

    bool InputManager::IsKeyReleased(Input::KeyCode key) const { return !currentKeyboardState.at(key) && previousKeyboardState.at(key); }

    bool InputManager::IsMouseButtonPressed(Input::MouseButton button) const { return mouseButtonsState.at(button); }

    Point InputManager::GetMousePosition() const { int x = 0; int y = 0; SDL_GetMouseState(&x, &y);

    return Point(x, y);
    

    }

    bool InputManager::IsGamepadButtonDown(Input::GamepadButton button, int gamepadIndex) const { return SDL_GameControllerGetButton(gamepad, GamepadButtonToSDL(button)); }

    void InputManager::KeyPressed(uint8_t keyPressed) { previousKeyboardState.at(KeyFromSDL(keyPressed)) = false; currentKeyboardState.at(KeyFromSDL(keyPressed)) = true; }

    void InputManager::KeyReleased(uint8_t keyReleased) { previousKeyboardState.at(KeyFromSDL(keyReleased)) = true; currentKeyboardState.at(KeyFromSDL(keyReleased)) = false; }

    void InputManager::SetMouseState(uint8_t mouseButton, bool pressed) { mouseButtonsState[MouseButtonFromSDL(mouseButton)] = pressed; }

    SDL_GameController* InputManager::GetGamepad() { for (int i = 0; i < SDL_NumJoysticks(); ++i) { if (SDL_IsGameController(i)) { return SDL_GameControllerOpen(i); } }

    return nullptr;
    

    }

  2. Assistant

    Your InputManager class is well structured with clear intent for each function. Here's some feedback and suggestions for improvement:

    1. Thread Safety: If your game engine is expected to be run on multiple threads, it's important to ensure that your InputManager is thread-safe. Data shared between threads, like the input states, should be carefully managed to prevent race conditions.

    2. Exception Handling: Your code currently uses std::unordered_map::at which throws an exception if the key is not found. It's often a good idea, especially in a real-time system such as a game, to avoid exceptions and instead handle such cases manually, maybe by returning a default value or an error code.

    3. Previous State Updating: It looks like you might have a bug in your KeyPressed and KeyReleased methods. You set previousKeyboardState.at(KeyFromSDL(keyPressed)) to false when a key is pressed. However, previousKeyboardState should usually represent the state of the keys during the last frame, not get updated immediately when a new event comes in. The code to update previousKeyboardState should probably be in the Update method, called once per frame before processing new events.

    4. Return Value of IsGamepadButtonDown: The method IsGamepadButtonDown always gets the state from gamepad, disregarding the gamepadIndex parameter. This might be a bug if you intend to support multiple gamepads. Make sure to access the correct gamepad according to the given index.

    5. Initialization of gamepad Pointer: Your gamepad pointer is used but never initialized in the constructor. This could potentially lead to undefined behavior. Consider initializing it to nullptr in the constructor.

    6. Mouse Buttons State Updating: The SetMouseState method will insert new keys into the mouseButtonsState map, but there's no code showing where the initial state is set. Ensure that the state is properly initialized before use.

    7. Make sure to add the necessary #include statements for any types or functions you're using in the header file, such as <unordered_map> for std::unordered_map, <utility> for std::pair if you're using Point, the correct includes for SDL, and any that provide Input::KeyCode, Input::MouseButton, and Input::GamepadButton definitions.

    8. Event Loop Inside Update: The Update method polls all SDL events, including potentially non-input related ones. This is usually fine for small projects, but for larger applications, you might want to have a dedicated event manager that dispatches events to different systems accordingly.

    9. Singleton Pattern: You are using the singleton pattern for your InputManager. This pattern can sometimes lead to issues with unit testing and refactoring, and it can also make dependencies less clear. Consider if passing an instance of InputManager to objects that need it (dependency injection) might be a better option depending on your architecture.

    10. Destructor: The ~InputManager() destructor does not clean up the gamepad if it's open. It's a good idea to ensure that resources are properly released if they are acquired.

    Here's one possible approach for safely updating the keyboard state:

    void InputManager::UpdateState()
    {
        previousKeyboardState = currentKeyboardState;
    
        SDL_Event event;
        // ... (handle events)
    }
    

    In your update loop, UpdateState would be called once per frame, ensuring that previousKeyboardState is the keyboard state from the last frame.

    Lastly, whenever dealing with raw pointers, especially with external resources like SDL's SDL_GameController, it's beneficial to consider smart pointers, such as unique_ptr with a custom deleter, to handle the resource management more safely and conveniently.