comparison libmlk-core/mlk/core/gamepad.c @ 443:dfc65293d984

core: initial gamepad support
author David Demelier <markand@malikania.fr>
date Sat, 21 Jan 2023 20:20:34 +0100
parents
children 773a082f0b91
comparison
equal deleted inserted replaced
442:9c3b3935f0aa 443:dfc65293d984
1 /*
2 * gamepad.c -- game controller support
3 *
4 * Copyright (c) 2020-2022 David Demelier <markand@malikania.fr>
5 *
6 * Permission to use, copy, modify, and/or distribute this software for any
7 * purpose with or without fee is hereby granted, provided that the above
8 * copyright notice and this permission notice appear in all copies.
9 *
10 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17 */
18
19 #include <assert.h>
20 #include <string.h>
21
22 #include <SDL.h>
23
24 #include "err.h"
25 #include "gamepad.h"
26
27 int
28 mlk_gamepad_open(struct mlk_gamepad *pad, int idx)
29 {
30 assert(pad);
31
32 memset(pad, 0, sizeof (*pad));
33
34 if (!(pad->handle = SDL_GameControllerOpen(idx)))
35 return MLK_ERR_SDL;
36
37 return 0;
38 }
39
40 void
41 mlk_gamepad_finish(struct mlk_gamepad *pad)
42 {
43 assert(pad);
44
45 if (pad->handle)
46 SDL_GameControllerClose(pad->handle);
47
48 memset(pad, 0, sizeof (*pad));
49 }
50
51 int
52 mlk_gamepad_iter_begin(struct mlk_gamepad_iter *it)
53 {
54 assert(it);
55
56 memset(it, 0, sizeof (*it));
57 it->idx = -1;
58
59 if ((it->end = SDL_NumJoysticks()) < 0) {
60 it->end = 0;
61 return MLK_ERR_SDL;
62 }
63
64 return 0;
65 }
66
67 int
68 mlk_gamepad_iter_next(struct mlk_gamepad_iter *it)
69 {
70 /*
71 * Go to the next gamepad, we need to iterate because SDL can combines
72 * joystick and game controllers with the same API.
73 */
74 for (++it->idx; it->idx < it->end && !SDL_IsGameController(it->idx); ++it->idx)
75 continue;
76
77 /* End of iteration. */
78 if (it->idx >= it->end) {
79 memset(it, 0, sizeof (*it));
80 return 0;
81 }
82
83 it->name = SDL_GameControllerNameForIndex(it->idx);
84
85 return 1;
86 }