Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improved support for input chords #5

Merged
merged 5 commits into from
Nov 8, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions src/engine/Chord.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
#include "Chord.hpp"
#include "Types.hpp"
#include "Utils.hpp"

Chord::Chord(int chord_id, std::unordered_set<SDL_Scancode> keys) {
if (chord_id == 0) {
Log(LogLevel::Error, "The chord_id should be greater than 0!");
app->quit.store(true);
return;
}

this->chord_id = chord_id;
this->keys = keys;
}

int Chord::GetChordID() { return this->chord_id; }

std::unordered_set<SDL_Scancode> Chord::GetKeys() { return this->keys; }

bool Chord::IsKeyInChord(SDL_Scancode key) { return this->keys.count(key) > 0; }
24 changes: 13 additions & 11 deletions src/engine/Collision.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -72,8 +72,6 @@ void Collision::HandlePairwiseCollision(Entity *collider) {
Overlap overlap = GetOverlap(rect_1, rect_2);

int pos_x = 0, pos_y = 0;
float vel_x = this->entity->GetComponent<Physics>()->GetVelocity().x;
float vel_y = this->entity->GetComponent<Physics>()->GetVelocity().y;

if (overlap == Overlap::Left) {
pos_x = col_x - obj_width;
Expand All @@ -89,18 +87,22 @@ void Collision::HandlePairwiseCollision(Entity *collider) {
pos_y = col_y + col_height;
}

this->entity->GetComponent<Transform>()->SetPosition(Position{float(pos_x), float(pos_y)});
if (this->entity->GetComponent<Physics>()) {
this->entity->GetComponent<Transform>()->SetPosition(Position{float(pos_x), float(pos_y)});
float vel_x = this->entity->GetComponent<Physics>()->GetVelocity().x;
float vel_y = this->entity->GetComponent<Physics>()->GetVelocity().y;

if (collider->GetCategory() != EntityCategory::SideBoundary) {
if (overlap == Overlap::Left || overlap == Overlap::Right) {
vel_x *= -this->GetRestitution();
}
if (overlap == Overlap::Top || overlap == Overlap::Bottom) {
vel_y *= -this->GetRestitution();
if (collider->GetCategory() != EntityCategory::SideBoundary) {
if (overlap == Overlap::Left || overlap == Overlap::Right) {
vel_x *= -this->GetRestitution();
}
if (overlap == Overlap::Top || overlap == Overlap::Bottom) {
vel_y *= -this->GetRestitution();
}
}
}

this->entity->GetComponent<Physics>()->SetVelocity(Velocity{vel_x, vel_y});
this->entity->GetComponent<Physics>()->SetVelocity(Velocity{vel_x, vel_y});
}
}

void Collision::Update() {}
Expand Down
7 changes: 0 additions & 7 deletions src/engine/EventManager.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -157,13 +157,6 @@ void EventManager::RaiseInputEvent(InputEvent event) {
input_event.SetDelay(0);
input_event.SetPriority(Priority::High);

if (event.type == InputEventType::Single) {
Log(LogLevel::Info, "Raising single input: [%d] [%d]", event.pressed, event.key);
}
if (event.type == InputEventType::Chord) {
Log(LogLevel::Info, "Raising chord input: [%d], [%d]", event.pressed, event.chord_id);
}

this->Raise(input_event);
}

Expand Down
153 changes: 92 additions & 61 deletions src/engine/Input.cpp
Original file line number Diff line number Diff line change
@@ -1,111 +1,142 @@
#include "Input.hpp"

#include "Engine.hpp"
#include "Chord.hpp"
#include "EventManager.hpp"
#include "SDL_keyboard.h"
#include "SDL_scancode.h"
#include "Types.hpp"
#include "Utils.hpp"
#include <algorithm>
#include <cstddef>

Input::Input() {
this->keyboard_state = nullptr;
this->chords = std::unordered_map<int, std::unordered_set<SDL_Scancode>>();
this->key_press_times = std::unordered_map<SDL_Scancode, int64_t>();
this->chord_delay = 100;
}
this->chords = std::vector<Chord>();

// Event handler function to be called on key state change
void Input::RaiseEvent(SDL_Scancode key, bool is_pressed) {
EventManager::GetInstance().RaiseInputEvent(
InputEvent{InputEventType::Single, key, 0, is_pressed});
this->buffer = std::vector<std::pair<SDL_Scancode, bool>>();
this->start = std::chrono::steady_clock::now();
this->elapsed = 0;
this->timeout = 100;
}

bool Input::IsKeyInChords(SDL_Scancode key) {
for (const auto &[chord_id, chord_keys] : this->chords) {
if (chord_keys.count(key) > 0) {
for (Chord &chord : this->chords) {
if (chord.IsKeyInChord(key)) {
return true;
}
}
return false;
}

void Input::LogBuffer() {
std::string log_buffer = "";
for (const auto &entry : this->buffer) {
SDL_Scancode key = entry.first;
bool pressed = entry.second;

log_buffer += std::to_string(key) + "_" + std::to_string(pressed) + " , ";
}
Log(LogLevel::Info, "buffer: %s", log_buffer.c_str());
}

void Input::FlushBuffer() {
for (const auto &entry : this->buffer) {
SDL_Scancode key = entry.first;
bool pressed = entry.second;

EventManager::GetInstance().RaiseInputEvent(
InputEvent{InputEventType::Single, key, 0, pressed});
}
this->buffer.clear();
}

void Input::Process() {
const Uint8 *new_state = SDL_GetKeyboardState(NULL);

// If first call, initialize prevState to match the current state
if (!this->keyboard_state) {
int num_keys;
this->keyboard_state = new Uint8[SDL_NUM_SCANCODES];
memcpy((void *)this->keyboard_state, new_state, SDL_NUM_SCANCODES);
}

// To ensure only changes to chords are raised
static std::unordered_map<int, bool> active_chords;

int64_t current_time = Engine::GetInstance().EngineTimelineGetTime();

for (const auto &[chord_id, chord_keys] : this->chords) {
bool chord_detected = true;

for (SDL_Scancode key : chord_keys) {
if (!new_state[key]) {
chord_detected = false;
break;
}
}

if (chord_detected) {
if (!active_chords[chord_id]) {
EventManager::GetInstance().RaiseInputEvent(
InputEvent{InputEventType::Chord, SDL_SCANCODE_UNKNOWN, chord_id, true});
active_chords[chord_id] = true;
}
} else {
if (active_chords[chord_id]) {
EventManager::GetInstance().RaiseInputEvent(
InputEvent{InputEventType::Chord, SDL_SCANCODE_UNKNOWN, chord_id, false});
active_chords[chord_id] = false;
}
}
}

// Iterate over all scancodes and check for changes
for (int i = 0; i < SDL_NUM_SCANCODES; ++i) {
if (new_state[i] == this->keyboard_state[i]) {
continue;
}

bool is_pressed = new_state[i];
bool pressed = new_state[i];
SDL_Scancode key = static_cast<SDL_Scancode>(i);

if (is_pressed) {
key_press_times[key] = current_time;
} else {
key_press_times.erase(key);
if (!this->IsKeyInChords(key)) {
EventManager::GetInstance().RaiseInputEvent(
InputEvent{InputEventType::Single, key, 0, pressed});
continue;
}

if (this->IsKeyInChords(key)) {
int64_t delay = Engine::GetInstance().EngineTimelineGetTime() - key_press_times[key];
this->buffer.push_back({key, pressed});

if (delay >= (this->chord_delay * 1'000'000)) {
this->RaiseEvent(key, is_pressed);
}
} else {
this->RaiseEvent(key, is_pressed);
int chord_id = this->BufferContainsChord();
if (chord_id != 0) {
this->TriggerChord(chord_id);
}
}

auto now = std::chrono::steady_clock::now();
this->elapsed =
std::chrono::duration_cast<std::chrono::milliseconds>(now - this->start).count();

if (this->elapsed >= this->timeout) {
this->ResetChords();
}

// Update the previous state
memcpy((void *)this->keyboard_state, new_state, SDL_NUM_SCANCODES);
}

void Input::RegisterInputChord(int chord_id, std::unordered_set<SDL_Scancode> chord) {
if (chord_id == 0) {
Log(LogLevel::Error, "The chord_id should be greater than 0!");
app->quit.store(true);
return;
int Input::BufferContainsChord() {
for (auto &chord : this->chords) {
bool chord_found = true;

for (const auto &key : chord.GetKeys()) {
auto buffer_iterator =
std::find_if(this->buffer.begin(), this->buffer.end(),
[key](const std::pair<SDL_Scancode, bool> &entry) {
return entry.first == key && entry.second == true;
});
if (buffer_iterator == buffer.end()) {
chord_found = false;
break;
}
}

if (chord_found) {
for (const auto &key : chord.GetKeys()) {
auto buffer_iterator =
std::remove_if(buffer.begin(), buffer.end(),
[key](const std::pair<SDL_Scancode, bool> &entry) {
return entry.first == key && entry.second == true;
});
buffer.erase(buffer_iterator, buffer.end());
}
return chord.GetChordID();
}
}

this->chords[chord_id] = chord;
return 0;
}

void Input::TriggerChord(int chord_id) {
this->ResetChords();

EventManager::GetInstance().RaiseInputEvent(
InputEvent{InputEventType::Chord, SDL_SCANCODE_UNKNOWN, chord_id, true});
}

void Input::ResetChords() {
this->start = std::chrono::steady_clock::now();
this->FlushBuffer();
}

void Input::RegisterInputChord(int chord_id, std::unordered_set<SDL_Scancode> keys) {
this->chords.push_back(Chord(chord_id, keys));
}
17 changes: 17 additions & 0 deletions src/engine/includes/Chord.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
#pragma once

#include "SDL_scancode.h"
#include <unordered_set>

class Chord {
private:
int chord_id;
std::unordered_set<SDL_Scancode> keys;

public:
Chord(int chord_id, std::unordered_set<SDL_Scancode> keys);

int GetChordID();
std::unordered_set<SDL_Scancode> GetKeys();
bool IsKeyInChord(SDL_Scancode key);
};
21 changes: 15 additions & 6 deletions src/engine/includes/Input.hpp
Original file line number Diff line number Diff line change
@@ -1,22 +1,31 @@
#pragma once

#include "Chord.hpp"
#include "SDL_scancode.h"
#include "SDL_stdinc.h"
#include <unordered_map>
#include <chrono>
#include <unordered_set>
#include <vector>

class Input {
private:
Uint8 *keyboard_state;
std::unordered_map<int, std::unordered_set<SDL_Scancode>> chords;
std::unordered_map<SDL_Scancode, int64_t> key_press_times;
int64_t chord_delay;
std::vector<Chord> chords;

std::vector<std::pair<SDL_Scancode, bool>> buffer;
std::chrono::steady_clock::time_point start;
int64_t elapsed;
int timeout;

void RaiseEvent(SDL_Scancode key, bool is_pressed);
bool IsKeyInChords(SDL_Scancode key);
int BufferContainsChord();
void LogBuffer();
void FlushBuffer();
void TriggerChord(int chord_id);
void ResetChords();

public:
Input();
void Process();
void RegisterInputChord(int chord_id, std::unordered_set<SDL_Scancode> chord);
void RegisterInputChord(int chord_id, std::unordered_set<SDL_Scancode> keys);
};
Binary file modified src/games/hw4_joshua/assets/ground.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading