src/gba/gba-input.c (view raw)
1#include "gba-input.h"
2
3struct GBAInputMapImpl {
4 int* map;
5 uint32_t type;
6};
7
8void GBAInputMapInit(struct GBAInputMap* map) {
9 map->maps = 0;
10 map->numMaps = 0;
11}
12
13void GBAInputMapDeinit(struct GBAInputMap* map) {
14 size_t m;
15 for (m = 0; m < map->numMaps; ++m) {
16 free(map->maps[m].map);
17 }
18 free(map->maps);
19 map->maps = 0;
20 map->numMaps = 0;
21}
22
23enum GBAKey GBAInputMapKey(struct GBAInputMap* map, uint32_t type, int key) {
24 size_t m;
25 struct GBAInputMapImpl* impl = 0;
26 for (m = 0; m < map->numMaps; ++m) {
27 if (map->maps[m].type == type) {
28 impl = &map->maps[m];
29 break;
30 }
31 }
32 if (!impl || !impl->map) {
33 return GBA_KEY_NONE;
34 }
35
36 for (m = 0; m < GBA_KEY_MAX; ++m) {
37 if (impl->map[m] == key) {
38 return m;
39 }
40 }
41 return GBA_KEY_NONE;
42}
43
44void GBAInputBindKey(struct GBAInputMap* map, uint32_t type, int key, enum GBAKey input) {
45 struct GBAInputMapImpl* impl = 0;
46 if (map->numMaps == 0) {
47 map->maps = malloc(sizeof(*map->maps));
48 map->numMaps = 1;
49 impl = &map->maps[0];
50 impl->type = type;
51 impl->map = calloc(GBA_KEY_MAX, sizeof(enum GBAKey));
52 } else {
53 size_t m;
54 for (m = 0; m < map->numMaps; ++m) {
55 if (map->maps[m].type == type) {
56 impl = &map->maps[m];
57 break;
58 }
59 }
60 }
61 if (!impl) {
62 size_t m;
63 for (m = 0; m < map->numMaps; ++m) {
64 if (!map->maps[m].type) {
65 impl = &map->maps[m];
66 break;
67 }
68 }
69 if (impl) {
70 impl->type = type;
71 impl->map = calloc(GBA_KEY_MAX, sizeof(enum GBAKey));
72 } else {
73 map->maps = realloc(map->maps, sizeof(*map->maps) * map->numMaps * 2);
74 for (m = map->numMaps * 2 - 1; m > map->numMaps; --m) {
75 map->maps[m].type = 0;
76 map->maps[m].map = 0;
77 }
78 map->numMaps *= 2;
79 impl = &map->maps[m];
80 impl->type = type;
81 impl->map = calloc(GBA_KEY_MAX, sizeof(enum GBAKey));
82 }
83 }
84 impl->map[input] = key;
85}