fencer/src/input.c

76 lines
1.9 KiB
C

#include "input.h"
#include "debug.h"
#include "list.h"
#include <stdint.h>
typedef struct InputAction {
const uint8_t* positive;
const uint8_t* negative;
int last;
void* object_arg;
InputActionDelegate delegate;
} InputAction;
static List _actions;
static const uint8_t* _keys;
void input_init() {
_actions = list_from_type(InputAction);
_keys = SDL_GetKeyboardState(NULL);
}
void input_clean() {
list_empty(&_actions);
}
static
void _key_changed_event(SDL_Event evt) {
const uint8_t* keyptr = _keys + evt.key.keysym.scancode;
list_foreach(InputAction, action, &_actions) {
if(keyptr == action->positive || keyptr == action->negative) {
int val = *action->positive - *action->negative;
if(val != action->last) {
action->last = val;
action->delegate(action->object_arg, val);
}
}
}
}
void input_handle_event(SDL_Event event) {
switch(event.type) {
default:return;
case SDL_KEYDOWN:
case SDL_KEYUP:
_key_changed_event(event);
break;
}
}
void input_add_axis_action(void* object, InputActionDelegate delegate, SDL_Scancode negative, SDL_Scancode positive) {
list_add(&_actions, &(InputAction){
.negative = _keys + negative,
.positive = _keys + positive,
.delegate = delegate,
.object_arg = object,
});
}
void input_add_key_action(void* object, InputActionDelegate delegate, SDL_Scancode key) {
list_add(&_actions, &(InputAction) {
.negative = _keys + SDL_SCANCODE_UNKNOWN,
.positive = _keys + key,
.delegate = delegate,
.object_arg = object,
});
}
void input_remove_actions(void* object) {
for(size_t i = 0; i < _actions.len; ++i) {
if(list_at_as(InputAction, &_actions, i)->object_arg == object) {
list_erase(&_actions, i);
}
}
}