holesome/src/game/input/input_mapper.cpp

104 lines
2.9 KiB
C++
Raw Normal View History

#include "input_mapper.h"
2023-05-08 18:20:55 +02:00
void InputMapper::setGame(Game *game)
{
2023-05-08 18:20:55 +02:00
InputMapper::game = game;
2023-05-16 21:56:55 +02:00
// Initialize identities
allIdentity = std::make_shared<InputIdentity>(InputDeviceType::ALL);
keyboardIdentity = std::make_shared<InputIdentity>(InputDeviceType::KEYBOARD);
gamepadIdentities = std::map<unsigned int, std::shared_ptr<InputIdentity>>();
}
2023-05-08 18:20:55 +02:00
void InputMapper::processEvents()
{
sf::Event event{};
while (game->window->pollEvent(event))
{
switch (event.type)
{
case sf::Event::KeyPressed:
handleKeyPress(event.key);
break;
case sf::Event::KeyReleased:
2023-05-09 20:50:50 +02:00
handleKeyRelease(event.key);
break;
case sf::Event::Closed:
game->exit();
break;
case sf::Event::Resized:
break;
2023-05-16 21:56:55 +02:00
case sf::Event::JoystickMoved:
handleJoystickMovement(event.joystickMove);
break;
default:
break;
}
}
}
void InputMapper::handleKeyPress(sf::Event::KeyEvent event)
{
// Close game on Escape or Q in DEV Mode
if (DEVELOPER_MODE && (event.code == sf::Keyboard::Escape || event.code == sf::Keyboard::Q))
{
game->exit();
return;
}
// Handle directionVector
auto direction = Direction::getKeyDirection(event.code);
if (direction != HardDirection::NONE)
{
2023-05-09 20:50:50 +02:00
inputDirectionBuffer.push_back(direction);
}
}
Direction InputMapper::getInputDirection()
2023-05-09 20:50:50 +02:00
{
HardDirection direction = HardDirection::NONE;
2023-05-09 20:50:50 +02:00
for (HardDirection directionPart: inputDirectionBuffer)
2023-05-09 20:50:50 +02:00
{
direction = static_cast<HardDirection>(direction | directionPart);
2023-05-09 20:50:50 +02:00
}
return Direction(direction);
2023-05-09 20:50:50 +02:00
}
void InputMapper::handleKeyRelease(sf::Event::KeyEvent event)
{
// Handle directionVector
auto direction = Direction::getKeyDirection(event.code);
if (direction != HardDirection::NONE)
2023-05-09 20:50:50 +02:00
{
// Remove directionVector from buffer
2023-05-09 20:50:50 +02:00
inputDirectionBuffer.erase(std::remove(inputDirectionBuffer.begin(), inputDirectionBuffer.end(), direction),
inputDirectionBuffer.end());
}
}
2023-05-16 21:56:55 +02:00
void InputMapper::handleJoystickMovement(sf::Event::JoystickMoveEvent event)
{
event.joystickId;
}
std::shared_ptr<InputIdentity> InputMapper::getInputIdentity(InputDeviceType deviceType, unsigned int gamepadId)
{
switch (deviceType)
{
case InputDeviceType::KEYBOARD:
return keyboardIdentity;
case InputDeviceType::GAMEPAD:
if (gamepadIdentities.find(gamepadId) == gamepadIdentities.end())
{
throw std::invalid_argument("Gamepad with id " + std::to_string(gamepadId) + " not found.");
}
return gamepadIdentities[gamepadId];
default:
return allIdentity;
}
}