#include "input.h" #include #include #include #include static struct Input input; static const int default_map[K_COUNT] = { KEY_LEFT, KEY_RIGHT, KEY_UP, KEY_DOWN, KEY_SHIFT, KEY_ALPHA, KEY_EXIT, KEY_TAN, KEY_F3, KEY_F2, KEY_F1, KEY_F4, KEY_F5, KEY_F6}; static const char *replay_path = "jtmm2.fls"; static void next_state(int i, int kdown); static PackedFrame pack_frame(void); static void unpack_frame(PackedFrame); void input_init(void) { int i = K_COUNT; while (i-- > 0) { input.keys[i] = default_map[i]; input.states[i] = KS_UP; } i = REPLAY_SIZE; input.replay_cursor = 0; input.playback = 0; } void input_update(void) { int i = K_COUNT; clearevents(); while (i-- > K_EXIT) { const int kdown = keydown(input.keys[i]); next_state(i, kdown); } if (input.playback) { unpack_frame(input.replay[input.replay_cursor++]); if (input.replay_cursor >= input.replay_end || input.replay_cursor >= REPLAY_SIZE) { input.replay_cursor--; input.playback = 0; } } else { i++; while (i-- > 0) { const int kdown = keydown(input.keys[i]); next_state(i, kdown); } input.replay[input.replay_cursor++] = pack_frame(); if (input.replay_cursor >= REPLAY_SIZE) input.replay_cursor--; } } void input_dump_replay(void) { const int fd = open(replay_path, O_WRONLY | O_CREAT | O_TRUNC, 0644); if (fd != -1) { write(fd, input.replay, input.replay_cursor * sizeof(PackedFrame)); close(fd); } } void input_load_replay(void) { const int fd = open(replay_path, O_RDONLY); if (fd != -1) { input.playback = 1; input.replay_cursor = 0; input.replay_end = read(fd, input.replay, REPLAY_SIZE) / sizeof(PackedFrame); if (!input.replay_end) input.replay_cursor = REPLAY_SIZE; close(fd); } } void input_set_down(enum Key k) { input.states[k] = KS_DOWN; } void input_set_pressed(enum Key k) { input.states[k] = KS_PRESS; } void input_set_up(enum Key k) { input.states[k] = KS_UP; } int input_down(enum Key k) { return input.states[k] != KS_UP; } int input_pressed(enum Key k) { return input.states[k] == KS_PRESS; } int input_up(enum Key k) { return input.states[k] == KS_UP; } static void next_state(int i, int kdown) { input.states[i] = (input.states[i] == KS_UP) ? (kdown ? KS_PRESS : KS_UP) : (kdown ? KS_DOWN : KS_UP); } static PackedFrame pack_frame(void) { PackedFrame r = 0; int i = K_EXIT; while (i-- > 0) r |= input_down(i) << i; return r; } static void unpack_frame(PackedFrame f) { int i = K_EXIT; while (i-- > 0) next_state(i, (f & (1 << i)) != 0); }