/// @file platform/keyboard.h /// @brief Tracks held keys and pending key presses. #pragma once #include #include #include "core/types.h" namespace kumo { /// @brief Keys tracked by Keyboard. Count is a sentinel. enum class Key : uint8_t { Left, Right, Up, Down, Space, Count }; /// @brief Stores the current key state and presses waiting for a tick. /// /// A press stays pending even if the key is released before the next tick. /// Key arguments must be one of Left, Right, Up, Down, or Space. class Keyboard { public: /// @brief Updates a key and records a press when it goes from up to down. void set_key(Key key, bool down) { State& state = keys_[static_cast(key)]; if (down && !state.down && state.presses < std::numeric_limits::max()) { ++state.presses; } state.down = down; } /// @brief Returns whether the key is currently held. bool is_down(Key key) const { return keys_[static_cast(key)].down; } /// @brief Returns and clears the pending presses for the key. uint32_t take_presses(Key key) { State& state = keys_[static_cast(key)]; const uint32_t presses = state.presses; state.presses = 0; return presses; } /// @brief Releases all held keys and keeps pending presses. /// /// Call when the window loses keyboard focus. void release_all() { for (State& state : keys_) { state.down = false; } } private: struct State { bool down = false; uint32_t presses = 0; }; std::array(Key::Count)> keys_{}; }; } // namespace kumo