From dbe5a92b540a38fa9118e8abbcf5e93ceed7d080 Mon Sep 17 00:00:00 2001 From: geemili Date: Thu, 29 Feb 2024 13:13:09 -0700 Subject: [PATCH] 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. --- src/main.zig | 18 +++++++++++++----- 1 file changed, 13 insertions(+), 5 deletions(-) diff --git a/src/main.zig b/src/main.zig index 43f3d88..d34b0e1 100644 --- a/src/main.zig +++ b/src/main.zig @@ -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;