shithub: cstory

Download patch

ref: 5bb839136bab80e2c4605e40442edb138ecb83b5
parent: 40464a9fc096a106c2be1819810e92cbd1eca160
author: Clownacy <Clownacy@users.noreply.github.com>
date: Fri Apr 3 12:53:58 EDT 2020

Added controller support to GLFW3 backend

--- a/src/Backends/GLFW3/Controller.cpp
+++ b/src/Backends/GLFW3/Controller.cpp
@@ -1,7 +1,17 @@
 #include "../Controller.h"
 
+#define GLFW_INCLUDE_NONE
+#include <GLFW/glfw3.h>
+
 #include "../../WindowsWrapper.h"
 
+#define DEADZONE (10000.0f / 32767.0f)
+
+static BOOL joystick_connected;
+static int connected_joystick_id;
+static float joystick_neutral_x;
+static float joystick_neutral_y;
+
 void ControllerBackend_Deinit(void)
 {
 	
@@ -9,17 +19,63 @@
 
 BOOL ControllerBackend_Init(void)
 {
-	return FALSE;
+	for (int i = GLFW_JOYSTICK_1; i < GLFW_JOYSTICK_LAST; ++i)
+	{
+		if (glfwJoystickPresent(i) == GLFW_TRUE && glfwJoystickIsGamepad(i) == GLFW_TRUE)
+		{
+			joystick_connected = TRUE;
+			connected_joystick_id = i;
+			break;
+		}
+	}
+
+	return joystick_connected;
 }
 
 BOOL ControllerBackend_GetJoystickStatus(JOYSTICK_STATUS *status)
 {
-	(void)status;
+	if (!joystick_connected)
+		return FALSE;
 
-	return FALSE;
+	if (glfwJoystickPresent(connected_joystick_id) == GLFW_FALSE || glfwJoystickIsGamepad(connected_joystick_id) == GLFW_FALSE)
+		return FALSE;
+
+	int total_axis;
+	const float *axis = glfwGetJoystickAxes(connected_joystick_id, &total_axis);
+
+	status->bLeft = axis[0] < joystick_neutral_x - DEADZONE;
+	status->bRight = axis[0] > joystick_neutral_x + DEADZONE;
+	status->bUp = axis[1] < joystick_neutral_x - DEADZONE;
+	status->bDown = axis[1] > joystick_neutral_x + DEADZONE;
+
+	int total_buttons;
+	const unsigned char *buttons = glfwGetJoystickButtons(connected_joystick_id, &total_buttons);
+
+	if (total_buttons > 32)
+		total_buttons = 32;
+
+	for (int i = 0; i < total_buttons; ++i)
+		status->bButton[i] = buttons[i] == GLFW_PRESS;
+
+	for (int i = total_buttons; i < 32; ++i)
+		status->bButton[i] = FALSE;
+
+	return TRUE;
 }
 
 BOOL ControllerBackend_ResetJoystickStatus(void)
 {
-	return FALSE;
+	if (!joystick_connected)
+		return FALSE;
+
+	if (glfwJoystickPresent(connected_joystick_id) == GLFW_FALSE || glfwJoystickIsGamepad(connected_joystick_id) == GLFW_FALSE)
+		return FALSE;
+
+	int total_axis;
+	const float *axis = glfwGetJoystickAxes(connected_joystick_id, &total_axis);
+
+	joystick_neutral_x = axis[0];
+	joystick_neutral_y = axis[1];
+
+	return TRUE;
 }