fix: don't crash if joystick doesn't have expected inputs

My laptop and desktop both have devices that appear as joysticks, but are
very clearly not. Before this change this meant that I couldn't test the
game on desktop after adding joystick support.
dev
LeRoyce Pearson 2024-02-29 13:13:09 -07:00
parent e2a52dad0b
commit dbe5a92b54
1 changed files with 13 additions and 5 deletions

View File

@ -249,7 +249,7 @@ pub fn main() !void {
input_state.up = input_state.up or gamepad_state.buttons[seizer.backend.glfw.c.GLFW_GAMEPAD_BUTTON_DPAD_UP] != 0;
input_state.down = input_state.down or gamepad_state.buttons[seizer.backend.glfw.c.GLFW_GAMEPAD_BUTTON_DPAD_DOWN] != 0;
}
} else if (seizer.backend.glfw.c.glfwJoystickPresent(seizer.backend.glfw.c.GLFW_JOYSTICK_1) != 0) {
} else if (seizer.backend.glfw.c.glfwJoystickPresent(seizer.backend.glfw.c.GLFW_JOYSTICK_1) != 0) handle_joystick: {
var controller_input_state = InputState{
.left = false,
.right = false,
@ -259,10 +259,20 @@ pub fn main() !void {
.undo = false,
};
// get hats and buttons
var hats_count: c_int = undefined;
const hats_ptr = seizer.backend.glfw.c.glfwGetJoystickHats(seizer.backend.glfw.c.GLFW_JOYSTICK_1, &hats_count);
const hats_ptr = seizer.backend.glfw.c.glfwGetJoystickHats(seizer.backend.glfw.c.GLFW_JOYSTICK_1, &hats_count) orelse break :handle_joystick;
const hats = hats_ptr[0..@intCast(hats_count)];
var buttons_count: c_int = undefined;
const buttons_ptr = seizer.backend.glfw.c.glfwGetJoystickButtons(seizer.backend.glfw.c.GLFW_JOYSTICK_1, &buttons_count) orelse break :handle_joystick;
const buttons = buttons_ptr[0..@intCast(buttons_count)];
// check that the joystick has enough inputs
if (hats.len < 1) break :handle_joystick;
if (buttons.len < 2) break :handle_joystick;
// handle hat inputs
const HAT_UP = seizer.backend.glfw.c.GLFW_HAT_UP;
const HAT_RIGHT = seizer.backend.glfw.c.GLFW_HAT_RIGHT;
const HAT_DOWN = seizer.backend.glfw.c.GLFW_HAT_DOWN;
@ -273,9 +283,7 @@ pub fn main() !void {
controller_input_state.up = hats[0] & HAT_UP != 0;
controller_input_state.down = hats[0] & HAT_DOWN != 0;
var buttons_count: c_int = undefined;
const buttons_ptr = seizer.backend.glfw.c.glfwGetJoystickButtons(seizer.backend.glfw.c.GLFW_JOYSTICK_1, &buttons_count);
const buttons = buttons_ptr[0..@intCast(buttons_count)];
// handle button inputs
controller_input_state.action = buttons[0] != 0;
controller_input_state.undo = buttons[1] != 0;