1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
|
#include <SDL3/SDL_log.h>
#include "player.h"
struct pw_players *pw_players_init(void) {
struct pw_players *players = SDL_malloc(sizeof(*players));
if (!players) {
return NULL;
}
SDL_zerop(players);
return players;
}
void pw_players_free(struct pw_players *players) {
if (!players) {
SDL_InvalidParamError("players");
return;
}
for (size_t i = 0; i < PW_PLAYERS_MAX; ++i) {
SDL_Gamepad *gamepad = players->gamepads[i];
if (gamepad) {
SDL_CloseGamepad(gamepad);
}
}
SDL_free(players);
}
static bool add_gamepad(struct pw_players *players,
SDL_GamepadDeviceEvent *event) {
size_t i;
for (i = 0; i < PW_PLAYERS_MAX; ++i) {
if (players->gamepads[i] == NULL) {
break;
}
}
if (i >= PW_PLAYERS_MAX) {
SDL_LogDebug(0, "connected gamepad for too many players");
return true;
}
players->gamepads[i] = SDL_OpenGamepad(event->which);
if (!players->gamepads[i]) {
return false;
}
SDL_LogDebug(0, "connected gamepad for player %zu", i + 1);
return true;
}
static bool remove_gamepad(struct pw_players *players,
SDL_GamepadDeviceEvent *event) {
size_t i = pw_player_find(players, event->which);
if (i >= PW_PLAYERS_MAX) {
SDL_LogDebug(0, "disconnected gamepad for unknown player");
return true;
}
SDL_CloseGamepad(players->gamepads[i]);
players->gamepads[i] = NULL;
SDL_LogDebug(0, "disconnected gamepad for player %zu", i + 1);
return true;
}
bool pw_players_event(struct pw_players *players, SDL_Event *event) {
if (!players) {
return SDL_InvalidParamError("players");
}
if (!event) {
return SDL_InvalidParamError("event");
}
switch (event->type) {
case SDL_EVENT_GAMEPAD_ADDED:
return add_gamepad(players, &event->gdevice);
case SDL_EVENT_GAMEPAD_REMOVED:
return remove_gamepad(players, &event->gdevice);
default:
return true;
}
}
size_t pw_players_status(struct pw_players *players,
bool connected[static PW_PLAYERS_MAX]) {
if (!players) {
SDL_InvalidParamError("players");
SDL_memset(connected, 0, sizeof(bool[PW_PLAYERS_MAX]));
return 0;
}
size_t count = 0;
for (size_t i = 0; i < PW_PLAYERS_MAX; i++) {
connected[i] = players->gamepads[i];
if (connected[i]) {
++count;
}
}
return count;
}
size_t pw_player_find(struct pw_players *players, SDL_JoystickID gamepad) {
for (size_t i = 0; i < PW_PLAYERS_MAX; i++) {
if (players->gamepads[i] &&
SDL_GetGamepadID(players->gamepads[i]) == gamepad) {
return i;
}
}
return PW_PLAYERS_MAX;
}
|