From 0c4b2c4a81198c79ad2815c847f0b297ff85e798 Mon Sep 17 00:00:00 2001 From: Michael Date: Tue, 10 Oct 2023 11:50:57 -0400 Subject: [PATCH 01/33] Update `PLATFORM_DRM` implementation of `GetGamepadAxisCount` --- src/rcore_drm.c | 593 ++++++++++++++++++++++-------------------------- 1 file changed, 268 insertions(+), 325 deletions(-) diff --git a/src/rcore_drm.c b/src/rcore_drm.c index ccf44feb3..66d6d7989 100644 --- a/src/rcore_drm.c +++ b/src/rcore_drm.c @@ -1,6 +1,6 @@ /********************************************************************************************** * -* rcore_drm - Functions to manage window, graphics device and inputs +* rcore_drm - Functions to manage window, graphics device and inputs * * PLATFORM: DRM * - Raspberry Pi 0-5 @@ -17,10 +17,8 @@ * - TRACELOG() function is located in raylib [utils] module * * CONFIGURATION: -* #define SUPPORT_SSH_KEYBOARD_RPI (Raspberry Pi only) -* Reconfigure standard input to receive key inputs, works with SSH connection. -* WARNING: Reconfiguring standard input could lead to undesired effects, like breaking other -* running processes orblocking the device if not restored properly. Use with care. +* #define RCORE_DRM_CUSTOM_FLAG +* Custom flag for rcore on PLATFORM_DRM -not used- * * DEPENDENCIES: * gestures - Gestures system for touch-ready devices (or simulated from mouse inputs) @@ -49,93 +47,15 @@ #include "rcore.h" -#include // POSIX file control definitions - open(), creat(), fcntl() -#include // POSIX standard function definitions - read(), close(), STDIN_FILENO -#include // POSIX terminal control definitions - tcgetattr(), tcsetattr() -#include // POSIX threads management (inputs reading) -#include // POSIX directory browsing - -#include // Required for: ioctl() - UNIX System call for device-specific input/output operations -#include // Linux: KDSKBMODE, K_MEDIUMRAM constants definition -#include // Linux: Keycodes constants definition (KEY_A, ...) -#include // Linux: Joystick support library - -#include // Generic Buffer Management (native platform for EGL on DRM) -#include // Direct Rendering Manager user-level library interface -#include // Direct Rendering Manager mode setting (KMS) interface - -#include "EGL/egl.h" // Native platform windowing system interface -#include "EGL/eglext.h" // EGL extensions - -//---------------------------------------------------------------------------------- -// Defines and Macros -//---------------------------------------------------------------------------------- -#define USE_LAST_TOUCH_DEVICE // When multiple touchscreens are connected, only use the one with the highest event number - -#define DEFAULT_GAMEPAD_DEV "/dev/input/js" // Gamepad input (base dev for all gamepads: js0, js1, ...) -#define DEFAULT_EVDEV_PATH "/dev/input/" // Path to the linux input events - //---------------------------------------------------------------------------------- // Types and Structures Definition //---------------------------------------------------------------------------------- - -typedef struct { - pthread_t threadId; // Event reading thread id - - int fd; // File descriptor to the device it is assigned to - int eventNum; // Number of 'event' device - Rectangle absRange; // Range of values for absolute pointing devices (touchscreens) - int touchSlot; // Hold the touch slot number of the currently being sent multitouch block - bool isMouse; // True if device supports relative X Y movements - bool isTouch; // True if device supports absolute X Y movements and has BTN_TOUCH - bool isMultitouch; // True if device supports multiple absolute movevents and has BTN_TOUCH - bool isKeyboard; // True if device has letter keycodes - bool isGamepad; // True if device has gamepad buttons -} InputEventWorker; - -typedef struct { - // Display data - int fd; // File descriptor for /dev/dri/... - drmModeConnector *connector; // Direct Rendering Manager (DRM) mode connector - drmModeCrtc *crtc; // CRT Controller - int modeIndex; // Index of the used mode of connector->modes - struct gbm_device *gbmDevice; // GBM device - struct gbm_surface *gbmSurface; // GBM surface - struct gbm_bo *prevBO; // Previous GBM buffer object (during frame swapping) - uint32_t prevFB; // Previous GBM framebufer (during frame swapping) - - EGLDisplay device; // Native display device (physical screen connection) - EGLSurface surface; // Surface to draw on, framebuffers (connected to context) - EGLContext context; // Graphic context, mode in which drawing can be done - EGLConfig config; // Graphic config - - // Input data - InputEventWorker eventWorker[10]; // List of worker threads for every monitored "/dev/input/event" - - // Keyboard data - int defaultKeyboardMode; // Default keyboard mode - bool eventKeyboardMode; // Keyboard in event mode - int defaultFileFlags; // Default IO file flags - struct termios defaultSettings; // Default keyboard settings - int keyboardFd; // File descriptor for the evdev keyboard - - // Mouse data - Vector2 eventWheelMove; // Registers the event mouse wheel variation - // NOTE: currentButtonState[] can't be written directly due to multithreading, app could miss the update - char currentButtonStateEvdev[MAX_MOUSE_BUTTONS]; // Holds the new mouse state for the next polling event to grab - - // Gamepad data - pthread_t gamepadThreadId; // Gamepad reading thread id - int gamepadStreamFd[MAX_GAMEPADS]; // Gamepad device file descriptor - -} PlatformData; +//... //---------------------------------------------------------------------------------- // Global Variables Definition //---------------------------------------------------------------------------------- -extern CoreData CORE; // Global CORE state context - -static PlatformData platform = { 0 }; // Platform specific data +extern CoreData CORE; // Global CORE state context //---------------------------------------------------------------------------------- // Module Internal Functions Declaration @@ -166,7 +86,7 @@ static int FindNearestConnectorMode(const drmModeConnector *connector, uint widt // NOTE: Functions declaration is provided by raylib.h //---------------------------------------------------------------------------------- -// Module Functions Definition: Window and Graphics Device +// Module Functions Definition //---------------------------------------------------------------------------------- // Initialize window and OpenGL context @@ -220,14 +140,19 @@ void InitWindow(int width, int height, const char *title) CORE.Window.ready = InitGraphicsDevice(width, height); // If graphic device is no properly initialized, we end program - if (!CORE.Window.ready) { TRACELOG(LOG_FATAL, "PLATFORM: Failed to initialize graphic device"); return; } - else SetWindowPosition(GetMonitorWidth(GetCurrentMonitor()) / 2 - CORE.Window.screen.width / 2, GetMonitorHeight(GetCurrentMonitor()) / 2 - CORE.Window.screen.height / 2); + if (!CORE.Window.ready) + { + TRACELOG(LOG_FATAL, "Failed to initialize Graphic Device"); + return; + } + else + SetWindowPosition(GetMonitorWidth(GetCurrentMonitor()) / 2 - CORE.Window.screen.width / 2, GetMonitorHeight(GetCurrentMonitor()) / 2 - CORE.Window.screen.height / 2); // Initialize hi-res timer InitTimer(); // Initialize random seed - SetRandomSeed((unsigned int)time(NULL)); + srand((unsigned int)time(NULL)); // Initialize base path for storage CORE.Storage.basePath = GetWorkingDirectory(); @@ -269,20 +194,15 @@ void InitWindow(int width, int height, const char *title) } #endif -#if defined(SUPPORT_EVENTS_AUTOMATION) - events = (AutomationEvent *)RL_CALLOC(MAX_CODE_AUTOMATION_EVENTS, sizeof(AutomationEvent)); - CORE.Time.frameCounter = 0; -#endif - - // Platform specific init window - //-------------------------------------------------------------- // Initialize raw input system InitEvdevInput(); // Evdev inputs initialization InitGamepad(); // Gamepad init InitKeyboard(); // Keyboard init (stdin) - //-------------------------------------------------------------- - - TRACELOG(LOG_INFO, "PLATFORM: DRM: Application initialized successfully"); + +#if defined(SUPPORT_EVENTS_AUTOMATION) + events = (AutomationEvent *)RL_CALLOC(MAX_CODE_AUTOMATION_EVENTS, sizeof(AutomationEvent)); + CORE.Time.frameCounter = 0; +#endif } // Close window and unload OpenGL context @@ -307,69 +227,67 @@ void CloseWindow(void) timeEndPeriod(1); // Restore time period #endif - // Platform specific close window - //-------------------------------------------------------------- - if (platform.prevFB) + if (CORE.Window.prevFB) { - drmModeRmFB(platform.fd, platform.prevFB); - platform.prevFB = 0; + drmModeRmFB(CORE.Window.fd, CORE.Window.prevFB); + CORE.Window.prevFB = 0; } - if (platform.prevBO) + if (CORE.Window.prevBO) { - gbm_surface_release_buffer(platform.gbmSurface, platform.prevBO); - platform.prevBO = NULL; + gbm_surface_release_buffer(CORE.Window.gbmSurface, CORE.Window.prevBO); + CORE.Window.prevBO = NULL; } - if (platform.gbmSurface) + if (CORE.Window.gbmSurface) { - gbm_surface_destroy(platform.gbmSurface); - platform.gbmSurface = NULL; + gbm_surface_destroy(CORE.Window.gbmSurface); + CORE.Window.gbmSurface = NULL; } - if (platform.gbmDevice) + if (CORE.Window.gbmDevice) { - gbm_device_destroy(platform.gbmDevice); - platform.gbmDevice = NULL; + gbm_device_destroy(CORE.Window.gbmDevice); + CORE.Window.gbmDevice = NULL; } - if (platform.crtc) + if (CORE.Window.crtc) { - if (platform.connector) + if (CORE.Window.connector) { - drmModeSetCrtc(platform.fd, platform.crtc->crtc_id, platform.crtc->buffer_id, - platform.crtc->x, platform.crtc->y, &platform.connector->connector_id, 1, &platform.crtc->mode); - drmModeFreeConnector(platform.connector); - platform.connector = NULL; + drmModeSetCrtc(CORE.Window.fd, CORE.Window.crtc->crtc_id, CORE.Window.crtc->buffer_id, + CORE.Window.crtc->x, CORE.Window.crtc->y, &CORE.Window.connector->connector_id, 1, &CORE.Window.crtc->mode); + drmModeFreeConnector(CORE.Window.connector); + CORE.Window.connector = NULL; } - drmModeFreeCrtc(platform.crtc); - platform.crtc = NULL; + drmModeFreeCrtc(CORE.Window.crtc); + CORE.Window.crtc = NULL; } - if (platform.fd != -1) + if (CORE.Window.fd != -1) { - close(platform.fd); - platform.fd = -1; + close(CORE.Window.fd); + CORE.Window.fd = -1; } // Close surface, context and display - if (platform.device != EGL_NO_DISPLAY) + if (CORE.Window.device != EGL_NO_DISPLAY) { - if (platform.surface != EGL_NO_SURFACE) + if (CORE.Window.surface != EGL_NO_SURFACE) { - eglDestroySurface(platform.device, platform.surface); - platform.surface = EGL_NO_SURFACE; + eglDestroySurface(CORE.Window.device, CORE.Window.surface); + CORE.Window.surface = EGL_NO_SURFACE; } - if (platform.context != EGL_NO_CONTEXT) + if (CORE.Window.context != EGL_NO_CONTEXT) { - eglDestroyContext(platform.device, platform.context); - platform.context = EGL_NO_CONTEXT; + eglDestroyContext(CORE.Window.device, CORE.Window.context); + CORE.Window.context = EGL_NO_CONTEXT; } - eglTerminate(platform.device); - platform.device = EGL_NO_DISPLAY; + eglTerminate(CORE.Window.device); + CORE.Window.device = EGL_NO_DISPLAY; } // Wait for mouse and gamepad threads to finish before closing @@ -379,22 +297,21 @@ void CloseWindow(void) CORE.Window.shouldClose = true; // Added to force threads to exit when the close window is called // Close the evdev keyboard - if (platform.keyboardFd != -1) + if (CORE.Input.Keyboard.fd != -1) { - close(platform.keyboardFd); - platform.keyboardFd = -1; + close(CORE.Input.Keyboard.fd); + CORE.Input.Keyboard.fd = -1; } - for (int i = 0; i < sizeof(platform.eventWorker)/sizeof(InputEventWorker); ++i) + for (int i = 0; i < sizeof(CORE.Input.eventWorker)/sizeof(InputEventWorker); ++i) { - if (platform.eventWorker[i].threadId) + if (CORE.Input.eventWorker[i].threadId) { - pthread_join(platform.eventWorker[i].threadId, NULL); + pthread_join(CORE.Input.eventWorker[i].threadId, NULL); } } - if (platform.gamepadThreadId) pthread_join(platform.gamepadThreadId, NULL); - //-------------------------------------------------------------- + if (CORE.Input.Gamepad.threadId) pthread_join(CORE.Input.Gamepad.threadId, NULL); #if defined(SUPPORT_EVENTS_AUTOMATION) RL_FREE(events); @@ -445,55 +362,55 @@ bool IsWindowResized(void) // Toggle fullscreen mode void ToggleFullscreen(void) { - TRACELOG(LOG_WARNING, "ToggleFullscreen() not available on target platform"); + TRACELOG(LOG_WARNING, "ToggleFullscreen() not available on PLATFORM_DRM"); } // Set window state: maximized, if resizable void MaximizeWindow(void) { - TRACELOG(LOG_WARNING, "MaximizeWindow() not available on target platform"); + TRACELOG(LOG_WARNING, "MaximizeWindow() not available on PLATFORM_DRM"); } // Set window state: minimized void MinimizeWindow(void) { - TRACELOG(LOG_WARNING, "MinimizeWindow() not available on target platform"); + TRACELOG(LOG_WARNING, "MinimizeWindow() not available on PLATFORM_DRM"); } // Set window state: not minimized/maximized void RestoreWindow(void) { - TRACELOG(LOG_WARNING, "RestoreWindow() not available on target platform"); + TRACELOG(LOG_WARNING, "RestoreWindow() not available on PLATFORM_DRM"); } // Toggle borderless windowed mode void ToggleBorderlessWindowed(void) { - TRACELOG(LOG_WARNING, "ToggleBorderlessWindowed() not available on target platform"); + TRACELOG(LOG_WARNING, "ToggleBorderlessWindowed() not available on PLATFORM_DRM"); } // Set window configuration state using flags void SetWindowState(unsigned int flags) { - TRACELOG(LOG_WARNING, "SetWindowState() not available on target platform"); + TRACELOG(LOG_WARNING, "SetWindowState() not available on PLATFORM_DRM"); } // Clear window configuration state flags void ClearWindowState(unsigned int flags) { - TRACELOG(LOG_WARNING, "ClearWindowState() not available on target platform"); + TRACELOG(LOG_WARNING, "ClearWindowState() not available on PLATFORM_DRM"); } // Set icon for window void SetWindowIcon(Image image) { - TRACELOG(LOG_WARNING, "SetWindowIcon() not available on target platform"); + TRACELOG(LOG_WARNING, "SetWindowIcon() not available on PLATFORM_DRM"); } // Set icon for window void SetWindowIcons(Image *images, int count) { - TRACELOG(LOG_WARNING, "SetWindowIcons() not available on target platform"); + TRACELOG(LOG_WARNING, "SetWindowIcons() not available on PLATFORM_DRM"); } // Set title for window @@ -505,13 +422,13 @@ void SetWindowTitle(const char *title) // Set window position on screen (windowed mode) void SetWindowPosition(int x, int y) { - TRACELOG(LOG_WARNING, "SetWindowPosition() not available on target platform"); + TRACELOG(LOG_WARNING, "SetWindowPosition() not available on PLATFORM_DRM"); } // Set monitor for the current window void SetWindowMonitor(int monitor) { - TRACELOG(LOG_WARNING, "SetWindowMonitor() not available on target platform"); + TRACELOG(LOG_WARNING, "SetWindowMonitor() not available on PLATFORM_DRM"); } // Set window minimum dimensions (FLAG_WINDOW_RESIZABLE) @@ -531,74 +448,74 @@ void SetWindowMaxSize(int width, int height) // Set window dimensions void SetWindowSize(int width, int height) { - TRACELOG(LOG_WARNING, "SetWindowSize() not available on target platform"); + TRACELOG(LOG_WARNING, "SetWindowSize() not available on PLATFORM_DRM"); } // Set window opacity, value opacity is between 0.0 and 1.0 void SetWindowOpacity(float opacity) { - TRACELOG(LOG_WARNING, "SetWindowOpacity() not available on target platform"); + TRACELOG(LOG_WARNING, "SetWindowOpacity() not available on PLATFORM_DRM"); } // Set window focused void SetWindowFocused(void) { - TRACELOG(LOG_WARNING, "SetWindowFocused() not available on target platform"); + TRACELOG(LOG_WARNING, "SetWindowFocused() not available on PLATFORM_DRM"); } // Get native window handle void *GetWindowHandle(void) { - TRACELOG(LOG_WARNING, "GetWindowHandle() not implemented on target platform"); + TRACELOG(LOG_WARNING, "GetWindowHandle() not implemented on PLATFORM_DRM"); return NULL; } // Get number of monitors int GetMonitorCount(void) { - TRACELOG(LOG_WARNING, "GetMonitorCount() not implemented on target platform"); + TRACELOG(LOG_WARNING, "GetMonitorCount() not implemented on PLATFORM_DRM"); return 1; } // Get number of monitors int GetCurrentMonitor(void) { - TRACELOG(LOG_WARNING, "GetCurrentMonitor() not implemented on target platform"); + TRACELOG(LOG_WARNING, "GetCurrentMonitor() not implemented on PLATFORM_DRM"); return 0; } // Get selected monitor position Vector2 GetMonitorPosition(int monitor) { - TRACELOG(LOG_WARNING, "GetMonitorPosition() not implemented on target platform"); + TRACELOG(LOG_WARNING, "GetMonitorPosition() not implemented on PLATFORM_DRM"); return (Vector2){ 0, 0 }; } // Get selected monitor width (currently used by monitor) int GetMonitorWidth(int monitor) { - TRACELOG(LOG_WARNING, "GetMonitorWidth() not implemented on target platform"); + TRACELOG(LOG_WARNING, "GetMonitorWidth() not implemented on PLATFORM_DRM"); return 0; } // Get selected monitor height (currently used by monitor) int GetMonitorHeight(int monitor) { - TRACELOG(LOG_WARNING, "GetMonitorHeight() not implemented on target platform"); + TRACELOG(LOG_WARNING, "GetMonitorHeight() not implemented on PLATFORM_DRM"); return 0; } // Get selected monitor physical width in millimetres int GetMonitorPhysicalWidth(int monitor) { - TRACELOG(LOG_WARNING, "GetMonitorPhysicalWidth() not implemented on target platform"); + TRACELOG(LOG_WARNING, "GetMonitorPhysicalWidth() not implemented on PLATFORM_DRM"); return 0; } // Get selected monitor physical height in millimetres int GetMonitorPhysicalHeight(int monitor) { - TRACELOG(LOG_WARNING, "GetMonitorPhysicalHeight() not implemented on target platform"); + TRACELOG(LOG_WARNING, "GetMonitorPhysicalHeight() not implemented on PLATFORM_DRM"); return 0; } @@ -606,19 +523,19 @@ int GetMonitorPhysicalHeight(int monitor) int GetMonitorRefreshRate(int monitor) { int refresh = 0; - - if ((platform.connector) && (platform.modeIndex >= 0)) + + if ((CORE.Window.connector) && (CORE.Window.modeIndex >= 0)) { - refresh = platform.connector->modes[platform.modeIndex].vrefresh; + refresh = CORE.Window.connector->modes[CORE.Window.modeIndex].vrefresh; } - + return refresh; } // Get the human-readable, UTF-8 encoded name of the selected monitor const char *GetMonitorName(int monitor) { - TRACELOG(LOG_WARNING, "GetMonitorName() not implemented on target platform"); + TRACELOG(LOG_WARNING, "GetMonitorName() not implemented on PLATFORM_DRM"); return ""; } @@ -637,14 +554,14 @@ Vector2 GetWindowScaleDPI(void) // Set clipboard text content void SetClipboardText(const char *text) { - TRACELOG(LOG_WARNING, "SetClipboardText() not implemented on target platform"); + TRACELOG(LOG_WARNING, "SetClipboardText() not implemented on PLATFORM_DRM"); } // Get clipboard text content // NOTE: returned string is allocated and freed by GLFW const char *GetClipboardText(void) { - TRACELOG(LOG_WARNING, "GetClipboardText() not implemented on target platform"); + TRACELOG(LOG_WARNING, "GetClipboardText() not implemented on PLATFORM_DRM"); return NULL; } @@ -678,40 +595,6 @@ void DisableCursor(void) CORE.Input.Mouse.cursorHidden = true; } -// Swap back buffer with front buffer (screen drawing) -void SwapScreenBuffer(void) -{ - eglSwapBuffers(platform.device, platform.surface); - - if (!platform.gbmSurface || (-1 == platform.fd) || !platform.connector || !platform.crtc) TRACELOG(LOG_ERROR, "DISPLAY: DRM initialization failed to swap"); - - struct gbm_bo *bo = gbm_surface_lock_front_buffer(platform.gbmSurface); - if (!bo) TRACELOG(LOG_ERROR, "DISPLAY: Failed GBM to lock front buffer"); - - uint32_t fb = 0; - int result = drmModeAddFB(platform.fd, platform.connector->modes[platform.modeIndex].hdisplay, platform.connector->modes[platform.modeIndex].vdisplay, 24, 32, gbm_bo_get_stride(bo), gbm_bo_get_handle(bo).u32, &fb); - if (result != 0) TRACELOG(LOG_ERROR, "DISPLAY: drmModeAddFB() failed with result: %d", result); - - result = drmModeSetCrtc(platform.fd, platform.crtc->crtc_id, fb, 0, 0, &platform.connector->connector_id, 1, &platform.connector->modes[platform.modeIndex]); - if (result != 0) TRACELOG(LOG_ERROR, "DISPLAY: drmModeSetCrtc() failed with result: %d", result); - - if (platform.prevFB) - { - result = drmModeRmFB(platform.fd, platform.prevFB); - if (result != 0) TRACELOG(LOG_ERROR, "DISPLAY: drmModeRmFB() failed with result: %d", result); - } - - platform.prevFB = fb; - - if (platform.prevBO) gbm_surface_release_buffer(platform.gbmSurface, platform.prevBO); - - platform.prevBO = bo; -} - -//---------------------------------------------------------------------------------- -// Module Functions Definition: Misc -//---------------------------------------------------------------------------------- - // Get elapsed time measure in seconds since InitTimer() double GetTime(void) { @@ -721,10 +604,33 @@ double GetTime(void) unsigned long long int nanoSeconds = (unsigned long long int)ts.tv_sec*1000000000LLU + (unsigned long long int)ts.tv_nsec; time = (double)(nanoSeconds - CORE.Time.base)*1e-9; // Elapsed time since InitTimer() - + return time; } +// Takes a screenshot of current screen (saved a .png) +void TakeScreenshot(const char *fileName) +{ +#if defined(SUPPORT_MODULE_RTEXTURES) + // Security check to (partially) avoid malicious code on PLATFORM_WEB + if (strchr(fileName, '\'') != NULL) { TRACELOG(LOG_WARNING, "SYSTEM: Provided fileName could be potentially malicious, avoid [\'] character"); return; } + + Vector2 scale = GetWindowScaleDPI(); + unsigned char *imgData = rlReadScreenPixels((int)((float)CORE.Window.render.width*scale.x), (int)((float)CORE.Window.render.height*scale.y)); + Image image = { imgData, (int)((float)CORE.Window.render.width*scale.x), (int)((float)CORE.Window.render.height*scale.y), 1, PIXELFORMAT_UNCOMPRESSED_R8G8B8A8 }; + + char path[2048] = { 0 }; + strcpy(path, TextFormat("%s/%s", CORE.Storage.basePath, fileName)); + + ExportImage(image, path); // WARNING: Module required: rtextures + RL_FREE(imgData); + + TRACELOG(LOG_INFO, "SYSTEM: [%s] Screenshot taken successfully", path); +#else + TRACELOG(LOG_WARNING,"IMAGE: ExportImage() requires module: rtextures"); +#endif +} + // Open URL with default system browser (if available) // NOTE: This function is only safe to use if you control the URL given. // A user could craft a malicious string performing another action. @@ -732,13 +638,20 @@ double GetTime(void) // Ref: https://github.com/raysan5/raylib/issues/686 void OpenURL(const char *url) { - TRACELOG(LOG_WARNING, "OpenURL() not implemented on target platform"); + TRACELOG(LOG_WARNING, "OpenURL() not implemented on PLATFORM_DRM"); } //---------------------------------------------------------------------------------- // Module Functions Definition: Inputs //---------------------------------------------------------------------------------- +// Set a custom key to exit program +// NOTE: default exitKey is ESCAPE +void SetExitKey(int key) +{ + CORE.Input.Keyboard.exitKey = key; +} + // Get gamepad internal name id const char *GetGamepadName(int gamepad) { @@ -746,7 +659,7 @@ const char *GetGamepadName(int gamepad) if (CORE.Input.Gamepad.ready[gamepad]) { - ioctl(platform.gamepadStreamFd[gamepad], JSIOCGNAME(64), &CORE.Input.Gamepad.name[gamepad]); + ioctl(CORE.Input.Gamepad.streamId[gamepad], JSIOCGNAME(64), &CORE.Input.Gamepad.name[gamepad]); name = CORE.Input.Gamepad.name[gamepad]; } @@ -756,18 +669,13 @@ const char *GetGamepadName(int gamepad) // Get gamepad axis count int GetGamepadAxisCount(int gamepad) { - int axisCount = 0; - - if (CORE.Input.Gamepad.ready[gamepad]) ioctl(platform.gamepadStreamFd[gamepad], JSIOCGAXES, &axisCount); - CORE.Input.Gamepad.axisCount = axisCount; - return CORE.Input.Gamepad.axisCount; } // Set internal gamepad mappings int SetGamepadMappings(const char *mappings) { - TRACELOG(LOG_WARNING, "SetGamepadMappings() not implemented on target platform"); + TRACELOG(LOG_WARNING, "SetGamepadMappings() not implemented on PLATFORM_DRM"); return 0; } @@ -815,7 +723,7 @@ float GetMouseWheelMove(void) // Set mouse cursor void SetMouseCursor(int cursor) { - TRACELOG(LOG_WARNING, "SetMouseCursor() not implemented on target platform"); + TRACELOG(LOG_WARNING, "SetMouseCursor() not implemented on PLATFORM_DRM"); } // Get touch position X for touch point 0 (relative to screen size) @@ -834,13 +742,43 @@ int GetTouchY(void) Vector2 GetTouchPosition(int index) { Vector2 position = { -1.0f, -1.0f }; - + if (index < MAX_TOUCH_POINTS) position = CORE.Input.Touch.position[index]; else TRACELOG(LOG_WARNING, "INPUT: Required touch point out of range (Max touch points: %i)", MAX_TOUCH_POINTS); - + return position; } +// Swap back buffer with front buffer (screen drawing) +void SwapScreenBuffer(void) +{ + eglSwapBuffers(CORE.Window.device, CORE.Window.surface); + + if (!CORE.Window.gbmSurface || (-1 == CORE.Window.fd) || !CORE.Window.connector || !CORE.Window.crtc) TRACELOG(LOG_ERROR, "DISPLAY: DRM initialization failed to swap"); + + struct gbm_bo *bo = gbm_surface_lock_front_buffer(CORE.Window.gbmSurface); + if (!bo) TRACELOG(LOG_ERROR, "DISPLAY: Failed GBM to lock front buffer"); + + uint32_t fb = 0; + int result = drmModeAddFB(CORE.Window.fd, CORE.Window.connector->modes[CORE.Window.modeIndex].hdisplay, CORE.Window.connector->modes[CORE.Window.modeIndex].vdisplay, 24, 32, gbm_bo_get_stride(bo), gbm_bo_get_handle(bo).u32, &fb); + if (result != 0) TRACELOG(LOG_ERROR, "DISPLAY: drmModeAddFB() failed with result: %d", result); + + result = drmModeSetCrtc(CORE.Window.fd, CORE.Window.crtc->crtc_id, fb, 0, 0, &CORE.Window.connector->connector_id, 1, &CORE.Window.connector->modes[CORE.Window.modeIndex]); + if (result != 0) TRACELOG(LOG_ERROR, "DISPLAY: drmModeSetCrtc() failed with result: %d", result); + + if (CORE.Window.prevFB) + { + result = drmModeRmFB(CORE.Window.fd, CORE.Window.prevFB); + if (result != 0) TRACELOG(LOG_ERROR, "DISPLAY: drmModeRmFB() failed with result: %d", result); + } + + CORE.Window.prevFB = fb; + + if (CORE.Window.prevBO) gbm_surface_release_buffer(CORE.Window.gbmSurface, CORE.Window.prevBO); + + CORE.Window.prevBO = bo; +} + // Register all input events void PollInputEvents(void) { @@ -853,7 +791,7 @@ void PollInputEvents(void) // Reset keys/chars pressed registered CORE.Input.Keyboard.keyPressedQueueCount = 0; CORE.Input.Keyboard.charPressedQueueCount = 0; - + // Reset key repeats for (int i = 0; i < MAX_KEYBOARD_KEYS; i++) CORE.Input.Keyboard.keyRepeatInFrame[i] = 0; @@ -872,12 +810,12 @@ void PollInputEvents(void) // Register previous mouse states CORE.Input.Mouse.previousWheelMove = CORE.Input.Mouse.currentWheelMove; - CORE.Input.Mouse.currentWheelMove = platform.eventWheelMove; - platform.eventWheelMove = (Vector2){ 0.0f, 0.0f }; + CORE.Input.Mouse.currentWheelMove = CORE.Input.Mouse.eventWheelMove; + CORE.Input.Mouse.eventWheelMove = (Vector2){ 0.0f, 0.0f }; for (int i = 0; i < MAX_MOUSE_BUTTONS; i++) { CORE.Input.Mouse.previousButtonState[i] = CORE.Input.Mouse.currentButtonState[i]; - CORE.Input.Mouse.currentButtonState[i] = platform.currentButtonStateEvdev[i]; + CORE.Input.Mouse.currentButtonState[i] = CORE.Input.Mouse.currentButtonStateEvdev[i]; } // Register gamepads buttons events @@ -894,20 +832,21 @@ void PollInputEvents(void) for (int i = 0; i < MAX_TOUCH_POINTS; i++) CORE.Input.Touch.previousTouchState[i] = CORE.Input.Touch.currentTouchState[i]; // Reset touch positions + // TODO: It resets on PLATFORM_WEB the mouse position and not filled again until a move-event, + // so, if mouse is not moved it returns a (0, 0) position... this behaviour should be reviewed! //for (int i = 0; i < MAX_TOUCH_POINTS; i++) CORE.Input.Touch.position[i] = (Vector2){ 0, 0 }; #if defined(SUPPORT_SSH_KEYBOARD_RPI) // NOTE: Keyboard reading could be done using input_event(s) or just read from stdin, both methods are used here. // stdin reading is still used for legacy purposes, it allows keyboard input trough SSH console - if (!platform.eventKeyboardMode) ProcessKeyboard(); + if (!CORE.Input.Keyboard.evtMode) ProcessKeyboard(); // NOTE: Mouse input events polling is done asynchronously in another pthread - EventThread() // NOTE: Gamepad (Joystick) input events polling is done asynchonously in another pthread - GamepadThread() #endif } - //---------------------------------------------------------------------------------- // Module Internal Functions Definition //---------------------------------------------------------------------------------- @@ -934,41 +873,41 @@ static bool InitGraphicsDevice(int width, int height) CORE.Window.fullscreen = true; CORE.Window.flags |= FLAG_FULLSCREEN_MODE; - platform.fd = -1; - platform.connector = NULL; - platform.modeIndex = -1; - platform.crtc = NULL; - platform.gbmDevice = NULL; - platform.gbmSurface = NULL; - platform.prevBO = NULL; - platform.prevFB = 0; + CORE.Window.fd = -1; + CORE.Window.connector = NULL; + CORE.Window.modeIndex = -1; + CORE.Window.crtc = NULL; + CORE.Window.gbmDevice = NULL; + CORE.Window.gbmSurface = NULL; + CORE.Window.prevBO = NULL; + CORE.Window.prevFB = 0; #if defined(DEFAULT_GRAPHIC_DEVICE_DRM) - platform.fd = open(DEFAULT_GRAPHIC_DEVICE_DRM, O_RDWR); + CORE.Window.fd = open(DEFAULT_GRAPHIC_DEVICE_DRM, O_RDWR); #else TRACELOG(LOG_INFO, "DISPLAY: No graphic card set, trying platform-gpu-card"); - platform.fd = open("/dev/dri/by-path/platform-gpu-card", O_RDWR); // VideoCore VI (Raspberry Pi 4) + CORE.Window.fd = open("/dev/dri/by-path/platform-gpu-card", O_RDWR); // VideoCore VI (Raspberry Pi 4) - if ((platform.fd == -1) || (drmModeGetResources(platform.fd) == NULL)) + if ((CORE.Window.fd == -1) || (drmModeGetResources(CORE.Window.fd) == NULL)) { TRACELOG(LOG_INFO, "DISPLAY: Failed to open platform-gpu-card, trying card1"); - platform.fd = open("/dev/dri/card1", O_RDWR); // Other Embedded + CORE.Window.fd = open("/dev/dri/card1", O_RDWR); // Other Embedded } - if ((platform.fd == -1) || (drmModeGetResources(platform.fd) == NULL)) + if ((CORE.Window.fd == -1) || (drmModeGetResources(CORE.Window.fd) == NULL)) { TRACELOG(LOG_INFO, "DISPLAY: Failed to open graphic card1, trying card0"); - platform.fd = open("/dev/dri/card0", O_RDWR); // VideoCore IV (Raspberry Pi 1-3) + CORE.Window.fd = open("/dev/dri/card0", O_RDWR); // VideoCore IV (Raspberry Pi 1-3) } #endif - if (platform.fd == -1) + if (CORE.Window.fd == -1) { TRACELOG(LOG_WARNING, "DISPLAY: Failed to open graphic card"); return false; } - drmModeRes *res = drmModeGetResources(platform.fd); + drmModeRes *res = drmModeGetResources(CORE.Window.fd); if (!res) { TRACELOG(LOG_WARNING, "DISPLAY: Failed get DRM resources"); @@ -976,18 +915,18 @@ static bool InitGraphicsDevice(int width, int height) } TRACELOG(LOG_TRACE, "DISPLAY: Connectors found: %i", res->count_connectors); - + for (size_t i = 0; i < res->count_connectors; i++) { TRACELOG(LOG_TRACE, "DISPLAY: Connector index %i", i); - - drmModeConnector *con = drmModeGetConnector(platform.fd, res->connectors[i]); + + drmModeConnector *con = drmModeGetConnector(CORE.Window.fd, res->connectors[i]); TRACELOG(LOG_TRACE, "DISPLAY: Connector modes detected: %i", con->count_modes); - + if ((con->connection == DRM_MODE_CONNECTED) && (con->encoder_id)) { TRACELOG(LOG_TRACE, "DISPLAY: DRM mode connected"); - platform.connector = con; + CORE.Window.connector = con; break; } else @@ -997,14 +936,14 @@ static bool InitGraphicsDevice(int width, int height) } } - if (!platform.connector) + if (!CORE.Window.connector) { TRACELOG(LOG_WARNING, "DISPLAY: No suitable DRM connector found"); drmModeFreeResources(res); return false; } - drmModeEncoder *enc = drmModeGetEncoder(platform.fd, platform.connector->encoder_id); + drmModeEncoder *enc = drmModeGetEncoder(CORE.Window.fd, CORE.Window.connector->encoder_id); if (!enc) { TRACELOG(LOG_WARNING, "DISPLAY: Failed to get DRM mode encoder"); @@ -1012,8 +951,8 @@ static bool InitGraphicsDevice(int width, int height) return false; } - platform.crtc = drmModeGetCrtc(platform.fd, enc->crtc_id); - if (!platform.crtc) + CORE.Window.crtc = drmModeGetCrtc(CORE.Window.fd, enc->crtc_id); + if (!CORE.Window.crtc) { TRACELOG(LOG_WARNING, "DISPLAY: Failed to get DRM mode crtc"); drmModeFreeEncoder(enc); @@ -1026,9 +965,9 @@ static bool InitGraphicsDevice(int width, int height) { TRACELOG(LOG_TRACE, "DISPLAY: Selecting DRM connector mode for current used mode..."); - platform.modeIndex = FindMatchingConnectorMode(platform.connector, &platform.crtc->mode); + CORE.Window.modeIndex = FindMatchingConnectorMode(CORE.Window.connector, &CORE.Window.crtc->mode); - if (platform.modeIndex < 0) + if (CORE.Window.modeIndex < 0) { TRACELOG(LOG_WARNING, "DISPLAY: No matching DRM connector mode found"); drmModeFreeEncoder(enc); @@ -1044,19 +983,19 @@ static bool InitGraphicsDevice(int width, int height) const int fps = (CORE.Time.target > 0)? (1.0/CORE.Time.target) : 60; // Try to find an exact matching mode - platform.modeIndex = FindExactConnectorMode(platform.connector, CORE.Window.screen.width, CORE.Window.screen.height, fps, allowInterlaced); + CORE.Window.modeIndex = FindExactConnectorMode(CORE.Window.connector, CORE.Window.screen.width, CORE.Window.screen.height, fps, allowInterlaced); // If nothing found, try to find a nearly matching mode - if (platform.modeIndex < 0) platform.modeIndex = FindNearestConnectorMode(platform.connector, CORE.Window.screen.width, CORE.Window.screen.height, fps, allowInterlaced); + if (CORE.Window.modeIndex < 0) CORE.Window.modeIndex = FindNearestConnectorMode(CORE.Window.connector, CORE.Window.screen.width, CORE.Window.screen.height, fps, allowInterlaced); // If nothing found, try to find an exactly matching mode including interlaced - if (platform.modeIndex < 0) platform.modeIndex = FindExactConnectorMode(platform.connector, CORE.Window.screen.width, CORE.Window.screen.height, fps, true); + if (CORE.Window.modeIndex < 0) CORE.Window.modeIndex = FindExactConnectorMode(CORE.Window.connector, CORE.Window.screen.width, CORE.Window.screen.height, fps, true); // If nothing found, try to find a nearly matching mode including interlaced - if (platform.modeIndex < 0) platform.modeIndex = FindNearestConnectorMode(platform.connector, CORE.Window.screen.width, CORE.Window.screen.height, fps, true); + if (CORE.Window.modeIndex < 0) CORE.Window.modeIndex = FindNearestConnectorMode(CORE.Window.connector, CORE.Window.screen.width, CORE.Window.screen.height, fps, true); // If nothing found, there is no suitable mode - if (platform.modeIndex < 0) + if (CORE.Window.modeIndex < 0) { TRACELOG(LOG_WARNING, "DISPLAY: Failed to find a suitable DRM connector mode"); drmModeFreeEncoder(enc); @@ -1064,13 +1003,13 @@ static bool InitGraphicsDevice(int width, int height) return false; } - CORE.Window.display.width = platform.connector->modes[platform.modeIndex].hdisplay; - CORE.Window.display.height = platform.connector->modes[platform.modeIndex].vdisplay; + CORE.Window.display.width = CORE.Window.connector->modes[CORE.Window.modeIndex].hdisplay; + CORE.Window.display.height = CORE.Window.connector->modes[CORE.Window.modeIndex].vdisplay; - TRACELOG(LOG_INFO, "DISPLAY: Selected DRM connector mode %s (%ux%u%c@%u)", platform.connector->modes[platform.modeIndex].name, - platform.connector->modes[platform.modeIndex].hdisplay, platform.connector->modes[platform.modeIndex].vdisplay, - (platform.connector->modes[platform.modeIndex].flags & DRM_MODE_FLAG_INTERLACE)? 'i' : 'p', - platform.connector->modes[platform.modeIndex].vrefresh); + TRACELOG(LOG_INFO, "DISPLAY: Selected DRM connector mode %s (%ux%u%c@%u)", CORE.Window.connector->modes[CORE.Window.modeIndex].name, + CORE.Window.connector->modes[CORE.Window.modeIndex].hdisplay, CORE.Window.connector->modes[CORE.Window.modeIndex].vdisplay, + (CORE.Window.connector->modes[CORE.Window.modeIndex].flags & DRM_MODE_FLAG_INTERLACE)? 'i' : 'p', + CORE.Window.connector->modes[CORE.Window.modeIndex].vrefresh); // Use the width and height of the surface for render CORE.Window.render.width = CORE.Window.screen.width; @@ -1082,16 +1021,16 @@ static bool InitGraphicsDevice(int width, int height) drmModeFreeResources(res); res = NULL; - platform.gbmDevice = gbm_create_device(platform.fd); - if (!platform.gbmDevice) + CORE.Window.gbmDevice = gbm_create_device(CORE.Window.fd); + if (!CORE.Window.gbmDevice) { TRACELOG(LOG_WARNING, "DISPLAY: Failed to create GBM device"); return false; } - platform.gbmSurface = gbm_surface_create(platform.gbmDevice, platform.connector->modes[platform.modeIndex].hdisplay, - platform.connector->modes[platform.modeIndex].vdisplay, GBM_FORMAT_ARGB8888, GBM_BO_USE_SCANOUT | GBM_BO_USE_RENDERING); - if (!platform.gbmSurface) + CORE.Window.gbmSurface = gbm_surface_create(CORE.Window.gbmDevice, CORE.Window.connector->modes[CORE.Window.modeIndex].hdisplay, + CORE.Window.connector->modes[CORE.Window.modeIndex].vdisplay, GBM_FORMAT_ARGB8888, GBM_BO_USE_SCANOUT | GBM_BO_USE_RENDERING); + if (!CORE.Window.gbmSurface) { TRACELOG(LOG_WARNING, "DISPLAY: Failed to create GBM surface"); return false; @@ -1130,22 +1069,22 @@ static bool InitGraphicsDevice(int width, int height) EGLint numConfigs = 0; // Get an EGL device connection - platform.device = eglGetDisplay((EGLNativeDisplayType)platform.gbmDevice); - if (platform.device == EGL_NO_DISPLAY) + CORE.Window.device = eglGetDisplay((EGLNativeDisplayType)CORE.Window.gbmDevice); + if (CORE.Window.device == EGL_NO_DISPLAY) { TRACELOG(LOG_WARNING, "DISPLAY: Failed to initialize EGL device"); return false; } // Initialize the EGL device connection - if (eglInitialize(platform.device, NULL, NULL) == EGL_FALSE) + if (eglInitialize(CORE.Window.device, NULL, NULL) == EGL_FALSE) { // If all of the calls to eglInitialize returned EGL_FALSE then an error has occurred. TRACELOG(LOG_WARNING, "DISPLAY: Failed to initialize EGL device"); return false; } - if (!eglChooseConfig(platform.device, NULL, NULL, 0, &numConfigs)) + if (!eglChooseConfig(CORE.Window.device, NULL, NULL, 0, &numConfigs)) { TRACELOG(LOG_WARNING, "DISPLAY: Failed to get EGL config count: 0x%x", eglGetError()); return false; @@ -1161,7 +1100,7 @@ static bool InitGraphicsDevice(int width, int height) } EGLint matchingNumConfigs = 0; - if (!eglChooseConfig(platform.device, framebufferAttribs, configs, numConfigs, &matchingNumConfigs)) + if (!eglChooseConfig(CORE.Window.device, framebufferAttribs, configs, numConfigs, &matchingNumConfigs)) { TRACELOG(LOG_WARNING, "DISPLAY: Failed to choose EGL config: 0x%x", eglGetError()); free(configs); @@ -1175,7 +1114,7 @@ static bool InitGraphicsDevice(int width, int height) for (EGLint i = 0; i < matchingNumConfigs; ++i) { EGLint id = 0; - if (!eglGetConfigAttrib(platform.device, configs[i], EGL_NATIVE_VISUAL_ID, &id)) + if (!eglGetConfigAttrib(CORE.Window.device, configs[i], EGL_NATIVE_VISUAL_ID, &id)) { TRACELOG(LOG_WARNING, "DISPLAY: Failed to get EGL config attribute: 0x%x", eglGetError()); continue; @@ -1184,7 +1123,7 @@ static bool InitGraphicsDevice(int width, int height) if (GBM_FORMAT_ARGB8888 == id) { TRACELOG(LOG_TRACE, "DISPLAY: Using EGL config: %d", i); - platform.config = configs[i]; + CORE.Window.config = configs[i]; found = 1; break; } @@ -1202,8 +1141,8 @@ static bool InitGraphicsDevice(int width, int height) eglBindAPI(EGL_OPENGL_ES_API); // Create an EGL rendering context - platform.context = eglCreateContext(platform.device, platform.config, EGL_NO_CONTEXT, contextAttribs); - if (platform.context == EGL_NO_CONTEXT) + CORE.Window.context = eglCreateContext(CORE.Window.device, CORE.Window.config, EGL_NO_CONTEXT, contextAttribs); + if (CORE.Window.context == EGL_NO_CONTEXT) { TRACELOG(LOG_WARNING, "DISPLAY: Failed to create EGL context"); return false; @@ -1211,8 +1150,8 @@ static bool InitGraphicsDevice(int width, int height) // Create an EGL window surface //--------------------------------------------------------------------------------- - platform.surface = eglCreateWindowSurface(platform.device, platform.config, (EGLNativeWindowType)platform.gbmSurface, NULL); - if (EGL_NO_SURFACE == platform.surface) + CORE.Window.surface = eglCreateWindowSurface(CORE.Window.device, CORE.Window.config, (EGLNativeWindowType)CORE.Window.gbmSurface, NULL); + if (EGL_NO_SURFACE == CORE.Window.surface) { TRACELOG(LOG_WARNING, "DISPLAY: Failed to create EGL window surface: 0x%04x", eglGetError()); return false; @@ -1226,9 +1165,9 @@ static bool InitGraphicsDevice(int width, int height) SetupFramebuffer(CORE.Window.display.width, CORE.Window.display.height); // There must be at least one frame displayed before the buffers are swapped - //eglSwapInterval(platform.device, 1); + //eglSwapInterval(CORE.Window.device, 1); - if (eglMakeCurrent(platform.device, platform.surface, platform.surface, platform.context) == EGL_FALSE) + if (eglMakeCurrent(CORE.Window.device, CORE.Window.surface, CORE.Window.surface, CORE.Window.context) == EGL_FALSE) { TRACELOG(LOG_WARNING, "DISPLAY: Failed to attach EGL rendering context to EGL surface"); return false; @@ -1271,11 +1210,11 @@ static void InitKeyboard(void) // Reading directly from stdin will give chars already key-mapped by kernel to ASCII or UNICODE // Save terminal keyboard settings - tcgetattr(STDIN_FILENO, &platform.defaultSettings); + tcgetattr(STDIN_FILENO, &CORE.Input.Keyboard.defaultSettings); // Reconfigure terminal with new settings struct termios keyboardNewSettings = { 0 }; - keyboardNewSettings = platform.defaultSettings; + keyboardNewSettings = CORE.Input.Keyboard.defaultSettings; // New terminal settings for keyboard: turn off buffering (non-canonical mode), echo and key processing // NOTE: ISIG controls if ^C and ^Z generate break signals or not @@ -1288,11 +1227,11 @@ static void InitKeyboard(void) tcsetattr(STDIN_FILENO, TCSANOW, &keyboardNewSettings); // Save old keyboard mode to restore it at the end - platform.defaultFileFlags = fcntl(STDIN_FILENO, F_GETFL, 0); // F_GETFL: Get the file access mode and the file status flags - fcntl(STDIN_FILENO, F_SETFL, platform.defaultFileFlags | O_NONBLOCK); // F_SETFL: Set the file status flags to the value specified + CORE.Input.Keyboard.defaultFileFlags = fcntl(STDIN_FILENO, F_GETFL, 0); // F_GETFL: Get the file access mode and the file status flags + fcntl(STDIN_FILENO, F_SETFL, CORE.Input.Keyboard.defaultFileFlags | O_NONBLOCK); // F_SETFL: Set the file status flags to the value specified // NOTE: If ioctl() returns -1, it means the call failed for some reason (error code set in errno) - int result = ioctl(STDIN_FILENO, KDGKBMODE, &platform.defaultKeyboardMode); + int result = ioctl(STDIN_FILENO, KDGKBMODE, &CORE.Input.Keyboard.defaultMode); // In case of failure, it could mean a remote keyboard is used (SSH) if (result < 0) TRACELOG(LOG_WARNING, "RPI: Failed to change keyboard mode, an SSH keyboard is probably used"); @@ -1314,11 +1253,11 @@ static void InitKeyboard(void) static void RestoreKeyboard(void) { // Reset to default keyboard settings - tcsetattr(STDIN_FILENO, TCSANOW, &platform.defaultSettings); + tcsetattr(STDIN_FILENO, TCSANOW, &CORE.Input.Keyboard.defaultSettings); // Reconfigure keyboard to default mode - fcntl(STDIN_FILENO, F_SETFL, platform.defaultFileFlags); - ioctl(STDIN_FILENO, KDSKBMODE, platform.defaultKeyboardMode); + fcntl(STDIN_FILENO, F_SETFL, CORE.Input.Keyboard.defaultFileFlags); + ioctl(STDIN_FILENO, KDSKBMODE, CORE.Input.Keyboard.defaultMode); } #if defined(SUPPORT_SSH_KEYBOARD_RPI) @@ -1437,7 +1376,7 @@ static void ProcessKeyboard(void) } #endif // SUPPORT_SSH_KEYBOARD_RPI -// Initialise user input from evdev(/dev/input/event) +// Initialise user input from evdev(/dev/input/event) // this means mouse, keyboard or gamepad devices static void InitEvdevInput(void) { @@ -1446,7 +1385,7 @@ static void InitEvdevInput(void) struct dirent *entity = NULL; // Initialise keyboard file descriptor - platform.keyboardFd = -1; + CORE.Input.Keyboard.fd = -1; // Reset variables for (int i = 0; i < MAX_TOUCH_POINTS; ++i) @@ -1508,9 +1447,9 @@ static void ConfigureEvdevDevice(char *device) // Open the device and allocate worker //------------------------------------------------------------------------------------------------------- // Find a free spot in the workers array - for (int i = 0; i < sizeof(platform.eventWorker)/sizeof(InputEventWorker); ++i) + for (int i = 0; i < sizeof(CORE.Input.eventWorker)/sizeof(InputEventWorker); ++i) { - if (platform.eventWorker[i].threadId == 0) + if (CORE.Input.eventWorker[i].threadId == 0) { freeWorkerId = i; break; @@ -1520,7 +1459,7 @@ static void ConfigureEvdevDevice(char *device) // Select the free worker from array if (freeWorkerId >= 0) { - worker = &(platform.eventWorker[freeWorkerId]); // Grab a pointer to the worker + worker = &(CORE.Input.eventWorker[freeWorkerId]); // Grab a pointer to the worker memset(worker, 0, sizeof(InputEventWorker)); // Clear the worker } else @@ -1631,13 +1570,13 @@ static void ConfigureEvdevDevice(char *device) // Decide what to do with the device //------------------------------------------------------------------------------------------------------- - if (worker->isKeyboard && (platform.keyboardFd == -1)) + if (worker->isKeyboard && (CORE.Input.Keyboard.fd == -1)) { // Use the first keyboard encountered. This assumes that a device that says it's a keyboard is just a // keyboard. The keyboard is polled synchronously, whereas other input devices are polled in separate // threads so that they don't drop events when the frame rate is slow. TRACELOG(LOG_INFO, "RPI: Opening keyboard device: %s", device); - platform.keyboardFd = worker->fd; + CORE.Input.Keyboard.fd = worker->fd; } else if (worker->isTouch || worker->isMouse) { @@ -1661,21 +1600,21 @@ static void ConfigureEvdevDevice(char *device) // Find touchscreen with the highest index int maxTouchNumber = -1; - for (int i = 0; i < sizeof(platform.eventWorker)/sizeof(InputEventWorker); ++i) + for (int i = 0; i < sizeof(CORE.Input.eventWorker)/sizeof(InputEventWorker); ++i) { - if (platform.eventWorker[i].isTouch && (platform.eventWorker[i].eventNum > maxTouchNumber)) maxTouchNumber = platform.eventWorker[i].eventNum; + if (CORE.Input.eventWorker[i].isTouch && (CORE.Input.eventWorker[i].eventNum > maxTouchNumber)) maxTouchNumber = CORE.Input.eventWorker[i].eventNum; } // Find touchscreens with lower indexes - for (int i = 0; i < sizeof(platform.eventWorker)/sizeof(InputEventWorker); ++i) + for (int i = 0; i < sizeof(CORE.Input.eventWorker)/sizeof(InputEventWorker); ++i) { - if (platform.eventWorker[i].isTouch && (platform.eventWorker[i].eventNum < maxTouchNumber)) + if (CORE.Input.eventWorker[i].isTouch && (CORE.Input.eventWorker[i].eventNum < maxTouchNumber)) { - if (platform.eventWorker[i].threadId != 0) + if (CORE.Input.eventWorker[i].threadId != 0) { TRACELOG(LOG_WARNING, "RPI: Found duplicate touchscreen, killing touchscreen on event: %d", i); - pthread_cancel(platform.eventWorker[i].threadId); - close(platform.eventWorker[i].fd); + pthread_cancel(CORE.Input.eventWorker[i].threadId); + close(CORE.Input.eventWorker[i].fd); } } } @@ -1709,7 +1648,7 @@ static void PollKeyboardEvents(void) 243, 244, 245, 246, 247, 248, 0, 0, 0, 0, 0, 0, 0 }; - int fd = platform.keyboardFd; + int fd = CORE.Input.Keyboard.fd; if (fd == -1) return; struct input_event event = { 0 }; @@ -1723,7 +1662,7 @@ static void PollKeyboardEvents(void) { #if defined(SUPPORT_SSH_KEYBOARD_RPI) // Change keyboard mode to events - platform.eventKeyboardMode = true; + CORE.Input.Keyboard.evtMode = true; #endif // Keyboard button parsing if ((event.code >= 1) && (event.code <= 255)) //Keyboard keys appear for codes 1 to 255 @@ -1796,7 +1735,7 @@ static void *EventThread(void *arg) gestureUpdate = true; } - if (event.code == REL_WHEEL) platform.eventWheelMove.y += event.value; + if (event.code == REL_WHEEL) CORE.Input.Mouse.eventWheelMove.y += event.value; } // Absolute movement parsing @@ -1847,11 +1786,11 @@ static void *EventThread(void *arg) // Touchscreen tap if (event.code == ABS_PRESSURE) { - int previousMouseLeftButtonState = platform.currentButtonStateEvdev[MOUSE_BUTTON_LEFT]; + int previousMouseLeftButtonState = CORE.Input.Mouse.currentButtonStateEvdev[MOUSE_BUTTON_LEFT]; if (!event.value && previousMouseLeftButtonState) { - platform.currentButtonStateEvdev[MOUSE_BUTTON_LEFT] = 0; + CORE.Input.Mouse.currentButtonStateEvdev[MOUSE_BUTTON_LEFT] = 0; touchAction = 0; // TOUCH_ACTION_UP gestureUpdate = true; @@ -1859,7 +1798,7 @@ static void *EventThread(void *arg) if (event.value && !previousMouseLeftButtonState) { - platform.currentButtonStateEvdev[MOUSE_BUTTON_LEFT] = 1; + CORE.Input.Mouse.currentButtonStateEvdev[MOUSE_BUTTON_LEFT] = 1; touchAction = 1; // TOUCH_ACTION_DOWN gestureUpdate = true; @@ -1874,19 +1813,19 @@ static void *EventThread(void *arg) // Mouse button parsing if ((event.code == BTN_TOUCH) || (event.code == BTN_LEFT)) { - platform.currentButtonStateEvdev[MOUSE_BUTTON_LEFT] = event.value; + CORE.Input.Mouse.currentButtonStateEvdev[MOUSE_BUTTON_LEFT] = event.value; if (event.value > 0) touchAction = 1; // TOUCH_ACTION_DOWN else touchAction = 0; // TOUCH_ACTION_UP gestureUpdate = true; } - if (event.code == BTN_RIGHT) platform.currentButtonStateEvdev[MOUSE_BUTTON_RIGHT] = event.value; - if (event.code == BTN_MIDDLE) platform.currentButtonStateEvdev[MOUSE_BUTTON_MIDDLE] = event.value; - if (event.code == BTN_SIDE) platform.currentButtonStateEvdev[MOUSE_BUTTON_SIDE] = event.value; - if (event.code == BTN_EXTRA) platform.currentButtonStateEvdev[MOUSE_BUTTON_EXTRA] = event.value; - if (event.code == BTN_FORWARD) platform.currentButtonStateEvdev[MOUSE_BUTTON_FORWARD] = event.value; - if (event.code == BTN_BACK) platform.currentButtonStateEvdev[MOUSE_BUTTON_BACK] = event.value; + if (event.code == BTN_RIGHT) CORE.Input.Mouse.currentButtonStateEvdev[MOUSE_BUTTON_RIGHT] = event.value; + if (event.code == BTN_MIDDLE) CORE.Input.Mouse.currentButtonStateEvdev[MOUSE_BUTTON_MIDDLE] = event.value; + if (event.code == BTN_SIDE) CORE.Input.Mouse.currentButtonStateEvdev[MOUSE_BUTTON_SIDE] = event.value; + if (event.code == BTN_EXTRA) CORE.Input.Mouse.currentButtonStateEvdev[MOUSE_BUTTON_EXTRA] = event.value; + if (event.code == BTN_FORWARD) CORE.Input.Mouse.currentButtonStateEvdev[MOUSE_BUTTON_FORWARD] = event.value; + if (event.code == BTN_BACK) CORE.Input.Mouse.currentButtonStateEvdev[MOUSE_BUTTON_BACK] = event.value; } // Screen confinement @@ -1906,7 +1845,7 @@ static void *EventThread(void *arg) if (CORE.Input.Touch.position[i].x >= 0) CORE.Input.Touch.pointCount++; } -#if defined(SUPPORT_GESTURES_SYSTEM) +#if defined(SUPPORT_GESTURES_SYSTEM) // PLATFORM_DRM if (gestureUpdate) { GestureEvent gestureEvent = { 0 }; @@ -1942,7 +1881,7 @@ static void InitGamepad(void) { sprintf(gamepadDev, "%s%i", DEFAULT_GAMEPAD_DEV, i); - if ((platform.gamepadStreamFd[i] = open(gamepadDev, O_RDONLY | O_NONBLOCK)) < 0) + if ((CORE.Input.Gamepad.streamId[i] = open(gamepadDev, O_RDONLY | O_NONBLOCK)) < 0) { // NOTE: Only show message for first gamepad if (i == 0) TRACELOG(LOG_WARNING, "RPI: Failed to open Gamepad device, no gamepad available"); @@ -1954,11 +1893,15 @@ static void InitGamepad(void) // NOTE: Only create one thread if (i == 0) { - int error = pthread_create(&platform.gamepadThreadId, NULL, &GamepadThread, NULL); + int error = pthread_create(&CORE.Input.Gamepad.threadId, NULL, &GamepadThread, NULL); if (error != 0) TRACELOG(LOG_WARNING, "RPI: Failed to create gamepad input event thread"); else TRACELOG(LOG_INFO, "RPI: Gamepad device initialized successfully"); } + + int axisCount = 0; + if (CORE.Input.Gamepad.ready[i]) ioctl(CORE.Input.Gamepad.streamId[i], JSIOCGAXES, &axisCount); + CORE.Input.Gamepad.axisCount = axisCount; } } } @@ -1984,7 +1927,7 @@ static void *GamepadThread(void *arg) { for (int i = 0; i < MAX_GAMEPADS; i++) { - if (read(platform.gamepadStreamFd[i], &gamepadEvent, sizeof(struct js_event)) == (int)sizeof(struct js_event)) + if (read(CORE.Input.Gamepad.streamId[i], &gamepadEvent, sizeof(struct js_event)) == (int)sizeof(struct js_event)) { gamepadEvent.type &= ~JS_EVENT_INIT; // Ignore synthetic events @@ -2034,7 +1977,7 @@ static int FindMatchingConnectorMode(const drmModeConnector *connector, const dr TRACELOG(LOG_TRACE, "DISPLAY: DRM mode: %d %ux%u@%u %s", i, connector->modes[i].hdisplay, connector->modes[i].vdisplay, connector->modes[i].vrefresh, (connector->modes[i].flags & DRM_MODE_FLAG_INTERLACE)? "interlaced" : "progressive"); - if (0 == BINCMP(&platform.crtc->mode, &platform.connector->modes[i])) return i; + if (0 == BINCMP(&CORE.Window.crtc->mode, &CORE.Window.connector->modes[i])) return i; } return -1; @@ -2049,9 +1992,9 @@ static int FindExactConnectorMode(const drmModeConnector *connector, uint width, if (NULL == connector) return -1; - for (int i = 0; i < platform.connector->count_modes; i++) + for (int i = 0; i < CORE.Window.connector->count_modes; i++) { - const drmModeModeInfo *const mode = &platform.connector->modes[i]; + const drmModeModeInfo *const mode = &CORE.Window.connector->modes[i]; TRACELOG(LOG_TRACE, "DISPLAY: DRM Mode %d %ux%u@%u %s", i, mode->hdisplay, mode->vdisplay, mode->vrefresh, (mode->flags & DRM_MODE_FLAG_INTERLACE)? "interlaced" : "progressive"); @@ -2072,9 +2015,9 @@ static int FindNearestConnectorMode(const drmModeConnector *connector, uint widt if (NULL == connector) return -1; int nearestIndex = -1; - for (int i = 0; i < platform.connector->count_modes; i++) + for (int i = 0; i < CORE.Window.connector->count_modes; i++) { - const drmModeModeInfo *const mode = &platform.connector->modes[i]; + const drmModeModeInfo *const mode = &CORE.Window.connector->modes[i]; TRACELOG(LOG_TRACE, "DISPLAY: DRM mode: %d %ux%u@%u %s", i, mode->hdisplay, mode->vdisplay, mode->vrefresh, (mode->flags & DRM_MODE_FLAG_INTERLACE)? "interlaced" : "progressive"); @@ -2101,9 +2044,9 @@ static int FindNearestConnectorMode(const drmModeConnector *connector, uint widt const int heightDiff = abs(mode->vdisplay - height); const int fpsDiff = abs(mode->vrefresh - fps); - const int nearestWidthDiff = abs(platform.connector->modes[nearestIndex].hdisplay - width); - const int nearestHeightDiff = abs(platform.connector->modes[nearestIndex].vdisplay - height); - const int nearestFpsDiff = abs(platform.connector->modes[nearestIndex].vrefresh - fps); + const int nearestWidthDiff = abs(CORE.Window.connector->modes[nearestIndex].hdisplay - width); + const int nearestHeightDiff = abs(CORE.Window.connector->modes[nearestIndex].vdisplay - height); + const int nearestFpsDiff = abs(CORE.Window.connector->modes[nearestIndex].vrefresh - fps); if ((widthDiff < nearestWidthDiff) || (heightDiff < nearestHeightDiff) || (fpsDiff < nearestFpsDiff)) { nearestIndex = i; From aacd3e25540b541e616329f9690e8710d543a360 Mon Sep 17 00:00:00 2001 From: Michael Date: Tue, 10 Oct 2023 12:29:29 -0400 Subject: [PATCH 02/33] Update --- src/rcore_drm.c | 595 ++++++++++++++++++++++++++---------------------- 1 file changed, 327 insertions(+), 268 deletions(-) diff --git a/src/rcore_drm.c b/src/rcore_drm.c index 66d6d7989..a7e7447a4 100644 --- a/src/rcore_drm.c +++ b/src/rcore_drm.c @@ -1,6 +1,6 @@ /********************************************************************************************** * -* rcore_drm - Functions to manage window, graphics device and inputs +* rcore_drm - Functions to manage window, graphics device and inputs * * PLATFORM: DRM * - Raspberry Pi 0-5 @@ -17,8 +17,10 @@ * - TRACELOG() function is located in raylib [utils] module * * CONFIGURATION: -* #define RCORE_DRM_CUSTOM_FLAG -* Custom flag for rcore on PLATFORM_DRM -not used- +* #define SUPPORT_SSH_KEYBOARD_RPI (Raspberry Pi only) +* Reconfigure standard input to receive key inputs, works with SSH connection. +* WARNING: Reconfiguring standard input could lead to undesired effects, like breaking other +* running processes orblocking the device if not restored properly. Use with care. * * DEPENDENCIES: * gestures - Gestures system for touch-ready devices (or simulated from mouse inputs) @@ -47,15 +49,93 @@ #include "rcore.h" +#include // POSIX file control definitions - open(), creat(), fcntl() +#include // POSIX standard function definitions - read(), close(), STDIN_FILENO +#include // POSIX terminal control definitions - tcgetattr(), tcsetattr() +#include // POSIX threads management (inputs reading) +#include // POSIX directory browsing + +#include // Required for: ioctl() - UNIX System call for device-specific input/output operations +#include // Linux: KDSKBMODE, K_MEDIUMRAM constants definition +#include // Linux: Keycodes constants definition (KEY_A, ...) +#include // Linux: Joystick support library + +#include // Generic Buffer Management (native platform for EGL on DRM) +#include // Direct Rendering Manager user-level library interface +#include // Direct Rendering Manager mode setting (KMS) interface + +#include "EGL/egl.h" // Native platform windowing system interface +#include "EGL/eglext.h" // EGL extensions + +//---------------------------------------------------------------------------------- +// Defines and Macros +//---------------------------------------------------------------------------------- +#define USE_LAST_TOUCH_DEVICE // When multiple touchscreens are connected, only use the one with the highest event number + +#define DEFAULT_GAMEPAD_DEV "/dev/input/js" // Gamepad input (base dev for all gamepads: js0, js1, ...) +#define DEFAULT_EVDEV_PATH "/dev/input/" // Path to the linux input events + //---------------------------------------------------------------------------------- // Types and Structures Definition //---------------------------------------------------------------------------------- -//... + +typedef struct { + pthread_t threadId; // Event reading thread id + + int fd; // File descriptor to the device it is assigned to + int eventNum; // Number of 'event' device + Rectangle absRange; // Range of values for absolute pointing devices (touchscreens) + int touchSlot; // Hold the touch slot number of the currently being sent multitouch block + bool isMouse; // True if device supports relative X Y movements + bool isTouch; // True if device supports absolute X Y movements and has BTN_TOUCH + bool isMultitouch; // True if device supports multiple absolute movevents and has BTN_TOUCH + bool isKeyboard; // True if device has letter keycodes + bool isGamepad; // True if device has gamepad buttons +} InputEventWorker; + +typedef struct { + // Display data + int fd; // File descriptor for /dev/dri/... + drmModeConnector *connector; // Direct Rendering Manager (DRM) mode connector + drmModeCrtc *crtc; // CRT Controller + int modeIndex; // Index of the used mode of connector->modes + struct gbm_device *gbmDevice; // GBM device + struct gbm_surface *gbmSurface; // GBM surface + struct gbm_bo *prevBO; // Previous GBM buffer object (during frame swapping) + uint32_t prevFB; // Previous GBM framebufer (during frame swapping) + + EGLDisplay device; // Native display device (physical screen connection) + EGLSurface surface; // Surface to draw on, framebuffers (connected to context) + EGLContext context; // Graphic context, mode in which drawing can be done + EGLConfig config; // Graphic config + + // Input data + InputEventWorker eventWorker[10]; // List of worker threads for every monitored "/dev/input/event" + + // Keyboard data + int defaultKeyboardMode; // Default keyboard mode + bool eventKeyboardMode; // Keyboard in event mode + int defaultFileFlags; // Default IO file flags + struct termios defaultSettings; // Default keyboard settings + int keyboardFd; // File descriptor for the evdev keyboard + + // Mouse data + Vector2 eventWheelMove; // Registers the event mouse wheel variation + // NOTE: currentButtonState[] can't be written directly due to multithreading, app could miss the update + char currentButtonStateEvdev[MAX_MOUSE_BUTTONS]; // Holds the new mouse state for the next polling event to grab + + // Gamepad data + pthread_t gamepadThreadId; // Gamepad reading thread id + int gamepadStreamFd[MAX_GAMEPADS]; // Gamepad device file descriptor + +} PlatformData; //---------------------------------------------------------------------------------- // Global Variables Definition //---------------------------------------------------------------------------------- -extern CoreData CORE; // Global CORE state context +extern CoreData CORE; // Global CORE state context + +static PlatformData platform = { 0 }; // Platform specific data //---------------------------------------------------------------------------------- // Module Internal Functions Declaration @@ -86,7 +166,7 @@ static int FindNearestConnectorMode(const drmModeConnector *connector, uint widt // NOTE: Functions declaration is provided by raylib.h //---------------------------------------------------------------------------------- -// Module Functions Definition +// Module Functions Definition: Window and Graphics Device //---------------------------------------------------------------------------------- // Initialize window and OpenGL context @@ -140,19 +220,14 @@ void InitWindow(int width, int height, const char *title) CORE.Window.ready = InitGraphicsDevice(width, height); // If graphic device is no properly initialized, we end program - if (!CORE.Window.ready) - { - TRACELOG(LOG_FATAL, "Failed to initialize Graphic Device"); - return; - } - else - SetWindowPosition(GetMonitorWidth(GetCurrentMonitor()) / 2 - CORE.Window.screen.width / 2, GetMonitorHeight(GetCurrentMonitor()) / 2 - CORE.Window.screen.height / 2); + if (!CORE.Window.ready) { TRACELOG(LOG_FATAL, "PLATFORM: Failed to initialize graphic device"); return; } + else SetWindowPosition(GetMonitorWidth(GetCurrentMonitor()) / 2 - CORE.Window.screen.width / 2, GetMonitorHeight(GetCurrentMonitor()) / 2 - CORE.Window.screen.height / 2); // Initialize hi-res timer InitTimer(); // Initialize random seed - srand((unsigned int)time(NULL)); + SetRandomSeed((unsigned int)time(NULL)); // Initialize base path for storage CORE.Storage.basePath = GetWorkingDirectory(); @@ -194,15 +269,20 @@ void InitWindow(int width, int height, const char *title) } #endif - // Initialize raw input system - InitEvdevInput(); // Evdev inputs initialization - InitGamepad(); // Gamepad init - InitKeyboard(); // Keyboard init (stdin) - #if defined(SUPPORT_EVENTS_AUTOMATION) events = (AutomationEvent *)RL_CALLOC(MAX_CODE_AUTOMATION_EVENTS, sizeof(AutomationEvent)); CORE.Time.frameCounter = 0; #endif + + // Platform specific init window + //-------------------------------------------------------------- + // Initialize raw input system + InitEvdevInput(); // Evdev inputs initialization + InitGamepad(); // Gamepad init + InitKeyboard(); // Keyboard init (stdin) + //-------------------------------------------------------------- + + TRACELOG(LOG_INFO, "PLATFORM: DRM: Application initialized successfully"); } // Close window and unload OpenGL context @@ -227,67 +307,69 @@ void CloseWindow(void) timeEndPeriod(1); // Restore time period #endif - if (CORE.Window.prevFB) + // Platform specific close window + //-------------------------------------------------------------- + if (platform.prevFB) { - drmModeRmFB(CORE.Window.fd, CORE.Window.prevFB); - CORE.Window.prevFB = 0; + drmModeRmFB(platform.fd, platform.prevFB); + platform.prevFB = 0; } - if (CORE.Window.prevBO) + if (platform.prevBO) { - gbm_surface_release_buffer(CORE.Window.gbmSurface, CORE.Window.prevBO); - CORE.Window.prevBO = NULL; + gbm_surface_release_buffer(platform.gbmSurface, platform.prevBO); + platform.prevBO = NULL; } - if (CORE.Window.gbmSurface) + if (platform.gbmSurface) { - gbm_surface_destroy(CORE.Window.gbmSurface); - CORE.Window.gbmSurface = NULL; + gbm_surface_destroy(platform.gbmSurface); + platform.gbmSurface = NULL; } - if (CORE.Window.gbmDevice) + if (platform.gbmDevice) { - gbm_device_destroy(CORE.Window.gbmDevice); - CORE.Window.gbmDevice = NULL; + gbm_device_destroy(platform.gbmDevice); + platform.gbmDevice = NULL; } - if (CORE.Window.crtc) + if (platform.crtc) { - if (CORE.Window.connector) + if (platform.connector) { - drmModeSetCrtc(CORE.Window.fd, CORE.Window.crtc->crtc_id, CORE.Window.crtc->buffer_id, - CORE.Window.crtc->x, CORE.Window.crtc->y, &CORE.Window.connector->connector_id, 1, &CORE.Window.crtc->mode); - drmModeFreeConnector(CORE.Window.connector); - CORE.Window.connector = NULL; + drmModeSetCrtc(platform.fd, platform.crtc->crtc_id, platform.crtc->buffer_id, + platform.crtc->x, platform.crtc->y, &platform.connector->connector_id, 1, &platform.crtc->mode); + drmModeFreeConnector(platform.connector); + platform.connector = NULL; } - drmModeFreeCrtc(CORE.Window.crtc); - CORE.Window.crtc = NULL; + drmModeFreeCrtc(platform.crtc); + platform.crtc = NULL; } - if (CORE.Window.fd != -1) + if (platform.fd != -1) { - close(CORE.Window.fd); - CORE.Window.fd = -1; + close(platform.fd); + platform.fd = -1; } // Close surface, context and display - if (CORE.Window.device != EGL_NO_DISPLAY) + if (platform.device != EGL_NO_DISPLAY) { - if (CORE.Window.surface != EGL_NO_SURFACE) + if (platform.surface != EGL_NO_SURFACE) { - eglDestroySurface(CORE.Window.device, CORE.Window.surface); - CORE.Window.surface = EGL_NO_SURFACE; + eglDestroySurface(platform.device, platform.surface); + platform.surface = EGL_NO_SURFACE; } - if (CORE.Window.context != EGL_NO_CONTEXT) + if (platform.context != EGL_NO_CONTEXT) { - eglDestroyContext(CORE.Window.device, CORE.Window.context); - CORE.Window.context = EGL_NO_CONTEXT; + eglDestroyContext(platform.device, platform.context); + platform.context = EGL_NO_CONTEXT; } - eglTerminate(CORE.Window.device); - CORE.Window.device = EGL_NO_DISPLAY; + eglTerminate(platform.device); + platform.device = EGL_NO_DISPLAY; } // Wait for mouse and gamepad threads to finish before closing @@ -297,21 +379,22 @@ void CloseWindow(void) CORE.Window.shouldClose = true; // Added to force threads to exit when the close window is called // Close the evdev keyboard - if (CORE.Input.Keyboard.fd != -1) + if (platform.keyboardFd != -1) { - close(CORE.Input.Keyboard.fd); - CORE.Input.Keyboard.fd = -1; + close(platform.keyboardFd); + platform.keyboardFd = -1; } - for (int i = 0; i < sizeof(CORE.Input.eventWorker)/sizeof(InputEventWorker); ++i) + for (int i = 0; i < sizeof(platform.eventWorker)/sizeof(InputEventWorker); ++i) { - if (CORE.Input.eventWorker[i].threadId) + if (platform.eventWorker[i].threadId) { - pthread_join(CORE.Input.eventWorker[i].threadId, NULL); + pthread_join(platform.eventWorker[i].threadId, NULL); } } - if (CORE.Input.Gamepad.threadId) pthread_join(CORE.Input.Gamepad.threadId, NULL); + if (platform.gamepadThreadId) pthread_join(platform.gamepadThreadId, NULL); + //-------------------------------------------------------------- #if defined(SUPPORT_EVENTS_AUTOMATION) RL_FREE(events); @@ -362,55 +445,55 @@ bool IsWindowResized(void) // Toggle fullscreen mode void ToggleFullscreen(void) { - TRACELOG(LOG_WARNING, "ToggleFullscreen() not available on PLATFORM_DRM"); + TRACELOG(LOG_WARNING, "ToggleFullscreen() not available on target platform"); } // Set window state: maximized, if resizable void MaximizeWindow(void) { - TRACELOG(LOG_WARNING, "MaximizeWindow() not available on PLATFORM_DRM"); + TRACELOG(LOG_WARNING, "MaximizeWindow() not available on target platform"); } // Set window state: minimized void MinimizeWindow(void) { - TRACELOG(LOG_WARNING, "MinimizeWindow() not available on PLATFORM_DRM"); + TRACELOG(LOG_WARNING, "MinimizeWindow() not available on target platform"); } // Set window state: not minimized/maximized void RestoreWindow(void) { - TRACELOG(LOG_WARNING, "RestoreWindow() not available on PLATFORM_DRM"); + TRACELOG(LOG_WARNING, "RestoreWindow() not available on target platform"); } // Toggle borderless windowed mode void ToggleBorderlessWindowed(void) { - TRACELOG(LOG_WARNING, "ToggleBorderlessWindowed() not available on PLATFORM_DRM"); + TRACELOG(LOG_WARNING, "ToggleBorderlessWindowed() not available on target platform"); } // Set window configuration state using flags void SetWindowState(unsigned int flags) { - TRACELOG(LOG_WARNING, "SetWindowState() not available on PLATFORM_DRM"); + TRACELOG(LOG_WARNING, "SetWindowState() not available on target platform"); } // Clear window configuration state flags void ClearWindowState(unsigned int flags) { - TRACELOG(LOG_WARNING, "ClearWindowState() not available on PLATFORM_DRM"); + TRACELOG(LOG_WARNING, "ClearWindowState() not available on target platform"); } // Set icon for window void SetWindowIcon(Image image) { - TRACELOG(LOG_WARNING, "SetWindowIcon() not available on PLATFORM_DRM"); + TRACELOG(LOG_WARNING, "SetWindowIcon() not available on target platform"); } // Set icon for window void SetWindowIcons(Image *images, int count) { - TRACELOG(LOG_WARNING, "SetWindowIcons() not available on PLATFORM_DRM"); + TRACELOG(LOG_WARNING, "SetWindowIcons() not available on target platform"); } // Set title for window @@ -422,13 +505,13 @@ void SetWindowTitle(const char *title) // Set window position on screen (windowed mode) void SetWindowPosition(int x, int y) { - TRACELOG(LOG_WARNING, "SetWindowPosition() not available on PLATFORM_DRM"); + TRACELOG(LOG_WARNING, "SetWindowPosition() not available on target platform"); } // Set monitor for the current window void SetWindowMonitor(int monitor) { - TRACELOG(LOG_WARNING, "SetWindowMonitor() not available on PLATFORM_DRM"); + TRACELOG(LOG_WARNING, "SetWindowMonitor() not available on target platform"); } // Set window minimum dimensions (FLAG_WINDOW_RESIZABLE) @@ -448,74 +531,74 @@ void SetWindowMaxSize(int width, int height) // Set window dimensions void SetWindowSize(int width, int height) { - TRACELOG(LOG_WARNING, "SetWindowSize() not available on PLATFORM_DRM"); + TRACELOG(LOG_WARNING, "SetWindowSize() not available on target platform"); } // Set window opacity, value opacity is between 0.0 and 1.0 void SetWindowOpacity(float opacity) { - TRACELOG(LOG_WARNING, "SetWindowOpacity() not available on PLATFORM_DRM"); + TRACELOG(LOG_WARNING, "SetWindowOpacity() not available on target platform"); } // Set window focused void SetWindowFocused(void) { - TRACELOG(LOG_WARNING, "SetWindowFocused() not available on PLATFORM_DRM"); + TRACELOG(LOG_WARNING, "SetWindowFocused() not available on target platform"); } // Get native window handle void *GetWindowHandle(void) { - TRACELOG(LOG_WARNING, "GetWindowHandle() not implemented on PLATFORM_DRM"); + TRACELOG(LOG_WARNING, "GetWindowHandle() not implemented on target platform"); return NULL; } // Get number of monitors int GetMonitorCount(void) { - TRACELOG(LOG_WARNING, "GetMonitorCount() not implemented on PLATFORM_DRM"); + TRACELOG(LOG_WARNING, "GetMonitorCount() not implemented on target platform"); return 1; } // Get number of monitors int GetCurrentMonitor(void) { - TRACELOG(LOG_WARNING, "GetCurrentMonitor() not implemented on PLATFORM_DRM"); + TRACELOG(LOG_WARNING, "GetCurrentMonitor() not implemented on target platform"); return 0; } // Get selected monitor position Vector2 GetMonitorPosition(int monitor) { - TRACELOG(LOG_WARNING, "GetMonitorPosition() not implemented on PLATFORM_DRM"); + TRACELOG(LOG_WARNING, "GetMonitorPosition() not implemented on target platform"); return (Vector2){ 0, 0 }; } // Get selected monitor width (currently used by monitor) int GetMonitorWidth(int monitor) { - TRACELOG(LOG_WARNING, "GetMonitorWidth() not implemented on PLATFORM_DRM"); + TRACELOG(LOG_WARNING, "GetMonitorWidth() not implemented on target platform"); return 0; } // Get selected monitor height (currently used by monitor) int GetMonitorHeight(int monitor) { - TRACELOG(LOG_WARNING, "GetMonitorHeight() not implemented on PLATFORM_DRM"); + TRACELOG(LOG_WARNING, "GetMonitorHeight() not implemented on target platform"); return 0; } // Get selected monitor physical width in millimetres int GetMonitorPhysicalWidth(int monitor) { - TRACELOG(LOG_WARNING, "GetMonitorPhysicalWidth() not implemented on PLATFORM_DRM"); + TRACELOG(LOG_WARNING, "GetMonitorPhysicalWidth() not implemented on target platform"); return 0; } // Get selected monitor physical height in millimetres int GetMonitorPhysicalHeight(int monitor) { - TRACELOG(LOG_WARNING, "GetMonitorPhysicalHeight() not implemented on PLATFORM_DRM"); + TRACELOG(LOG_WARNING, "GetMonitorPhysicalHeight() not implemented on target platform"); return 0; } @@ -523,19 +606,19 @@ int GetMonitorPhysicalHeight(int monitor) int GetMonitorRefreshRate(int monitor) { int refresh = 0; - - if ((CORE.Window.connector) && (CORE.Window.modeIndex >= 0)) + + if ((platform.connector) && (platform.modeIndex >= 0)) { - refresh = CORE.Window.connector->modes[CORE.Window.modeIndex].vrefresh; + refresh = platform.connector->modes[platform.modeIndex].vrefresh; } - + return refresh; } // Get the human-readable, UTF-8 encoded name of the selected monitor const char *GetMonitorName(int monitor) { - TRACELOG(LOG_WARNING, "GetMonitorName() not implemented on PLATFORM_DRM"); + TRACELOG(LOG_WARNING, "GetMonitorName() not implemented on target platform"); return ""; } @@ -554,14 +637,14 @@ Vector2 GetWindowScaleDPI(void) // Set clipboard text content void SetClipboardText(const char *text) { - TRACELOG(LOG_WARNING, "SetClipboardText() not implemented on PLATFORM_DRM"); + TRACELOG(LOG_WARNING, "SetClipboardText() not implemented on target platform"); } // Get clipboard text content // NOTE: returned string is allocated and freed by GLFW const char *GetClipboardText(void) { - TRACELOG(LOG_WARNING, "GetClipboardText() not implemented on PLATFORM_DRM"); + TRACELOG(LOG_WARNING, "GetClipboardText() not implemented on target platform"); return NULL; } @@ -595,6 +678,40 @@ void DisableCursor(void) CORE.Input.Mouse.cursorHidden = true; } +// Swap back buffer with front buffer (screen drawing) +void SwapScreenBuffer(void) +{ + eglSwapBuffers(platform.device, platform.surface); + + if (!platform.gbmSurface || (-1 == platform.fd) || !platform.connector || !platform.crtc) TRACELOG(LOG_ERROR, "DISPLAY: DRM initialization failed to swap"); + + struct gbm_bo *bo = gbm_surface_lock_front_buffer(platform.gbmSurface); + if (!bo) TRACELOG(LOG_ERROR, "DISPLAY: Failed GBM to lock front buffer"); + + uint32_t fb = 0; + int result = drmModeAddFB(platform.fd, platform.connector->modes[platform.modeIndex].hdisplay, platform.connector->modes[platform.modeIndex].vdisplay, 24, 32, gbm_bo_get_stride(bo), gbm_bo_get_handle(bo).u32, &fb); + if (result != 0) TRACELOG(LOG_ERROR, "DISPLAY: drmModeAddFB() failed with result: %d", result); + + result = drmModeSetCrtc(platform.fd, platform.crtc->crtc_id, fb, 0, 0, &platform.connector->connector_id, 1, &platform.connector->modes[platform.modeIndex]); + if (result != 0) TRACELOG(LOG_ERROR, "DISPLAY: drmModeSetCrtc() failed with result: %d", result); + + if (platform.prevFB) + { + result = drmModeRmFB(platform.fd, platform.prevFB); + if (result != 0) TRACELOG(LOG_ERROR, "DISPLAY: drmModeRmFB() failed with result: %d", result); + } + + platform.prevFB = fb; + + if (platform.prevBO) gbm_surface_release_buffer(platform.gbmSurface, platform.prevBO); + + platform.prevBO = bo; +} + +//---------------------------------------------------------------------------------- +// Module Functions Definition: Misc +//---------------------------------------------------------------------------------- + // Get elapsed time measure in seconds since InitTimer() double GetTime(void) { @@ -604,33 +721,10 @@ double GetTime(void) unsigned long long int nanoSeconds = (unsigned long long int)ts.tv_sec*1000000000LLU + (unsigned long long int)ts.tv_nsec; time = (double)(nanoSeconds - CORE.Time.base)*1e-9; // Elapsed time since InitTimer() - + return time; } -// Takes a screenshot of current screen (saved a .png) -void TakeScreenshot(const char *fileName) -{ -#if defined(SUPPORT_MODULE_RTEXTURES) - // Security check to (partially) avoid malicious code on PLATFORM_WEB - if (strchr(fileName, '\'') != NULL) { TRACELOG(LOG_WARNING, "SYSTEM: Provided fileName could be potentially malicious, avoid [\'] character"); return; } - - Vector2 scale = GetWindowScaleDPI(); - unsigned char *imgData = rlReadScreenPixels((int)((float)CORE.Window.render.width*scale.x), (int)((float)CORE.Window.render.height*scale.y)); - Image image = { imgData, (int)((float)CORE.Window.render.width*scale.x), (int)((float)CORE.Window.render.height*scale.y), 1, PIXELFORMAT_UNCOMPRESSED_R8G8B8A8 }; - - char path[2048] = { 0 }; - strcpy(path, TextFormat("%s/%s", CORE.Storage.basePath, fileName)); - - ExportImage(image, path); // WARNING: Module required: rtextures - RL_FREE(imgData); - - TRACELOG(LOG_INFO, "SYSTEM: [%s] Screenshot taken successfully", path); -#else - TRACELOG(LOG_WARNING,"IMAGE: ExportImage() requires module: rtextures"); -#endif -} - // Open URL with default system browser (if available) // NOTE: This function is only safe to use if you control the URL given. // A user could craft a malicious string performing another action. @@ -638,20 +732,13 @@ void TakeScreenshot(const char *fileName) // Ref: https://github.com/raysan5/raylib/issues/686 void OpenURL(const char *url) { - TRACELOG(LOG_WARNING, "OpenURL() not implemented on PLATFORM_DRM"); + TRACELOG(LOG_WARNING, "OpenURL() not implemented on target platform"); } //---------------------------------------------------------------------------------- // Module Functions Definition: Inputs //---------------------------------------------------------------------------------- -// Set a custom key to exit program -// NOTE: default exitKey is ESCAPE -void SetExitKey(int key) -{ - CORE.Input.Keyboard.exitKey = key; -} - // Get gamepad internal name id const char *GetGamepadName(int gamepad) { @@ -659,7 +746,7 @@ const char *GetGamepadName(int gamepad) if (CORE.Input.Gamepad.ready[gamepad]) { - ioctl(CORE.Input.Gamepad.streamId[gamepad], JSIOCGNAME(64), &CORE.Input.Gamepad.name[gamepad]); + ioctl(platform.gamepadStreamFd[gamepad], JSIOCGNAME(64), &CORE.Input.Gamepad.name[gamepad]); name = CORE.Input.Gamepad.name[gamepad]; } @@ -675,7 +762,7 @@ int GetGamepadAxisCount(int gamepad) // Set internal gamepad mappings int SetGamepadMappings(const char *mappings) { - TRACELOG(LOG_WARNING, "SetGamepadMappings() not implemented on PLATFORM_DRM"); + TRACELOG(LOG_WARNING, "SetGamepadMappings() not implemented on target platform"); return 0; } @@ -723,7 +810,7 @@ float GetMouseWheelMove(void) // Set mouse cursor void SetMouseCursor(int cursor) { - TRACELOG(LOG_WARNING, "SetMouseCursor() not implemented on PLATFORM_DRM"); + TRACELOG(LOG_WARNING, "SetMouseCursor() not implemented on target platform"); } // Get touch position X for touch point 0 (relative to screen size) @@ -742,43 +829,13 @@ int GetTouchY(void) Vector2 GetTouchPosition(int index) { Vector2 position = { -1.0f, -1.0f }; - + if (index < MAX_TOUCH_POINTS) position = CORE.Input.Touch.position[index]; else TRACELOG(LOG_WARNING, "INPUT: Required touch point out of range (Max touch points: %i)", MAX_TOUCH_POINTS); - + return position; } -// Swap back buffer with front buffer (screen drawing) -void SwapScreenBuffer(void) -{ - eglSwapBuffers(CORE.Window.device, CORE.Window.surface); - - if (!CORE.Window.gbmSurface || (-1 == CORE.Window.fd) || !CORE.Window.connector || !CORE.Window.crtc) TRACELOG(LOG_ERROR, "DISPLAY: DRM initialization failed to swap"); - - struct gbm_bo *bo = gbm_surface_lock_front_buffer(CORE.Window.gbmSurface); - if (!bo) TRACELOG(LOG_ERROR, "DISPLAY: Failed GBM to lock front buffer"); - - uint32_t fb = 0; - int result = drmModeAddFB(CORE.Window.fd, CORE.Window.connector->modes[CORE.Window.modeIndex].hdisplay, CORE.Window.connector->modes[CORE.Window.modeIndex].vdisplay, 24, 32, gbm_bo_get_stride(bo), gbm_bo_get_handle(bo).u32, &fb); - if (result != 0) TRACELOG(LOG_ERROR, "DISPLAY: drmModeAddFB() failed with result: %d", result); - - result = drmModeSetCrtc(CORE.Window.fd, CORE.Window.crtc->crtc_id, fb, 0, 0, &CORE.Window.connector->connector_id, 1, &CORE.Window.connector->modes[CORE.Window.modeIndex]); - if (result != 0) TRACELOG(LOG_ERROR, "DISPLAY: drmModeSetCrtc() failed with result: %d", result); - - if (CORE.Window.prevFB) - { - result = drmModeRmFB(CORE.Window.fd, CORE.Window.prevFB); - if (result != 0) TRACELOG(LOG_ERROR, "DISPLAY: drmModeRmFB() failed with result: %d", result); - } - - CORE.Window.prevFB = fb; - - if (CORE.Window.prevBO) gbm_surface_release_buffer(CORE.Window.gbmSurface, CORE.Window.prevBO); - - CORE.Window.prevBO = bo; -} - // Register all input events void PollInputEvents(void) { @@ -791,7 +848,7 @@ void PollInputEvents(void) // Reset keys/chars pressed registered CORE.Input.Keyboard.keyPressedQueueCount = 0; CORE.Input.Keyboard.charPressedQueueCount = 0; - + // Reset key repeats for (int i = 0; i < MAX_KEYBOARD_KEYS; i++) CORE.Input.Keyboard.keyRepeatInFrame[i] = 0; @@ -810,12 +867,12 @@ void PollInputEvents(void) // Register previous mouse states CORE.Input.Mouse.previousWheelMove = CORE.Input.Mouse.currentWheelMove; - CORE.Input.Mouse.currentWheelMove = CORE.Input.Mouse.eventWheelMove; - CORE.Input.Mouse.eventWheelMove = (Vector2){ 0.0f, 0.0f }; + CORE.Input.Mouse.currentWheelMove = platform.eventWheelMove; + platform.eventWheelMove = (Vector2){ 0.0f, 0.0f }; for (int i = 0; i < MAX_MOUSE_BUTTONS; i++) { CORE.Input.Mouse.previousButtonState[i] = CORE.Input.Mouse.currentButtonState[i]; - CORE.Input.Mouse.currentButtonState[i] = CORE.Input.Mouse.currentButtonStateEvdev[i]; + CORE.Input.Mouse.currentButtonState[i] = platform.currentButtonStateEvdev[i]; } // Register gamepads buttons events @@ -832,21 +889,20 @@ void PollInputEvents(void) for (int i = 0; i < MAX_TOUCH_POINTS; i++) CORE.Input.Touch.previousTouchState[i] = CORE.Input.Touch.currentTouchState[i]; // Reset touch positions - // TODO: It resets on PLATFORM_WEB the mouse position and not filled again until a move-event, - // so, if mouse is not moved it returns a (0, 0) position... this behaviour should be reviewed! //for (int i = 0; i < MAX_TOUCH_POINTS; i++) CORE.Input.Touch.position[i] = (Vector2){ 0, 0 }; #if defined(SUPPORT_SSH_KEYBOARD_RPI) // NOTE: Keyboard reading could be done using input_event(s) or just read from stdin, both methods are used here. // stdin reading is still used for legacy purposes, it allows keyboard input trough SSH console - if (!CORE.Input.Keyboard.evtMode) ProcessKeyboard(); + if (!platform.eventKeyboardMode) ProcessKeyboard(); // NOTE: Mouse input events polling is done asynchronously in another pthread - EventThread() // NOTE: Gamepad (Joystick) input events polling is done asynchonously in another pthread - GamepadThread() #endif } + //---------------------------------------------------------------------------------- // Module Internal Functions Definition //---------------------------------------------------------------------------------- @@ -873,41 +929,41 @@ static bool InitGraphicsDevice(int width, int height) CORE.Window.fullscreen = true; CORE.Window.flags |= FLAG_FULLSCREEN_MODE; - CORE.Window.fd = -1; - CORE.Window.connector = NULL; - CORE.Window.modeIndex = -1; - CORE.Window.crtc = NULL; - CORE.Window.gbmDevice = NULL; - CORE.Window.gbmSurface = NULL; - CORE.Window.prevBO = NULL; - CORE.Window.prevFB = 0; + platform.fd = -1; + platform.connector = NULL; + platform.modeIndex = -1; + platform.crtc = NULL; + platform.gbmDevice = NULL; + platform.gbmSurface = NULL; + platform.prevBO = NULL; + platform.prevFB = 0; #if defined(DEFAULT_GRAPHIC_DEVICE_DRM) - CORE.Window.fd = open(DEFAULT_GRAPHIC_DEVICE_DRM, O_RDWR); + platform.fd = open(DEFAULT_GRAPHIC_DEVICE_DRM, O_RDWR); #else TRACELOG(LOG_INFO, "DISPLAY: No graphic card set, trying platform-gpu-card"); - CORE.Window.fd = open("/dev/dri/by-path/platform-gpu-card", O_RDWR); // VideoCore VI (Raspberry Pi 4) + platform.fd = open("/dev/dri/by-path/platform-gpu-card", O_RDWR); // VideoCore VI (Raspberry Pi 4) - if ((CORE.Window.fd == -1) || (drmModeGetResources(CORE.Window.fd) == NULL)) + if ((platform.fd == -1) || (drmModeGetResources(platform.fd) == NULL)) { TRACELOG(LOG_INFO, "DISPLAY: Failed to open platform-gpu-card, trying card1"); - CORE.Window.fd = open("/dev/dri/card1", O_RDWR); // Other Embedded + platform.fd = open("/dev/dri/card1", O_RDWR); // Other Embedded } - if ((CORE.Window.fd == -1) || (drmModeGetResources(CORE.Window.fd) == NULL)) + if ((platform.fd == -1) || (drmModeGetResources(platform.fd) == NULL)) { TRACELOG(LOG_INFO, "DISPLAY: Failed to open graphic card1, trying card0"); - CORE.Window.fd = open("/dev/dri/card0", O_RDWR); // VideoCore IV (Raspberry Pi 1-3) + platform.fd = open("/dev/dri/card0", O_RDWR); // VideoCore IV (Raspberry Pi 1-3) } #endif - if (CORE.Window.fd == -1) + if (platform.fd == -1) { TRACELOG(LOG_WARNING, "DISPLAY: Failed to open graphic card"); return false; } - drmModeRes *res = drmModeGetResources(CORE.Window.fd); + drmModeRes *res = drmModeGetResources(platform.fd); if (!res) { TRACELOG(LOG_WARNING, "DISPLAY: Failed get DRM resources"); @@ -915,18 +971,18 @@ static bool InitGraphicsDevice(int width, int height) } TRACELOG(LOG_TRACE, "DISPLAY: Connectors found: %i", res->count_connectors); - + for (size_t i = 0; i < res->count_connectors; i++) { TRACELOG(LOG_TRACE, "DISPLAY: Connector index %i", i); - - drmModeConnector *con = drmModeGetConnector(CORE.Window.fd, res->connectors[i]); + + drmModeConnector *con = drmModeGetConnector(platform.fd, res->connectors[i]); TRACELOG(LOG_TRACE, "DISPLAY: Connector modes detected: %i", con->count_modes); - + if ((con->connection == DRM_MODE_CONNECTED) && (con->encoder_id)) { TRACELOG(LOG_TRACE, "DISPLAY: DRM mode connected"); - CORE.Window.connector = con; + platform.connector = con; break; } else @@ -936,14 +992,14 @@ static bool InitGraphicsDevice(int width, int height) } } - if (!CORE.Window.connector) + if (!platform.connector) { TRACELOG(LOG_WARNING, "DISPLAY: No suitable DRM connector found"); drmModeFreeResources(res); return false; } - drmModeEncoder *enc = drmModeGetEncoder(CORE.Window.fd, CORE.Window.connector->encoder_id); + drmModeEncoder *enc = drmModeGetEncoder(platform.fd, platform.connector->encoder_id); if (!enc) { TRACELOG(LOG_WARNING, "DISPLAY: Failed to get DRM mode encoder"); @@ -951,8 +1007,8 @@ static bool InitGraphicsDevice(int width, int height) return false; } - CORE.Window.crtc = drmModeGetCrtc(CORE.Window.fd, enc->crtc_id); - if (!CORE.Window.crtc) + platform.crtc = drmModeGetCrtc(platform.fd, enc->crtc_id); + if (!platform.crtc) { TRACELOG(LOG_WARNING, "DISPLAY: Failed to get DRM mode crtc"); drmModeFreeEncoder(enc); @@ -965,9 +1021,9 @@ static bool InitGraphicsDevice(int width, int height) { TRACELOG(LOG_TRACE, "DISPLAY: Selecting DRM connector mode for current used mode..."); - CORE.Window.modeIndex = FindMatchingConnectorMode(CORE.Window.connector, &CORE.Window.crtc->mode); + platform.modeIndex = FindMatchingConnectorMode(platform.connector, &platform.crtc->mode); - if (CORE.Window.modeIndex < 0) + if (platform.modeIndex < 0) { TRACELOG(LOG_WARNING, "DISPLAY: No matching DRM connector mode found"); drmModeFreeEncoder(enc); @@ -983,19 +1039,19 @@ static bool InitGraphicsDevice(int width, int height) const int fps = (CORE.Time.target > 0)? (1.0/CORE.Time.target) : 60; // Try to find an exact matching mode - CORE.Window.modeIndex = FindExactConnectorMode(CORE.Window.connector, CORE.Window.screen.width, CORE.Window.screen.height, fps, allowInterlaced); + platform.modeIndex = FindExactConnectorMode(platform.connector, CORE.Window.screen.width, CORE.Window.screen.height, fps, allowInterlaced); // If nothing found, try to find a nearly matching mode - if (CORE.Window.modeIndex < 0) CORE.Window.modeIndex = FindNearestConnectorMode(CORE.Window.connector, CORE.Window.screen.width, CORE.Window.screen.height, fps, allowInterlaced); + if (platform.modeIndex < 0) platform.modeIndex = FindNearestConnectorMode(platform.connector, CORE.Window.screen.width, CORE.Window.screen.height, fps, allowInterlaced); // If nothing found, try to find an exactly matching mode including interlaced - if (CORE.Window.modeIndex < 0) CORE.Window.modeIndex = FindExactConnectorMode(CORE.Window.connector, CORE.Window.screen.width, CORE.Window.screen.height, fps, true); + if (platform.modeIndex < 0) platform.modeIndex = FindExactConnectorMode(platform.connector, CORE.Window.screen.width, CORE.Window.screen.height, fps, true); // If nothing found, try to find a nearly matching mode including interlaced - if (CORE.Window.modeIndex < 0) CORE.Window.modeIndex = FindNearestConnectorMode(CORE.Window.connector, CORE.Window.screen.width, CORE.Window.screen.height, fps, true); + if (platform.modeIndex < 0) platform.modeIndex = FindNearestConnectorMode(platform.connector, CORE.Window.screen.width, CORE.Window.screen.height, fps, true); // If nothing found, there is no suitable mode - if (CORE.Window.modeIndex < 0) + if (platform.modeIndex < 0) { TRACELOG(LOG_WARNING, "DISPLAY: Failed to find a suitable DRM connector mode"); drmModeFreeEncoder(enc); @@ -1003,13 +1059,13 @@ static bool InitGraphicsDevice(int width, int height) return false; } - CORE.Window.display.width = CORE.Window.connector->modes[CORE.Window.modeIndex].hdisplay; - CORE.Window.display.height = CORE.Window.connector->modes[CORE.Window.modeIndex].vdisplay; + CORE.Window.display.width = platform.connector->modes[platform.modeIndex].hdisplay; + CORE.Window.display.height = platform.connector->modes[platform.modeIndex].vdisplay; - TRACELOG(LOG_INFO, "DISPLAY: Selected DRM connector mode %s (%ux%u%c@%u)", CORE.Window.connector->modes[CORE.Window.modeIndex].name, - CORE.Window.connector->modes[CORE.Window.modeIndex].hdisplay, CORE.Window.connector->modes[CORE.Window.modeIndex].vdisplay, - (CORE.Window.connector->modes[CORE.Window.modeIndex].flags & DRM_MODE_FLAG_INTERLACE)? 'i' : 'p', - CORE.Window.connector->modes[CORE.Window.modeIndex].vrefresh); + TRACELOG(LOG_INFO, "DISPLAY: Selected DRM connector mode %s (%ux%u%c@%u)", platform.connector->modes[platform.modeIndex].name, + platform.connector->modes[platform.modeIndex].hdisplay, platform.connector->modes[platform.modeIndex].vdisplay, + (platform.connector->modes[platform.modeIndex].flags & DRM_MODE_FLAG_INTERLACE)? 'i' : 'p', + platform.connector->modes[platform.modeIndex].vrefresh); // Use the width and height of the surface for render CORE.Window.render.width = CORE.Window.screen.width; @@ -1021,16 +1077,16 @@ static bool InitGraphicsDevice(int width, int height) drmModeFreeResources(res); res = NULL; - CORE.Window.gbmDevice = gbm_create_device(CORE.Window.fd); - if (!CORE.Window.gbmDevice) + platform.gbmDevice = gbm_create_device(platform.fd); + if (!platform.gbmDevice) { TRACELOG(LOG_WARNING, "DISPLAY: Failed to create GBM device"); return false; } - CORE.Window.gbmSurface = gbm_surface_create(CORE.Window.gbmDevice, CORE.Window.connector->modes[CORE.Window.modeIndex].hdisplay, - CORE.Window.connector->modes[CORE.Window.modeIndex].vdisplay, GBM_FORMAT_ARGB8888, GBM_BO_USE_SCANOUT | GBM_BO_USE_RENDERING); - if (!CORE.Window.gbmSurface) + platform.gbmSurface = gbm_surface_create(platform.gbmDevice, platform.connector->modes[platform.modeIndex].hdisplay, + platform.connector->modes[platform.modeIndex].vdisplay, GBM_FORMAT_ARGB8888, GBM_BO_USE_SCANOUT | GBM_BO_USE_RENDERING); + if (!platform.gbmSurface) { TRACELOG(LOG_WARNING, "DISPLAY: Failed to create GBM surface"); return false; @@ -1069,22 +1125,22 @@ static bool InitGraphicsDevice(int width, int height) EGLint numConfigs = 0; // Get an EGL device connection - CORE.Window.device = eglGetDisplay((EGLNativeDisplayType)CORE.Window.gbmDevice); - if (CORE.Window.device == EGL_NO_DISPLAY) + platform.device = eglGetDisplay((EGLNativeDisplayType)platform.gbmDevice); + if (platform.device == EGL_NO_DISPLAY) { TRACELOG(LOG_WARNING, "DISPLAY: Failed to initialize EGL device"); return false; } // Initialize the EGL device connection - if (eglInitialize(CORE.Window.device, NULL, NULL) == EGL_FALSE) + if (eglInitialize(platform.device, NULL, NULL) == EGL_FALSE) { // If all of the calls to eglInitialize returned EGL_FALSE then an error has occurred. TRACELOG(LOG_WARNING, "DISPLAY: Failed to initialize EGL device"); return false; } - if (!eglChooseConfig(CORE.Window.device, NULL, NULL, 0, &numConfigs)) + if (!eglChooseConfig(platform.device, NULL, NULL, 0, &numConfigs)) { TRACELOG(LOG_WARNING, "DISPLAY: Failed to get EGL config count: 0x%x", eglGetError()); return false; @@ -1100,7 +1156,7 @@ static bool InitGraphicsDevice(int width, int height) } EGLint matchingNumConfigs = 0; - if (!eglChooseConfig(CORE.Window.device, framebufferAttribs, configs, numConfigs, &matchingNumConfigs)) + if (!eglChooseConfig(platform.device, framebufferAttribs, configs, numConfigs, &matchingNumConfigs)) { TRACELOG(LOG_WARNING, "DISPLAY: Failed to choose EGL config: 0x%x", eglGetError()); free(configs); @@ -1114,7 +1170,7 @@ static bool InitGraphicsDevice(int width, int height) for (EGLint i = 0; i < matchingNumConfigs; ++i) { EGLint id = 0; - if (!eglGetConfigAttrib(CORE.Window.device, configs[i], EGL_NATIVE_VISUAL_ID, &id)) + if (!eglGetConfigAttrib(platform.device, configs[i], EGL_NATIVE_VISUAL_ID, &id)) { TRACELOG(LOG_WARNING, "DISPLAY: Failed to get EGL config attribute: 0x%x", eglGetError()); continue; @@ -1123,7 +1179,7 @@ static bool InitGraphicsDevice(int width, int height) if (GBM_FORMAT_ARGB8888 == id) { TRACELOG(LOG_TRACE, "DISPLAY: Using EGL config: %d", i); - CORE.Window.config = configs[i]; + platform.config = configs[i]; found = 1; break; } @@ -1141,8 +1197,8 @@ static bool InitGraphicsDevice(int width, int height) eglBindAPI(EGL_OPENGL_ES_API); // Create an EGL rendering context - CORE.Window.context = eglCreateContext(CORE.Window.device, CORE.Window.config, EGL_NO_CONTEXT, contextAttribs); - if (CORE.Window.context == EGL_NO_CONTEXT) + platform.context = eglCreateContext(platform.device, platform.config, EGL_NO_CONTEXT, contextAttribs); + if (platform.context == EGL_NO_CONTEXT) { TRACELOG(LOG_WARNING, "DISPLAY: Failed to create EGL context"); return false; @@ -1150,8 +1206,8 @@ static bool InitGraphicsDevice(int width, int height) // Create an EGL window surface //--------------------------------------------------------------------------------- - CORE.Window.surface = eglCreateWindowSurface(CORE.Window.device, CORE.Window.config, (EGLNativeWindowType)CORE.Window.gbmSurface, NULL); - if (EGL_NO_SURFACE == CORE.Window.surface) + platform.surface = eglCreateWindowSurface(platform.device, platform.config, (EGLNativeWindowType)platform.gbmSurface, NULL); + if (EGL_NO_SURFACE == platform.surface) { TRACELOG(LOG_WARNING, "DISPLAY: Failed to create EGL window surface: 0x%04x", eglGetError()); return false; @@ -1165,9 +1221,9 @@ static bool InitGraphicsDevice(int width, int height) SetupFramebuffer(CORE.Window.display.width, CORE.Window.display.height); // There must be at least one frame displayed before the buffers are swapped - //eglSwapInterval(CORE.Window.device, 1); + //eglSwapInterval(platform.device, 1); - if (eglMakeCurrent(CORE.Window.device, CORE.Window.surface, CORE.Window.surface, CORE.Window.context) == EGL_FALSE) + if (eglMakeCurrent(platform.device, platform.surface, platform.surface, platform.context) == EGL_FALSE) { TRACELOG(LOG_WARNING, "DISPLAY: Failed to attach EGL rendering context to EGL surface"); return false; @@ -1210,11 +1266,11 @@ static void InitKeyboard(void) // Reading directly from stdin will give chars already key-mapped by kernel to ASCII or UNICODE // Save terminal keyboard settings - tcgetattr(STDIN_FILENO, &CORE.Input.Keyboard.defaultSettings); + tcgetattr(STDIN_FILENO, &platform.defaultSettings); // Reconfigure terminal with new settings struct termios keyboardNewSettings = { 0 }; - keyboardNewSettings = CORE.Input.Keyboard.defaultSettings; + keyboardNewSettings = platform.defaultSettings; // New terminal settings for keyboard: turn off buffering (non-canonical mode), echo and key processing // NOTE: ISIG controls if ^C and ^Z generate break signals or not @@ -1227,11 +1283,11 @@ static void InitKeyboard(void) tcsetattr(STDIN_FILENO, TCSANOW, &keyboardNewSettings); // Save old keyboard mode to restore it at the end - CORE.Input.Keyboard.defaultFileFlags = fcntl(STDIN_FILENO, F_GETFL, 0); // F_GETFL: Get the file access mode and the file status flags - fcntl(STDIN_FILENO, F_SETFL, CORE.Input.Keyboard.defaultFileFlags | O_NONBLOCK); // F_SETFL: Set the file status flags to the value specified + platform.defaultFileFlags = fcntl(STDIN_FILENO, F_GETFL, 0); // F_GETFL: Get the file access mode and the file status flags + fcntl(STDIN_FILENO, F_SETFL, platform.defaultFileFlags | O_NONBLOCK); // F_SETFL: Set the file status flags to the value specified // NOTE: If ioctl() returns -1, it means the call failed for some reason (error code set in errno) - int result = ioctl(STDIN_FILENO, KDGKBMODE, &CORE.Input.Keyboard.defaultMode); + int result = ioctl(STDIN_FILENO, KDGKBMODE, &platform.defaultKeyboardMode); // In case of failure, it could mean a remote keyboard is used (SSH) if (result < 0) TRACELOG(LOG_WARNING, "RPI: Failed to change keyboard mode, an SSH keyboard is probably used"); @@ -1253,11 +1309,11 @@ static void InitKeyboard(void) static void RestoreKeyboard(void) { // Reset to default keyboard settings - tcsetattr(STDIN_FILENO, TCSANOW, &CORE.Input.Keyboard.defaultSettings); + tcsetattr(STDIN_FILENO, TCSANOW, &platform.defaultSettings); // Reconfigure keyboard to default mode - fcntl(STDIN_FILENO, F_SETFL, CORE.Input.Keyboard.defaultFileFlags); - ioctl(STDIN_FILENO, KDSKBMODE, CORE.Input.Keyboard.defaultMode); + fcntl(STDIN_FILENO, F_SETFL, platform.defaultFileFlags); + ioctl(STDIN_FILENO, KDSKBMODE, platform.defaultKeyboardMode); } #if defined(SUPPORT_SSH_KEYBOARD_RPI) @@ -1376,7 +1432,7 @@ static void ProcessKeyboard(void) } #endif // SUPPORT_SSH_KEYBOARD_RPI -// Initialise user input from evdev(/dev/input/event) +// Initialise user input from evdev(/dev/input/event) // this means mouse, keyboard or gamepad devices static void InitEvdevInput(void) { @@ -1385,7 +1441,7 @@ static void InitEvdevInput(void) struct dirent *entity = NULL; // Initialise keyboard file descriptor - CORE.Input.Keyboard.fd = -1; + platform.keyboardFd = -1; // Reset variables for (int i = 0; i < MAX_TOUCH_POINTS; ++i) @@ -1447,9 +1503,9 @@ static void ConfigureEvdevDevice(char *device) // Open the device and allocate worker //------------------------------------------------------------------------------------------------------- // Find a free spot in the workers array - for (int i = 0; i < sizeof(CORE.Input.eventWorker)/sizeof(InputEventWorker); ++i) + for (int i = 0; i < sizeof(platform.eventWorker)/sizeof(InputEventWorker); ++i) { - if (CORE.Input.eventWorker[i].threadId == 0) + if (platform.eventWorker[i].threadId == 0) { freeWorkerId = i; break; @@ -1459,7 +1515,7 @@ static void ConfigureEvdevDevice(char *device) // Select the free worker from array if (freeWorkerId >= 0) { - worker = &(CORE.Input.eventWorker[freeWorkerId]); // Grab a pointer to the worker + worker = &(platform.eventWorker[freeWorkerId]); // Grab a pointer to the worker memset(worker, 0, sizeof(InputEventWorker)); // Clear the worker } else @@ -1570,13 +1626,13 @@ static void ConfigureEvdevDevice(char *device) // Decide what to do with the device //------------------------------------------------------------------------------------------------------- - if (worker->isKeyboard && (CORE.Input.Keyboard.fd == -1)) + if (worker->isKeyboard && (platform.keyboardFd == -1)) { // Use the first keyboard encountered. This assumes that a device that says it's a keyboard is just a // keyboard. The keyboard is polled synchronously, whereas other input devices are polled in separate // threads so that they don't drop events when the frame rate is slow. TRACELOG(LOG_INFO, "RPI: Opening keyboard device: %s", device); - CORE.Input.Keyboard.fd = worker->fd; + platform.keyboardFd = worker->fd; } else if (worker->isTouch || worker->isMouse) { @@ -1600,21 +1656,21 @@ static void ConfigureEvdevDevice(char *device) // Find touchscreen with the highest index int maxTouchNumber = -1; - for (int i = 0; i < sizeof(CORE.Input.eventWorker)/sizeof(InputEventWorker); ++i) + for (int i = 0; i < sizeof(platform.eventWorker)/sizeof(InputEventWorker); ++i) { - if (CORE.Input.eventWorker[i].isTouch && (CORE.Input.eventWorker[i].eventNum > maxTouchNumber)) maxTouchNumber = CORE.Input.eventWorker[i].eventNum; + if (platform.eventWorker[i].isTouch && (platform.eventWorker[i].eventNum > maxTouchNumber)) maxTouchNumber = platform.eventWorker[i].eventNum; } // Find touchscreens with lower indexes - for (int i = 0; i < sizeof(CORE.Input.eventWorker)/sizeof(InputEventWorker); ++i) + for (int i = 0; i < sizeof(platform.eventWorker)/sizeof(InputEventWorker); ++i) { - if (CORE.Input.eventWorker[i].isTouch && (CORE.Input.eventWorker[i].eventNum < maxTouchNumber)) + if (platform.eventWorker[i].isTouch && (platform.eventWorker[i].eventNum < maxTouchNumber)) { - if (CORE.Input.eventWorker[i].threadId != 0) + if (platform.eventWorker[i].threadId != 0) { TRACELOG(LOG_WARNING, "RPI: Found duplicate touchscreen, killing touchscreen on event: %d", i); - pthread_cancel(CORE.Input.eventWorker[i].threadId); - close(CORE.Input.eventWorker[i].fd); + pthread_cancel(platform.eventWorker[i].threadId); + close(platform.eventWorker[i].fd); } } } @@ -1648,7 +1704,7 @@ static void PollKeyboardEvents(void) 243, 244, 245, 246, 247, 248, 0, 0, 0, 0, 0, 0, 0 }; - int fd = CORE.Input.Keyboard.fd; + int fd = platform.keyboardFd; if (fd == -1) return; struct input_event event = { 0 }; @@ -1662,7 +1718,7 @@ static void PollKeyboardEvents(void) { #if defined(SUPPORT_SSH_KEYBOARD_RPI) // Change keyboard mode to events - CORE.Input.Keyboard.evtMode = true; + platform.eventKeyboardMode = true; #endif // Keyboard button parsing if ((event.code >= 1) && (event.code <= 255)) //Keyboard keys appear for codes 1 to 255 @@ -1735,7 +1791,7 @@ static void *EventThread(void *arg) gestureUpdate = true; } - if (event.code == REL_WHEEL) CORE.Input.Mouse.eventWheelMove.y += event.value; + if (event.code == REL_WHEEL) platform.eventWheelMove.y += event.value; } // Absolute movement parsing @@ -1786,11 +1842,11 @@ static void *EventThread(void *arg) // Touchscreen tap if (event.code == ABS_PRESSURE) { - int previousMouseLeftButtonState = CORE.Input.Mouse.currentButtonStateEvdev[MOUSE_BUTTON_LEFT]; + int previousMouseLeftButtonState = platform.currentButtonStateEvdev[MOUSE_BUTTON_LEFT]; if (!event.value && previousMouseLeftButtonState) { - CORE.Input.Mouse.currentButtonStateEvdev[MOUSE_BUTTON_LEFT] = 0; + platform.currentButtonStateEvdev[MOUSE_BUTTON_LEFT] = 0; touchAction = 0; // TOUCH_ACTION_UP gestureUpdate = true; @@ -1798,7 +1854,7 @@ static void *EventThread(void *arg) if (event.value && !previousMouseLeftButtonState) { - CORE.Input.Mouse.currentButtonStateEvdev[MOUSE_BUTTON_LEFT] = 1; + platform.currentButtonStateEvdev[MOUSE_BUTTON_LEFT] = 1; touchAction = 1; // TOUCH_ACTION_DOWN gestureUpdate = true; @@ -1813,19 +1869,19 @@ static void *EventThread(void *arg) // Mouse button parsing if ((event.code == BTN_TOUCH) || (event.code == BTN_LEFT)) { - CORE.Input.Mouse.currentButtonStateEvdev[MOUSE_BUTTON_LEFT] = event.value; + platform.currentButtonStateEvdev[MOUSE_BUTTON_LEFT] = event.value; if (event.value > 0) touchAction = 1; // TOUCH_ACTION_DOWN else touchAction = 0; // TOUCH_ACTION_UP gestureUpdate = true; } - if (event.code == BTN_RIGHT) CORE.Input.Mouse.currentButtonStateEvdev[MOUSE_BUTTON_RIGHT] = event.value; - if (event.code == BTN_MIDDLE) CORE.Input.Mouse.currentButtonStateEvdev[MOUSE_BUTTON_MIDDLE] = event.value; - if (event.code == BTN_SIDE) CORE.Input.Mouse.currentButtonStateEvdev[MOUSE_BUTTON_SIDE] = event.value; - if (event.code == BTN_EXTRA) CORE.Input.Mouse.currentButtonStateEvdev[MOUSE_BUTTON_EXTRA] = event.value; - if (event.code == BTN_FORWARD) CORE.Input.Mouse.currentButtonStateEvdev[MOUSE_BUTTON_FORWARD] = event.value; - if (event.code == BTN_BACK) CORE.Input.Mouse.currentButtonStateEvdev[MOUSE_BUTTON_BACK] = event.value; + if (event.code == BTN_RIGHT) platform.currentButtonStateEvdev[MOUSE_BUTTON_RIGHT] = event.value; + if (event.code == BTN_MIDDLE) platform.currentButtonStateEvdev[MOUSE_BUTTON_MIDDLE] = event.value; + if (event.code == BTN_SIDE) platform.currentButtonStateEvdev[MOUSE_BUTTON_SIDE] = event.value; + if (event.code == BTN_EXTRA) platform.currentButtonStateEvdev[MOUSE_BUTTON_EXTRA] = event.value; + if (event.code == BTN_FORWARD) platform.currentButtonStateEvdev[MOUSE_BUTTON_FORWARD] = event.value; + if (event.code == BTN_BACK) platform.currentButtonStateEvdev[MOUSE_BUTTON_BACK] = event.value; } // Screen confinement @@ -1845,7 +1901,7 @@ static void *EventThread(void *arg) if (CORE.Input.Touch.position[i].x >= 0) CORE.Input.Touch.pointCount++; } -#if defined(SUPPORT_GESTURES_SYSTEM) // PLATFORM_DRM +#if defined(SUPPORT_GESTURES_SYSTEM) if (gestureUpdate) { GestureEvent gestureEvent = { 0 }; @@ -1881,7 +1937,7 @@ static void InitGamepad(void) { sprintf(gamepadDev, "%s%i", DEFAULT_GAMEPAD_DEV, i); - if ((CORE.Input.Gamepad.streamId[i] = open(gamepadDev, O_RDONLY | O_NONBLOCK)) < 0) + if ((platform.gamepadStreamFd[i] = open(gamepadDev, O_RDONLY | O_NONBLOCK)) < 0) { // NOTE: Only show message for first gamepad if (i == 0) TRACELOG(LOG_WARNING, "RPI: Failed to open Gamepad device, no gamepad available"); @@ -1893,15 +1949,11 @@ static void InitGamepad(void) // NOTE: Only create one thread if (i == 0) { - int error = pthread_create(&CORE.Input.Gamepad.threadId, NULL, &GamepadThread, NULL); + int error = pthread_create(&platform.gamepadThreadId, NULL, &GamepadThread, NULL); if (error != 0) TRACELOG(LOG_WARNING, "RPI: Failed to create gamepad input event thread"); else TRACELOG(LOG_INFO, "RPI: Gamepad device initialized successfully"); } - - int axisCount = 0; - if (CORE.Input.Gamepad.ready[i]) ioctl(CORE.Input.Gamepad.streamId[i], JSIOCGAXES, &axisCount); - CORE.Input.Gamepad.axisCount = axisCount; } } } @@ -1923,11 +1975,18 @@ static void *GamepadThread(void *arg) // Read gamepad event struct js_event gamepadEvent = { 0 }; + int axisCount = 0; + while (!CORE.Window.shouldClose) { for (int i = 0; i < MAX_GAMEPADS; i++) { - if (read(CORE.Input.Gamepad.streamId[i], &gamepadEvent, sizeof(struct js_event)) == (int)sizeof(struct js_event)) + // Update the axis count for each gamepad. + axisCount = 0; + if (CORE.Input.Gamepad.ready[i]) ioctl(platform.gamepadStreamFd[i], JSIOCGAXES, &axisCount); + CORE.Input.Gamepad.axisCount = axisCount; + + if (read(platform.gamepadStreamFd[i], &gamepadEvent, sizeof(struct js_event)) == (int)sizeof(struct js_event)) { gamepadEvent.type &= ~JS_EVENT_INIT; // Ignore synthetic events @@ -1977,7 +2036,7 @@ static int FindMatchingConnectorMode(const drmModeConnector *connector, const dr TRACELOG(LOG_TRACE, "DISPLAY: DRM mode: %d %ux%u@%u %s", i, connector->modes[i].hdisplay, connector->modes[i].vdisplay, connector->modes[i].vrefresh, (connector->modes[i].flags & DRM_MODE_FLAG_INTERLACE)? "interlaced" : "progressive"); - if (0 == BINCMP(&CORE.Window.crtc->mode, &CORE.Window.connector->modes[i])) return i; + if (0 == BINCMP(&platform.crtc->mode, &platform.connector->modes[i])) return i; } return -1; @@ -1992,9 +2051,9 @@ static int FindExactConnectorMode(const drmModeConnector *connector, uint width, if (NULL == connector) return -1; - for (int i = 0; i < CORE.Window.connector->count_modes; i++) + for (int i = 0; i < platform.connector->count_modes; i++) { - const drmModeModeInfo *const mode = &CORE.Window.connector->modes[i]; + const drmModeModeInfo *const mode = &platform.connector->modes[i]; TRACELOG(LOG_TRACE, "DISPLAY: DRM Mode %d %ux%u@%u %s", i, mode->hdisplay, mode->vdisplay, mode->vrefresh, (mode->flags & DRM_MODE_FLAG_INTERLACE)? "interlaced" : "progressive"); @@ -2015,9 +2074,9 @@ static int FindNearestConnectorMode(const drmModeConnector *connector, uint widt if (NULL == connector) return -1; int nearestIndex = -1; - for (int i = 0; i < CORE.Window.connector->count_modes; i++) + for (int i = 0; i < platform.connector->count_modes; i++) { - const drmModeModeInfo *const mode = &CORE.Window.connector->modes[i]; + const drmModeModeInfo *const mode = &platform.connector->modes[i]; TRACELOG(LOG_TRACE, "DISPLAY: DRM mode: %d %ux%u@%u %s", i, mode->hdisplay, mode->vdisplay, mode->vrefresh, (mode->flags & DRM_MODE_FLAG_INTERLACE)? "interlaced" : "progressive"); @@ -2044,9 +2103,9 @@ static int FindNearestConnectorMode(const drmModeConnector *connector, uint widt const int heightDiff = abs(mode->vdisplay - height); const int fpsDiff = abs(mode->vrefresh - fps); - const int nearestWidthDiff = abs(CORE.Window.connector->modes[nearestIndex].hdisplay - width); - const int nearestHeightDiff = abs(CORE.Window.connector->modes[nearestIndex].vdisplay - height); - const int nearestFpsDiff = abs(CORE.Window.connector->modes[nearestIndex].vrefresh - fps); + const int nearestWidthDiff = abs(platform.connector->modes[nearestIndex].hdisplay - width); + const int nearestHeightDiff = abs(platform.connector->modes[nearestIndex].vdisplay - height); + const int nearestFpsDiff = abs(platform.connector->modes[nearestIndex].vrefresh - fps); if ((widthDiff < nearestWidthDiff) || (heightDiff < nearestHeightDiff) || (fpsDiff < nearestFpsDiff)) { nearestIndex = i; From 81641bfbbb1a949fdd7f2ffa624232f7f7a0b6df Mon Sep 17 00:00:00 2001 From: Michael Date: Tue, 10 Oct 2023 12:34:57 -0400 Subject: [PATCH 03/33] Update `PLATFORM_DRM` implementation of `GetGamepadName` --- src/rcore_drm.c | 12 +++--------- 1 file changed, 3 insertions(+), 9 deletions(-) diff --git a/src/rcore_drm.c b/src/rcore_drm.c index a7e7447a4..899f1c047 100644 --- a/src/rcore_drm.c +++ b/src/rcore_drm.c @@ -742,15 +742,7 @@ void OpenURL(const char *url) // Get gamepad internal name id const char *GetGamepadName(int gamepad) { - const char *name = NULL; - - if (CORE.Input.Gamepad.ready[gamepad]) - { - ioctl(platform.gamepadStreamFd[gamepad], JSIOCGNAME(64), &CORE.Input.Gamepad.name[gamepad]); - name = CORE.Input.Gamepad.name[gamepad]; - } - - return name; + return CORE.Input.Gamepad.name[gamepad]; } // Get gamepad axis count @@ -1954,6 +1946,8 @@ static void InitGamepad(void) if (error != 0) TRACELOG(LOG_WARNING, "RPI: Failed to create gamepad input event thread"); else TRACELOG(LOG_INFO, "RPI: Gamepad device initialized successfully"); } + + ioctl(platform.gamepadStreamFd[gamepad], JSIOCGNAME(64), &CORE.Input.Gamepad.name[i]); } } } From 9719bfc61039dde4927ef8fb663da9dd7a84eec3 Mon Sep 17 00:00:00 2001 From: Michael Date: Tue, 10 Oct 2023 12:55:09 -0400 Subject: [PATCH 04/33] Add example to test gamepad info functions Fix typo --- examples/Makefile | 1 + examples/core/core_input_gamepad_info.c | 60 +++++++++++++++++++++++++ src/rcore_drm.c | 2 +- 3 files changed, 62 insertions(+), 1 deletion(-) create mode 100644 examples/core/core_input_gamepad_info.c diff --git a/examples/Makefile b/examples/Makefile index 9404d39cc..6031f05e9 100644 --- a/examples/Makefile +++ b/examples/Makefile @@ -365,6 +365,7 @@ CORE = \ core/core_input_mouse \ core/core_input_mouse_wheel \ core/core_input_gamepad \ + core/core_input_gamepad_info \ core/core_input_multitouch \ core/core_input_gestures \ core/core_input_gestures_web \ diff --git a/examples/core/core_input_gamepad_info.c b/examples/core/core_input_gamepad_info.c new file mode 100644 index 000000000..0dcf76928 --- /dev/null +++ b/examples/core/core_input_gamepad_info.c @@ -0,0 +1,60 @@ +/******************************************************************************************* +* +* raylib [core] example - Gamepad information +* +* NOTE: This example requires a Gamepad connected to the system +* Check raylib.h for buttons configuration +* +* Example originally created with raylib 4.6, last time updated with raylib 4.6 +* +* Example licensed under an unmodified zlib/libpng license, which is an OSI-certified, +* BSD-like license that allows static linking with closed source software +* +* Copyright (c) 2013-2023 Ramon Santamaria (@raysan5) +* +********************************************************************************************/ + +#include "raylib.h" + +//------------------------------------------------------------------------------------ +// Program main entry point +//------------------------------------------------------------------------------------ +int main(void) +{ + // Initialization + //-------------------------------------------------------------------------------------- + const int screenWidth = 3440; + const int screenHeight = 1440; + + SetConfigFlags(FLAG_MSAA_4X_HINT); // Set MSAA 4X hint before windows creation + + InitWindow(screenWidth, screenHeight, "raylib [core] example - gamepad information"); + + SetTargetFPS(60); // Set our game to run at 60 frames-per-second + + // Main game loop + while (!WindowShouldClose()) // Detect window close button or ESC key + { + int y = 10; + + BeginDrawing(); + + ClearBackground(RAYWHITE); + + for (int i = 0; i < 4; i++) // by default rcore.h has a MAX_GAMEPADS of 4 so mimmic that here. + { + if (IsGamepadAvailable(i)) + { + DrawText(TextFormat("Gamepad:\n\tName: %s\n\tAxes: %d", GetGamepadName(i), GetGamepadAxisCount(i)), 10, y, 20, BLACK); + y += 40; + } + } + + EndDrawing(); + } + + // De-Initialization + //-------------------------------------------------------------------------------------- + CloseWindow(); // Close window and OpenGL context + //-------------------------------------------------------------------------------------- +} \ No newline at end of file diff --git a/src/rcore_drm.c b/src/rcore_drm.c index 899f1c047..03ed5888c 100644 --- a/src/rcore_drm.c +++ b/src/rcore_drm.c @@ -1947,7 +1947,7 @@ static void InitGamepad(void) else TRACELOG(LOG_INFO, "RPI: Gamepad device initialized successfully"); } - ioctl(platform.gamepadStreamFd[gamepad], JSIOCGNAME(64), &CORE.Input.Gamepad.name[i]); + ioctl(platform.gamepadStreamFd[i], JSIOCGNAME(64), &CORE.Input.Gamepad.name[i]); } } } From 3028324634e6ae59dc504d4809b219c8c03403e9 Mon Sep 17 00:00:00 2001 From: Michael Date: Tue, 10 Oct 2023 19:11:14 -0400 Subject: [PATCH 05/33] Update new gamepad info example --- examples/core/core_input_gamepad_info.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/examples/core/core_input_gamepad_info.c b/examples/core/core_input_gamepad_info.c index 0dcf76928..84a687cd8 100644 --- a/examples/core/core_input_gamepad_info.c +++ b/examples/core/core_input_gamepad_info.c @@ -23,8 +23,8 @@ int main(void) { // Initialization //-------------------------------------------------------------------------------------- - const int screenWidth = 3440; - const int screenHeight = 1440; + const int screenWidth = 800; + const int screenHeight = 450; SetConfigFlags(FLAG_MSAA_4X_HINT); // Set MSAA 4X hint before windows creation From e9dbf45f131aab77d8dbf59bec65d8ea796461c0 Mon Sep 17 00:00:00 2001 From: Michael Date: Tue, 10 Oct 2023 19:19:28 -0400 Subject: [PATCH 06/33] Move axis count update out of GamepadThread - race condition --- src/rcore_drm.c | 12 +++++------- 1 file changed, 5 insertions(+), 7 deletions(-) diff --git a/src/rcore_drm.c b/src/rcore_drm.c index 03ed5888c..cfef6a69f 100644 --- a/src/rcore_drm.c +++ b/src/rcore_drm.c @@ -1948,6 +1948,11 @@ static void InitGamepad(void) } ioctl(platform.gamepadStreamFd[i], JSIOCGNAME(64), &CORE.Input.Gamepad.name[i]); + + + int axisCount = 0; + if (CORE.Input.Gamepad.ready[i]) ioctl(platform.gamepadStreamFd[i], JSIOCGAXES, &axisCount); + CORE.Input.Gamepad.axisCount = axisCount; } } } @@ -1969,17 +1974,10 @@ static void *GamepadThread(void *arg) // Read gamepad event struct js_event gamepadEvent = { 0 }; - int axisCount = 0; - while (!CORE.Window.shouldClose) { for (int i = 0; i < MAX_GAMEPADS; i++) { - // Update the axis count for each gamepad. - axisCount = 0; - if (CORE.Input.Gamepad.ready[i]) ioctl(platform.gamepadStreamFd[i], JSIOCGAXES, &axisCount); - CORE.Input.Gamepad.axisCount = axisCount; - if (read(platform.gamepadStreamFd[i], &gamepadEvent, sizeof(struct js_event)) == (int)sizeof(struct js_event)) { gamepadEvent.type &= ~JS_EVENT_INIT; // Ignore synthetic events From c4bb0958ec8359a237e99ca3ddf0151069ea3101 Mon Sep 17 00:00:00 2001 From: Michael Date: Tue, 10 Oct 2023 19:26:30 -0400 Subject: [PATCH 07/33] Remove pointless if statement --- src/rcore_drm.c | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/src/rcore_drm.c b/src/rcore_drm.c index cfef6a69f..3b688b8a1 100644 --- a/src/rcore_drm.c +++ b/src/rcore_drm.c @@ -1948,11 +1948,7 @@ static void InitGamepad(void) } ioctl(platform.gamepadStreamFd[i], JSIOCGNAME(64), &CORE.Input.Gamepad.name[i]); - - - int axisCount = 0; - if (CORE.Input.Gamepad.ready[i]) ioctl(platform.gamepadStreamFd[i], JSIOCGAXES, &axisCount); - CORE.Input.Gamepad.axisCount = axisCount; + ioctl(platform.gamepadStreamFd[i], JSIOCGAXES, &CORE.Input.Gamepad.axisCount); } } } From 4bc31deac2a7e7a20768cade73efdf96a2e5bfe5 Mon Sep 17 00:00:00 2001 From: Michael Date: Thu, 12 Oct 2023 16:26:09 -0400 Subject: [PATCH 08/33] Start integrating stuff from the mikesinput lib --- src/rcore_drm.c | 177 ++++++++++++++++++++++++++++++++++++++---------- 1 file changed, 142 insertions(+), 35 deletions(-) diff --git a/src/rcore_drm.c b/src/rcore_drm.c index 3b688b8a1..2b35f9f3d 100644 --- a/src/rcore_drm.c +++ b/src/rcore_drm.c @@ -72,8 +72,14 @@ //---------------------------------------------------------------------------------- #define USE_LAST_TOUCH_DEVICE // When multiple touchscreens are connected, only use the one with the highest event number -#define DEFAULT_GAMEPAD_DEV "/dev/input/js" // Gamepad input (base dev for all gamepads: js0, js1, ...) -#define DEFAULT_EVDEV_PATH "/dev/input/" // Path to the linux input events +#define DEFAULT_EVDEV_PATH "/dev/input/by-id" // Path to the linux input events + +#define MI_BITS_PER_LONG (8 * sizeof(long)) +#define MI_NBITS(x) ((((x)-1) / MI_BITS_PER_LONG) + 1) +#define MI_OFF(x) ((x) % MI_BITS_PER_LONG) +#define MI_BIT(x) (1UL << MI_OFF(x)) +#define MI_LONG(x) ((x) / MI_BITS_PER_LONG) +#define MI_IS_BIT_SET(array, bit) ((array[MI_LONG(bit)] >> MI_OFF(bit)) & 1) //---------------------------------------------------------------------------------- // Types and Structures Definition @@ -148,12 +154,15 @@ static void RestoreKeyboard(void); // Restore keyboard syst static void ProcessKeyboard(void); // Process keyboard events #endif +static void InitDrmInput(void); // Initialize inputs for DRM platform +static void InitDrmJoystick(int index, char *path) // Initialize a joystick for DRM platform + static void InitEvdevInput(void); // Initialize evdev inputs static void ConfigureEvdevDevice(char *device); // Identifies a input device and configures it for use if appropriate static void PollKeyboardEvents(void); // Process evdev keyboard events static void *EventThread(void *arg); // Input device events reading thread -static void InitGamepad(void); // Initialize raw gamepad input +//static void InitGamepad(void); // Initialize raw gamepad input static void *GamepadThread(void *arg); // Mouse reading thread static int FindMatchingConnectorMode(const drmModeConnector *connector, const drmModeModeInfo *mode); // Search matching DRM mode in connector's mode list @@ -215,6 +224,11 @@ void InitWindow(int width, int height, const char *title) CORE.Input.Gamepad.lastButtonPressed = 0; // GAMEPAD_BUTTON_UNKNOWN CORE.Window.eventWaiting = false; + for (int i = 0; i < MAX_GAMEPADS; i++) + { + CORE.Input.Gamepad.ready[i] = false; + } + // Initialize graphics device (display device and OpenGL context) // NOTE: returns true if window and graphic device has been initialized successfully CORE.Window.ready = InitGraphicsDevice(width, height); @@ -277,8 +291,9 @@ void InitWindow(int width, int height, const char *title) // Platform specific init window //-------------------------------------------------------------- // Initialize raw input system + InitDrmInput(); // DRM platform input initialization InitEvdevInput(); // Evdev inputs initialization - InitGamepad(); // Gamepad init + //InitGamepad(); // Gamepad init InitKeyboard(); // Keyboard init (stdin) //-------------------------------------------------------------- @@ -1424,6 +1439,98 @@ static void ProcessKeyboard(void) } #endif // SUPPORT_SSH_KEYBOARD_RPI +// Initialize user input from /dev/input/by-id +// This includes keyobard, mouse, gamepads, and touch screens. +static void InitDrmInput(void) +{ + char path[MAX_FILEPATH_LENGTH] = { 0 }; + DIR *directory = NULL; + struct dirent *entity = NULL; + + // Initialise keyboard file descriptor + platform.keyboardFd = -1; + + // Reset variables + for (int i = 0; i < MAX_TOUCH_POINTS; ++i) + { + CORE.Input.Touch.position[i].x = -1; + CORE.Input.Touch.position[i].y = -1; + } + + // Reset keyboard key state + for (int i = 0; i < MAX_KEYBOARD_KEYS; i++) + { + CORE.Input.Keyboard.currentKeyState[i] = 0; + CORE.Input.Keyboard.keyRepeatInFrame[i] = 0; + } + + // Open the linux directory of "/dev/input/by-id" + directory = opendir(DEFAULT_EVDEV_PATH); + + if (directory) + { + while ((entity = readdir(directory)) != NULL) + { + sprintf(path, "%s%s", DEFAULT_EVDEV_PATH, entity->d_name); + + // Devices are in the format: + // /dev/input/by-id/usb-Name_of_Device-[event-joystick|event-kbd|event-mouse] + int len = strlen("event-joystick"); + if (strncmp("event-joystick", entity->d_name + (strlen(entity->d_name)-len), len) == 0) + { + TraceLog(LOG_INFO, TextFormat("Device %s is an event joystick", entity->d_name)); + for (int i = 0; i < MAX_GAMEPADS; i++) + { + if (CORE.Input.Gamepad.ready) + continue; + + InitDrmJoystick(i, path); + break; + } + + } + + len = strlen("event-kbd"); + if (strncmp("event-kbd", entity->d_name + (strlen(entity->d_name)-len), len) == 0) + { + TraceLog(LOG_INFO, TextFormat("Device %s is an event keyboard", entity->d_name)); + } + + len = strlen("event-mouse"); + if (strncmp("event-mouse", entity->d_name + (strlen(entity->d_name)-len), len) == 0) + { + TraceLog(LOG_INFO, TextFormat("Device %s is an event mouse", entity->d_name)); + } + } + + closedir(directory); + } +} + +void InitDrmJoystick(int index, const char *path) +{ + if ((platform.gamepadStreamFd[index] = open(path, O_RDONLY | O_NONBLOCK)) < 0) + { + // This isn't an active device that can be read so return without doing anything else. + return; + } + + // Get the bits describing the absolute axes of the device. + unsigned long abs_bits[ABS_MAX / 8 + 1] = {0}; + ioctl(platform.gamepadStreamFd[index], EVIOCGBIT(EV_ABS, sizeof(abs_bits)), &abs_bits); + + // Count the axes present on the device. + CORE.Input.Gamepad.axisCount = 0; + for (int axis = 0; axis < ABS_MAX; axis++) + { + if (MI_IS_BIT_SET(abs_bits, axis)) { + CORE.Input.Gamepad.axisCount++; + } + } + + CORE.Input.Gamepad.ready[index] = true; +} + // Initialise user input from evdev(/dev/input/event) // this means mouse, keyboard or gamepad devices static void InitEvdevInput(void) @@ -1921,37 +2028,37 @@ static void *EventThread(void *arg) } // Initialize gamepad system -static void InitGamepad(void) -{ - char gamepadDev[128] = { 0 }; - - for (int i = 0; i < MAX_GAMEPADS; i++) - { - sprintf(gamepadDev, "%s%i", DEFAULT_GAMEPAD_DEV, i); - - if ((platform.gamepadStreamFd[i] = open(gamepadDev, O_RDONLY | O_NONBLOCK)) < 0) - { - // NOTE: Only show message for first gamepad - if (i == 0) TRACELOG(LOG_WARNING, "RPI: Failed to open Gamepad device, no gamepad available"); - } - else - { - CORE.Input.Gamepad.ready[i] = true; - - // NOTE: Only create one thread - if (i == 0) - { - int error = pthread_create(&platform.gamepadThreadId, NULL, &GamepadThread, NULL); - - if (error != 0) TRACELOG(LOG_WARNING, "RPI: Failed to create gamepad input event thread"); - else TRACELOG(LOG_INFO, "RPI: Gamepad device initialized successfully"); - } - - ioctl(platform.gamepadStreamFd[i], JSIOCGNAME(64), &CORE.Input.Gamepad.name[i]); - ioctl(platform.gamepadStreamFd[i], JSIOCGAXES, &CORE.Input.Gamepad.axisCount); - } - } -} +// static void InitGamepad(void) +// { +// char gamepadDev[128] = { 0 }; +// +// for (int i = 0; i < MAX_GAMEPADS; i++) +// { +// sprintf(gamepadDev, "%s%i", DEFAULT_GAMEPAD_DEV, i); +// +// if ((platform.gamepadStreamFd[i] = open(gamepadDev, O_RDONLY | O_NONBLOCK)) < 0) +// { +// // NOTE: Only show message for first gamepad +// if (i == 0) TRACELOG(LOG_WARNING, "RPI: Failed to open Gamepad device, no gamepad available"); +// } +// else +// { +// CORE.Input.Gamepad.ready[i] = true; +// +// // NOTE: Only create one thread +// if (i == 0) +// { +// int error = pthread_create(&platform.gamepadThreadId, NULL, &GamepadThread, NULL); +// +// if (error != 0) TRACELOG(LOG_WARNING, "RPI: Failed to create gamepad input event thread"); +// else TRACELOG(LOG_INFO, "RPI: Gamepad device initialized successfully"); +// } +// +// ioctl(platform.gamepadStreamFd[i], JSIOCGNAME(64), &CORE.Input.Gamepad.name[i]); +// ioctl(platform.gamepadStreamFd[i], JSIOCGAXES, &CORE.Input.Gamepad.axisCount); +// } +// } +// } // Process Gamepad (/dev/input/js0) static void *GamepadThread(void *arg) From ebd46076ab144ee54a4d03a9ef1ccdb7392764aa Mon Sep 17 00:00:00 2001 From: Michael Date: Thu, 12 Oct 2023 16:42:49 -0400 Subject: [PATCH 09/33] Add more logging --- src/rcore_drm.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/rcore_drm.c b/src/rcore_drm.c index 2b35f9f3d..f1d1b70a9 100644 --- a/src/rcore_drm.c +++ b/src/rcore_drm.c @@ -1443,6 +1443,8 @@ static void ProcessKeyboard(void) // This includes keyobard, mouse, gamepads, and touch screens. static void InitDrmInput(void) { + TraceLog(LOG_INFO, "RUNNING InitDrmInput"); + char path[MAX_FILEPATH_LENGTH] = { 0 }; DIR *directory = NULL; struct dirent *entity = NULL; @@ -1487,7 +1489,6 @@ static void InitDrmInput(void) InitDrmJoystick(i, path); break; } - } len = strlen("event-kbd"); From eac530681866642d9f5ae258b18c2fe4a10202f9 Mon Sep 17 00:00:00 2001 From: Michael Date: Thu, 12 Oct 2023 16:45:21 -0400 Subject: [PATCH 10/33] Add semicolon --- src/rcore_drm.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/rcore_drm.c b/src/rcore_drm.c index f1d1b70a9..5546a51cb 100644 --- a/src/rcore_drm.c +++ b/src/rcore_drm.c @@ -155,7 +155,7 @@ static void ProcessKeyboard(void); // Process keyboard even #endif static void InitDrmInput(void); // Initialize inputs for DRM platform -static void InitDrmJoystick(int index, char *path) // Initialize a joystick for DRM platform +static void InitDrmJoystick(int index, char *path); // Initialize a joystick for DRM platform static void InitEvdevInput(void); // Initialize evdev inputs static void ConfigureEvdevDevice(char *device); // Identifies a input device and configures it for use if appropriate @@ -1444,7 +1444,7 @@ static void ProcessKeyboard(void) static void InitDrmInput(void) { TraceLog(LOG_INFO, "RUNNING InitDrmInput"); - + char path[MAX_FILEPATH_LENGTH] = { 0 }; DIR *directory = NULL; struct dirent *entity = NULL; From dc115592e94606139badff184c10700944994fa5 Mon Sep 17 00:00:00 2001 From: Michael Date: Thu, 12 Oct 2023 16:46:19 -0400 Subject: [PATCH 11/33] Add forgotten static --- src/rcore_drm.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/rcore_drm.c b/src/rcore_drm.c index 5546a51cb..fb1c5a238 100644 --- a/src/rcore_drm.c +++ b/src/rcore_drm.c @@ -1508,7 +1508,7 @@ static void InitDrmInput(void) } } -void InitDrmJoystick(int index, const char *path) +static void InitDrmJoystick(int index, const char *path) { if ((platform.gamepadStreamFd[index] = open(path, O_RDONLY | O_NONBLOCK)) < 0) { From 2503ff9f95f0600f4bb053b571659bbd2cfe62d5 Mon Sep 17 00:00:00 2001 From: Michael Date: Thu, 12 Oct 2023 16:48:16 -0400 Subject: [PATCH 12/33] More fixes --- src/rcore_drm.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/rcore_drm.c b/src/rcore_drm.c index fb1c5a238..897a90a89 100644 --- a/src/rcore_drm.c +++ b/src/rcore_drm.c @@ -155,7 +155,7 @@ static void ProcessKeyboard(void); // Process keyboard even #endif static void InitDrmInput(void); // Initialize inputs for DRM platform -static void InitDrmJoystick(int index, char *path); // Initialize a joystick for DRM platform +static void InitDrmJoystick(int index, const char *path); // Initialize a joystick for DRM platform static void InitEvdevInput(void); // Initialize evdev inputs static void ConfigureEvdevDevice(char *device); // Identifies a input device and configures it for use if appropriate From 8489d8107584356697f9ccf7c1ee417552e6047f Mon Sep 17 00:00:00 2001 From: Michael Date: Thu, 12 Oct 2023 17:04:40 -0400 Subject: [PATCH 13/33] Update axisCount to be array --- src/rcore.h | 2 +- src/rcore_drm.c | 15 +++++++++++---- 2 files changed, 12 insertions(+), 5 deletions(-) diff --git a/src/rcore.h b/src/rcore.h index 4d40c9567..b38d665ac 100644 --- a/src/rcore.h +++ b/src/rcore.h @@ -181,7 +181,7 @@ typedef struct CoreData { } Touch; struct { int lastButtonPressed; // Register last gamepad button pressed - int axisCount; // Register number of available gamepad axis + int axisCount[MAX_GAMEPADS]; // Register number of available gamepad axis bool ready[MAX_GAMEPADS]; // Flag to know if gamepad is ready char name[MAX_GAMEPADS][64]; // Gamepad name holder char currentButtonState[MAX_GAMEPADS][MAX_GAMEPAD_BUTTONS]; // Current gamepad buttons state diff --git a/src/rcore_drm.c b/src/rcore_drm.c index 897a90a89..4718c9ce4 100644 --- a/src/rcore_drm.c +++ b/src/rcore_drm.c @@ -763,7 +763,7 @@ const char *GetGamepadName(int gamepad) // Get gamepad axis count int GetGamepadAxisCount(int gamepad) { - return CORE.Input.Gamepad.axisCount; + return CORE.Input.Gamepad.axisCount[gamepad]; } // Set internal gamepad mappings @@ -861,7 +861,11 @@ void PollInputEvents(void) // Reset last gamepad button/axis registered state CORE.Input.Gamepad.lastButtonPressed = 0; // GAMEPAD_BUTTON_UNKNOWN - CORE.Input.Gamepad.axisCount = 0; + + for (int i = 0; i < MAX_GAMEPADS; i++) + { + CORE.Input.Gamepad.axisCount[i] = 0; + } // Register previous keys states for (int i = 0; i < MAX_KEYBOARD_KEYS; i++) @@ -1519,16 +1523,19 @@ static void InitDrmJoystick(int index, const char *path) // Get the bits describing the absolute axes of the device. unsigned long abs_bits[ABS_MAX / 8 + 1] = {0}; ioctl(platform.gamepadStreamFd[index], EVIOCGBIT(EV_ABS, sizeof(abs_bits)), &abs_bits); + ioctl(platform.gamepadStreamFd[index], EVIOCGNAME(64), &CORE.Input.Gamepad.name[index]); // Count the axes present on the device. - CORE.Input.Gamepad.axisCount = 0; + CORE.Input.Gamepad.axisCount[index] = 0; for (int axis = 0; axis < ABS_MAX; axis++) { if (MI_IS_BIT_SET(abs_bits, axis)) { - CORE.Input.Gamepad.axisCount++; + CORE.Input.Gamepad.axisCount[index]++; } } + TraceLog(LOG_INFO, TextFormat("Gamepad [%d] %s has %d axes", index, CORE.Input.Gamepad.name[index], CORE.Input.Gamepad.axisCount[index])); + CORE.Input.Gamepad.ready[index] = true; } From 684dcb6947fc76a4d4d499d9230da34908c7d886 Mon Sep 17 00:00:00 2001 From: Michael Date: Thu, 12 Oct 2023 17:18:10 -0400 Subject: [PATCH 14/33] More debugging --- src/rcore_drm.c | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/src/rcore_drm.c b/src/rcore_drm.c index 4718c9ce4..49ed39a5b 100644 --- a/src/rcore_drm.c +++ b/src/rcore_drm.c @@ -1514,11 +1514,10 @@ static void InitDrmInput(void) static void InitDrmJoystick(int index, const char *path) { - if ((platform.gamepadStreamFd[index] = open(path, O_RDONLY | O_NONBLOCK)) < 0) - { - // This isn't an active device that can be read so return without doing anything else. - return; - } + TraceLog(LOG_INFO, "InitDrmJoystick"); + + int result = (platform.gamepadStreamFd[index] = open(path, O_RDONLY | O_NONBLOCK)); + printf("Result of file open: %d\n", result); // Get the bits describing the absolute axes of the device. unsigned long abs_bits[ABS_MAX / 8 + 1] = {0}; From 537b012dc6a76cc563af2f2f86aac92c6bf81ed1 Mon Sep 17 00:00:00 2001 From: Michael Date: Thu, 12 Oct 2023 17:21:45 -0400 Subject: [PATCH 15/33] Add forgotten index to ready check --- src/rcore_drm.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/rcore_drm.c b/src/rcore_drm.c index 49ed39a5b..477574f44 100644 --- a/src/rcore_drm.c +++ b/src/rcore_drm.c @@ -1487,7 +1487,7 @@ static void InitDrmInput(void) TraceLog(LOG_INFO, TextFormat("Device %s is an event joystick", entity->d_name)); for (int i = 0; i < MAX_GAMEPADS; i++) { - if (CORE.Input.Gamepad.ready) + if (CORE.Input.Gamepad.ready[i]) continue; InitDrmJoystick(i, path); @@ -1515,7 +1515,7 @@ static void InitDrmInput(void) static void InitDrmJoystick(int index, const char *path) { TraceLog(LOG_INFO, "InitDrmJoystick"); - + int result = (platform.gamepadStreamFd[index] = open(path, O_RDONLY | O_NONBLOCK)); printf("Result of file open: %d\n", result); From 00592ffe95f8837211abb1c0de915d1401a04ad4 Mon Sep 17 00:00:00 2001 From: Michael Date: Thu, 12 Oct 2023 17:22:54 -0400 Subject: [PATCH 16/33] Add path logging --- src/rcore_drm.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/rcore_drm.c b/src/rcore_drm.c index 477574f44..c0cd9c7db 100644 --- a/src/rcore_drm.c +++ b/src/rcore_drm.c @@ -1514,7 +1514,7 @@ static void InitDrmInput(void) static void InitDrmJoystick(int index, const char *path) { - TraceLog(LOG_INFO, "InitDrmJoystick"); + TraceLog(LOG_INFO, TextFormat("InitDrmJoystick - %s", path); int result = (platform.gamepadStreamFd[index] = open(path, O_RDONLY | O_NONBLOCK)); printf("Result of file open: %d\n", result); From 7bbe5e55e883af33845324e1803f518a41ba292f Mon Sep 17 00:00:00 2001 From: Michael Date: Thu, 12 Oct 2023 17:25:57 -0400 Subject: [PATCH 17/33] Missing parenthesis --- src/rcore_drm.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/rcore_drm.c b/src/rcore_drm.c index c0cd9c7db..5de234cf1 100644 --- a/src/rcore_drm.c +++ b/src/rcore_drm.c @@ -1514,7 +1514,7 @@ static void InitDrmInput(void) static void InitDrmJoystick(int index, const char *path) { - TraceLog(LOG_INFO, TextFormat("InitDrmJoystick - %s", path); + TraceLog(LOG_INFO, TextFormat("InitDrmJoystick - %s", path)); int result = (platform.gamepadStreamFd[index] = open(path, O_RDONLY | O_NONBLOCK)); printf("Result of file open: %d\n", result); From b76d20d7d29eb30a584ed3e7277939f0a980b512 Mon Sep 17 00:00:00 2001 From: Michael Date: Thu, 12 Oct 2023 17:28:28 -0400 Subject: [PATCH 18/33] Add missing slash --- src/rcore_drm.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/rcore_drm.c b/src/rcore_drm.c index 5de234cf1..bd2201c32 100644 --- a/src/rcore_drm.c +++ b/src/rcore_drm.c @@ -1477,7 +1477,7 @@ static void InitDrmInput(void) { while ((entity = readdir(directory)) != NULL) { - sprintf(path, "%s%s", DEFAULT_EVDEV_PATH, entity->d_name); + sprintf(path, "%s/%s", DEFAULT_EVDEV_PATH, entity->d_name); // Devices are in the format: // /dev/input/by-id/usb-Name_of_Device-[event-joystick|event-kbd|event-mouse] From f872f239e42c24af9fcd944edb2851cba9b1cf78 Mon Sep 17 00:00:00 2001 From: Michael Date: Thu, 12 Oct 2023 17:38:21 -0400 Subject: [PATCH 19/33] Fix axis count being reset to 0 --- src/rcore_drm.c | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/src/rcore_drm.c b/src/rcore_drm.c index bd2201c32..e214420e5 100644 --- a/src/rcore_drm.c +++ b/src/rcore_drm.c @@ -862,11 +862,6 @@ void PollInputEvents(void) // Reset last gamepad button/axis registered state CORE.Input.Gamepad.lastButtonPressed = 0; // GAMEPAD_BUTTON_UNKNOWN - for (int i = 0; i < MAX_GAMEPADS; i++) - { - CORE.Input.Gamepad.axisCount[i] = 0; - } - // Register previous keys states for (int i = 0; i < MAX_KEYBOARD_KEYS; i++) { @@ -1529,6 +1524,7 @@ static void InitDrmJoystick(int index, const char *path) for (int axis = 0; axis < ABS_MAX; axis++) { if (MI_IS_BIT_SET(abs_bits, axis)) { + TraceLog(LOG_INFO, TextFormat("Gamepad %d has axis %d", index, axis); CORE.Input.Gamepad.axisCount[index]++; } } From 99ee13bbdff6476ec3bd87ef146725b34248fa31 Mon Sep 17 00:00:00 2001 From: Michael Date: Thu, 12 Oct 2023 17:39:58 -0400 Subject: [PATCH 20/33] Fix missing paren --- src/rcore_drm.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/rcore_drm.c b/src/rcore_drm.c index e214420e5..d2f4fe366 100644 --- a/src/rcore_drm.c +++ b/src/rcore_drm.c @@ -1524,7 +1524,7 @@ static void InitDrmJoystick(int index, const char *path) for (int axis = 0; axis < ABS_MAX; axis++) { if (MI_IS_BIT_SET(abs_bits, axis)) { - TraceLog(LOG_INFO, TextFormat("Gamepad %d has axis %d", index, axis); + TraceLog(LOG_INFO, TextFormat("Gamepad %d has axis %d", index, axis)); CORE.Input.Gamepad.axisCount[index]++; } } From 57fafad066f5134804bc064a1d74c89376c4e81d Mon Sep 17 00:00:00 2001 From: Michael Date: Thu, 12 Oct 2023 19:14:19 -0400 Subject: [PATCH 21/33] Test polling joystick button events --- src/rcore_drm.c | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/src/rcore_drm.c b/src/rcore_drm.c index d2f4fe366..616e81867 100644 --- a/src/rcore_drm.c +++ b/src/rcore_drm.c @@ -156,6 +156,7 @@ static void ProcessKeyboard(void); // Process keyboard even static void InitDrmInput(void); // Initialize inputs for DRM platform static void InitDrmJoystick(int index, const char *path); // Initialize a joystick for DRM platform +static void PollDrmJoystickEvents(); static void InitEvdevInput(void); // Initialize evdev inputs static void ConfigureEvdevDevice(char *device); // Identifies a input device and configures it for use if appropriate @@ -869,6 +870,7 @@ void PollInputEvents(void) CORE.Input.Keyboard.keyRepeatInFrame[i] = 0; } + PollDrmJoystickEvents(); PollKeyboardEvents(); // Register previous mouse states @@ -1534,6 +1536,27 @@ static void InitDrmJoystick(int index, const char *path) CORE.Input.Gamepad.ready[index] = true; } +static void PollDrmJoystickEvents() +{ + struct input_event ev; + + for (int i = 0; i < MAX_GAMEPADS; i++) + { + if (!CORE.Input.Gamepad.ready[i]) + continue; + + while (read(platform.gamepadStreamFd, &ev, sizeof(ev)) > 0) + { + switch(ev.type) + { + case EV_KEY: + printf("Key %d = %d", ev.code, ev.value); + break; + } + } + } +} + // Initialise user input from evdev(/dev/input/event) // this means mouse, keyboard or gamepad devices static void InitEvdevInput(void) From 2569d101da98f1f038f70e588110f802c9e56b22 Mon Sep 17 00:00:00 2001 From: Michael Date: Fri, 13 Oct 2023 11:56:54 -0400 Subject: [PATCH 22/33] Major updates --- examples/core/core_input_gamepad_info.c | 54 ++++++++++------- src/rcore_desktop.c | 4 +- src/rcore_drm.c | 78 +++++++++++++++++++++---- 3 files changed, 101 insertions(+), 35 deletions(-) diff --git a/examples/core/core_input_gamepad_info.c b/examples/core/core_input_gamepad_info.c index 84a687cd8..8a33bd66b 100644 --- a/examples/core/core_input_gamepad_info.c +++ b/examples/core/core_input_gamepad_info.c @@ -1,18 +1,18 @@ /******************************************************************************************* -* -* raylib [core] example - Gamepad information -* -* NOTE: This example requires a Gamepad connected to the system -* Check raylib.h for buttons configuration -* -* Example originally created with raylib 4.6, last time updated with raylib 4.6 -* -* Example licensed under an unmodified zlib/libpng license, which is an OSI-certified, -* BSD-like license that allows static linking with closed source software -* -* Copyright (c) 2013-2023 Ramon Santamaria (@raysan5) -* -********************************************************************************************/ + * + * raylib [core] example - Gamepad information + * + * NOTE: This example requires a Gamepad connected to the system + * Check raylib.h for buttons configuration + * + * Example originally created with raylib 4.6, last time updated with raylib 4.6 + * + * Example licensed under an unmodified zlib/libpng license, which is an OSI-certified, + * BSD-like license that allows static linking with closed source software + * + * Copyright (c) 2013-2023 Ramon Santamaria (@raysan5) + * + ********************************************************************************************/ #include "raylib.h" @@ -26,14 +26,14 @@ int main(void) const int screenWidth = 800; const int screenHeight = 450; - SetConfigFlags(FLAG_MSAA_4X_HINT); // Set MSAA 4X hint before windows creation + SetConfigFlags(FLAG_MSAA_4X_HINT); // Set MSAA 4X hint before windows creation InitWindow(screenWidth, screenHeight, "raylib [core] example - gamepad information"); - SetTargetFPS(60); // Set our game to run at 60 frames-per-second + SetTargetFPS(60); // Set our game to run at 60 frames-per-second // Main game loop - while (!WindowShouldClose()) // Detect window close button or ESC key + while (!WindowShouldClose()) // Detect window close button or ESC key { int y = 10; @@ -41,12 +41,24 @@ int main(void) ClearBackground(RAYWHITE); - for (int i = 0; i < 4; i++) // by default rcore.h has a MAX_GAMEPADS of 4 so mimmic that here. + for (int i = 0; i < 4; i++) // by default rcore.h has a MAX_GAMEPADS of 4 so mimmic that here. { if (IsGamepadAvailable(i)) { - DrawText(TextFormat("Gamepad:\n\tName: %s\n\tAxes: %d", GetGamepadName(i), GetGamepadAxisCount(i)), 10, y, 20, BLACK); - y += 40; + DrawText(TextFormat("Gamepad name: %s", GetGamepadName(i)), 10, y, 20, BLACK); + y += 30; + DrawText(TextFormat("\tAxis count: %d", GetGamepadAxisCount(i)), 10, y, 20, BLACK); + y += 30; + for (int axis = 0; axis < GetGamepadAxisCount(i); axis++) + { + DrawText(TextFormat("\tAxis %d = %f", axis, GetGamepadAxisMovement(i, axis)), 10, y, 20, BLACK); + y += 30; + } + for (int button = 0; button < 32; button++) + { + DrawText(TextFormat("\tButton %d = %d", button, IsGamepadButtonPressed(i, button)), 10, y, 20, BLACK); + y += 30; + } } } @@ -55,6 +67,6 @@ int main(void) // De-Initialization //-------------------------------------------------------------------------------------- - CloseWindow(); // Close window and OpenGL context + CloseWindow(); // Close window and OpenGL context //-------------------------------------------------------------------------------------- } \ No newline at end of file diff --git a/src/rcore_desktop.c b/src/rcore_desktop.c index c410b713b..3cc0ea34c 100644 --- a/src/rcore_desktop.c +++ b/src/rcore_desktop.c @@ -1339,7 +1339,7 @@ void PollInputEvents(void) // Reset last gamepad button/axis registered state CORE.Input.Gamepad.lastButtonPressed = 0; // GAMEPAD_BUTTON_UNKNOWN - CORE.Input.Gamepad.axisCount = 0; + //CORE.Input.Gamepad.axisCount = 0; // Keyboard/Mouse input polling (automatically managed by GLFW3 through callback) // Register previous keys states @@ -1439,7 +1439,7 @@ void PollInputEvents(void) CORE.Input.Gamepad.currentButtonState[i][GAMEPAD_BUTTON_LEFT_TRIGGER_2] = (char)(CORE.Input.Gamepad.axisState[i][GAMEPAD_AXIS_LEFT_TRIGGER] > 0.1f); CORE.Input.Gamepad.currentButtonState[i][GAMEPAD_BUTTON_RIGHT_TRIGGER_2] = (char)(CORE.Input.Gamepad.axisState[i][GAMEPAD_AXIS_RIGHT_TRIGGER] > 0.1f); - CORE.Input.Gamepad.axisCount = GLFW_GAMEPAD_AXIS_LAST + 1; + CORE.Input.Gamepad.axisCount[i] = GLFW_GAMEPAD_AXIS_LAST + 1; } } diff --git a/src/rcore_drm.c b/src/rcore_drm.c index 616e81867..3498c67a5 100644 --- a/src/rcore_drm.c +++ b/src/rcore_drm.c @@ -85,6 +85,11 @@ // Types and Structures Definition //---------------------------------------------------------------------------------- +typedef struct { + int min; + int max; +} GamepadAxisRange; + typedef struct { pthread_t threadId; // Event reading thread id @@ -131,9 +136,13 @@ typedef struct { char currentButtonStateEvdev[MAX_MOUSE_BUTTONS]; // Holds the new mouse state for the next polling event to grab // Gamepad data - pthread_t gamepadThreadId; // Gamepad reading thread id - int gamepadStreamFd[MAX_GAMEPADS]; // Gamepad device file descriptor - + pthread_t gamepadThreadId; // Gamepad reading thread id + int gamepadStreamFd[MAX_GAMEPADS]; // Gamepad device file descriptor + struct input_absinfo gamepadAxisFeatures[MAX_GAMEPADS][ABS_MAX]; // Store the features of each axis for each gamepad. + int gamepadActiveAxes[MAX_GAMEPADS][MAX_GAMEPAD_AXIS]; // Map axis ID to actual axis, e.g. the first axis found will be axis 0 as far as raylib is concerned but might actually be ABS_HAT0X (16) for some gamepads. + int gamepadButtonCount[MAX_GAMEPADS]; // Store the number of active buttons found, up to MAX_GAMEPAD_BUTTONS + int gamepadActiveButtons[MAX_GAMEPADS][MAX_GAMEPAD_BUTTONS]; // Map button ID to actual key. e.g. the first key on a joystick might be KEY_A or KEY_X. + } PlatformData; //---------------------------------------------------------------------------------- @@ -1479,7 +1488,7 @@ static void InitDrmInput(void) // Devices are in the format: // /dev/input/by-id/usb-Name_of_Device-[event-joystick|event-kbd|event-mouse] int len = strlen("event-joystick"); - if (strncmp("event-joystick", entity->d_name + (strlen(entity->d_name)-len), len) == 0) + if (strncmp("event-joystick", entity->d_name + (strlen(entity->d_name)-len), len) == 0) // If the device id ends with "event-joystick" { TraceLog(LOG_INFO, TextFormat("Device %s is an event joystick", entity->d_name)); for (int i = 0; i < MAX_GAMEPADS; i++) @@ -1493,13 +1502,13 @@ static void InitDrmInput(void) } len = strlen("event-kbd"); - if (strncmp("event-kbd", entity->d_name + (strlen(entity->d_name)-len), len) == 0) + if (strncmp("event-kbd", entity->d_name + (strlen(entity->d_name)-len), len) == 0) // If the device id ends with "event-kbd" { TraceLog(LOG_INFO, TextFormat("Device %s is an event keyboard", entity->d_name)); } len = strlen("event-mouse"); - if (strncmp("event-mouse", entity->d_name + (strlen(entity->d_name)-len), len) == 0) + if (strncmp("event-mouse", entity->d_name + (strlen(entity->d_name)-len), len) == 0) // If the device id ends with "event-mouse" { TraceLog(LOG_INFO, TextFormat("Device %s is an event mouse", entity->d_name)); } @@ -1516,18 +1525,36 @@ static void InitDrmJoystick(int index, const char *path) int result = (platform.gamepadStreamFd[index] = open(path, O_RDONLY | O_NONBLOCK)); printf("Result of file open: %d\n", result); + // Get the name of the device. + ioctl(platform.gamepadStreamFd[index], EVIOCGNAME(64), &CORE.Input.Gamepad.name[index]); + + // Get the bits describing the buttons of the device. + unsigned long key_bits[KEY_MAX / 8 + 1] = {0}; + ioctl(platform.gamepadStreamFd[index], EVIOCGBIT(EV_KEY, sizeof(key_bits)), &key_bits); + + // Count the buttons present and map a game button id (0-32) to the key code of the physical button. + for (int key = 0; key < KEY_MAX; key++) + { + if (MI_IS_BIT_SET(key_bits, key) && platform.gamepadButtonCount[index] < MAX_GAMEPAD_BUTTONS) + { + platform.gamepadActiveButtons[index][platform.gamepadButtonCount[index]++] = key; + } + } + // Get the bits describing the absolute axes of the device. unsigned long abs_bits[ABS_MAX / 8 + 1] = {0}; ioctl(platform.gamepadStreamFd[index], EVIOCGBIT(EV_ABS, sizeof(abs_bits)), &abs_bits); - ioctl(platform.gamepadStreamFd[index], EVIOCGNAME(64), &CORE.Input.Gamepad.name[index]); - - // Count the axes present on the device. + + // Count the axes present on the device and read their features. CORE.Input.Gamepad.axisCount[index] = 0; for (int axis = 0; axis < ABS_MAX; axis++) { - if (MI_IS_BIT_SET(abs_bits, axis)) { + // axis may be any number between 0x00 and 0x3f, and it is common for the first axis to be 0x10 (ABS_HAT0X). This maps the active axes to a range of IDs between 0 and MAX_GAMEPAD_AXIS + if (MI_IS_BIT_SET(abs_bits, axis) && CORE.Input.Gamepad.axisCount < MAX_GAMEPAD_AXIS) + { + platform.gamepadActiveAxes[index][CORE.Input.Gamepad.axisCount[index]++] = axis; TraceLog(LOG_INFO, TextFormat("Gamepad %d has axis %d", index, axis)); - CORE.Input.Gamepad.axisCount[index]++; + ioctl(platform.gamepadStreamFd[index], EVIOCGABS(axis), &platform.gamepadAxisFeatures[index][axis]); } } @@ -1550,7 +1577,32 @@ static void PollDrmJoystickEvents() switch(ev.type) { case EV_KEY: - printf("Key %d = %d", ev.code, ev.value); + if (ev.code < MAX_GAMEPAD_BUTTONS) + { + CORE.Input.Gamepad.currentButtonState[i][ev.code] = ev.value; + for (int lookupButton = 0; lookupButton < MAX_GAMEPAD_BUTTONS; lookupButton++) + { + if (platform.gamepadActiveButtons[i][lookupButton] == ev.code) + { + CORE.Input.Gamepad.currentButtonState[i][lookupButton] = ev.value; + break; + } + } + } + break; + case EV_ABS: + if (ev.code < MAX_GAMEPAD_AXIS) + { + struct input_absinfo f = platform.gamepadAxisFeatures[i][ev.code]; + for (int lookupAxis = 0; lookupAxis < MAX_GAMEPAD_AXIS; lookupAxis++) + { + if (platform.gamepadActiveAxes[i][lookupAxis] == ev.code) + { + CORE.Input.Gamepad.axisState[i][lookupAxis] = ((float)ev.value - ((f.maximum - f.minimum) / 2.0f)) / (float)(f.maximum - f.minimum); + break; + } + } + } break; } } @@ -2086,6 +2138,7 @@ static void *EventThread(void *arg) // } // } +/* // Process Gamepad (/dev/input/js0) static void *GamepadThread(void *arg) { @@ -2142,6 +2195,7 @@ static void *GamepadThread(void *arg) return NULL; } +*/ // Search matching DRM mode in connector's mode list static int FindMatchingConnectorMode(const drmModeConnector *connector, const drmModeModeInfo *mode) From 9809ae4a75d47ad71cd887407b34fb08cb343995 Mon Sep 17 00:00:00 2001 From: Michael Date: Fri, 13 Oct 2023 11:58:25 -0400 Subject: [PATCH 23/33] Fix missing array index --- src/rcore_drm.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/rcore_drm.c b/src/rcore_drm.c index 3498c67a5..5ff736d81 100644 --- a/src/rcore_drm.c +++ b/src/rcore_drm.c @@ -1550,7 +1550,7 @@ static void InitDrmJoystick(int index, const char *path) for (int axis = 0; axis < ABS_MAX; axis++) { // axis may be any number between 0x00 and 0x3f, and it is common for the first axis to be 0x10 (ABS_HAT0X). This maps the active axes to a range of IDs between 0 and MAX_GAMEPAD_AXIS - if (MI_IS_BIT_SET(abs_bits, axis) && CORE.Input.Gamepad.axisCount < MAX_GAMEPAD_AXIS) + if (MI_IS_BIT_SET(abs_bits, axis) && CORE.Input.Gamepad.axisCount[index] < MAX_GAMEPAD_AXIS) { platform.gamepadActiveAxes[index][CORE.Input.Gamepad.axisCount[index]++] = axis; TraceLog(LOG_INFO, TextFormat("Gamepad %d has axis %d", index, axis)); From dacbfc8810e22ff8210409db3abcc1cddc9d154c Mon Sep 17 00:00:00 2001 From: Michael Date: Fri, 13 Oct 2023 12:00:55 -0400 Subject: [PATCH 24/33] Fix another missing array index --- src/rcore_drm.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/rcore_drm.c b/src/rcore_drm.c index 5ff736d81..6bfeada62 100644 --- a/src/rcore_drm.c +++ b/src/rcore_drm.c @@ -1572,7 +1572,7 @@ static void PollDrmJoystickEvents() if (!CORE.Input.Gamepad.ready[i]) continue; - while (read(platform.gamepadStreamFd, &ev, sizeof(ev)) > 0) + while (read(platform.gamepadStreamFd[i], &ev, sizeof(ev)) > 0) { switch(ev.type) { From d32cf0107f42b238ae9629bfd49f941deca4a9fc Mon Sep 17 00:00:00 2001 From: Michael Date: Fri, 13 Oct 2023 12:10:12 -0400 Subject: [PATCH 25/33] Update example --- examples/core/core_input_gamepad_info.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/core/core_input_gamepad_info.c b/examples/core/core_input_gamepad_info.c index 8a33bd66b..77a4a5da1 100644 --- a/examples/core/core_input_gamepad_info.c +++ b/examples/core/core_input_gamepad_info.c @@ -56,7 +56,7 @@ int main(void) } for (int button = 0; button < 32; button++) { - DrawText(TextFormat("\tButton %d = %d", button, IsGamepadButtonPressed(i, button)), 10, y, 20, BLACK); + DrawText(TextFormat("\tButton %d = %d", button, IsGamepadButtonDown(i, button)), 10, y, 20, BLACK); y += 30; } } From 53901aecfd6c3c5e203ecd2f641198b2d46b38ff Mon Sep 17 00:00:00 2001 From: Michael Date: Fri, 13 Oct 2023 12:11:34 -0400 Subject: [PATCH 26/33] dumb logging --- src/rcore_drm.c | 1 + 1 file changed, 1 insertion(+) diff --git a/src/rcore_drm.c b/src/rcore_drm.c index 6bfeada62..6316c3195 100644 --- a/src/rcore_drm.c +++ b/src/rcore_drm.c @@ -1579,6 +1579,7 @@ static void PollDrmJoystickEvents() case EV_KEY: if (ev.code < MAX_GAMEPAD_BUTTONS) { + printf("b %d = %d\n:", ev.code, ev.value); CORE.Input.Gamepad.currentButtonState[i][ev.code] = ev.value; for (int lookupButton = 0; lookupButton < MAX_GAMEPAD_BUTTONS; lookupButton++) { From d879090ce9fa15f91e59054f94535287cdb147d6 Mon Sep 17 00:00:00 2001 From: Michael Date: Fri, 13 Oct 2023 12:13:30 -0400 Subject: [PATCH 27/33] Wrong constant for ev.code handling --- src/rcore_drm.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/rcore_drm.c b/src/rcore_drm.c index 6316c3195..54a1dac33 100644 --- a/src/rcore_drm.c +++ b/src/rcore_drm.c @@ -1577,7 +1577,7 @@ static void PollDrmJoystickEvents() switch(ev.type) { case EV_KEY: - if (ev.code < MAX_GAMEPAD_BUTTONS) + if (ev.code < KEY_MAX) { printf("b %d = %d\n:", ev.code, ev.value); CORE.Input.Gamepad.currentButtonState[i][ev.code] = ev.value; From 7e08cef7f5d0da0ca65aa588a08a20f917b7de60 Mon Sep 17 00:00:00 2001 From: Michael Date: Fri, 13 Oct 2023 12:15:16 -0400 Subject: [PATCH 28/33] More dumb logging --- src/rcore_drm.c | 1 + 1 file changed, 1 insertion(+) diff --git a/src/rcore_drm.c b/src/rcore_drm.c index 54a1dac33..83922c580 100644 --- a/src/rcore_drm.c +++ b/src/rcore_drm.c @@ -1574,6 +1574,7 @@ static void PollDrmJoystickEvents() while (read(platform.gamepadStreamFd[i], &ev, sizeof(ev)) > 0) { + printf("event type: %d\n", ev.type); switch(ev.type) { case EV_KEY: From 3691c488c8b02dd5a78a0dd192095d38a906d581 Mon Sep 17 00:00:00 2001 From: Michael Date: Fri, 13 Oct 2023 12:19:34 -0400 Subject: [PATCH 29/33] Remove some logging --- src/rcore_drm.c | 3 --- 1 file changed, 3 deletions(-) diff --git a/src/rcore_drm.c b/src/rcore_drm.c index 83922c580..8f5de95d2 100644 --- a/src/rcore_drm.c +++ b/src/rcore_drm.c @@ -1523,7 +1523,6 @@ static void InitDrmJoystick(int index, const char *path) TraceLog(LOG_INFO, TextFormat("InitDrmJoystick - %s", path)); int result = (platform.gamepadStreamFd[index] = open(path, O_RDONLY | O_NONBLOCK)); - printf("Result of file open: %d\n", result); // Get the name of the device. ioctl(platform.gamepadStreamFd[index], EVIOCGNAME(64), &CORE.Input.Gamepad.name[index]); @@ -1574,13 +1573,11 @@ static void PollDrmJoystickEvents() while (read(platform.gamepadStreamFd[i], &ev, sizeof(ev)) > 0) { - printf("event type: %d\n", ev.type); switch(ev.type) { case EV_KEY: if (ev.code < KEY_MAX) { - printf("b %d = %d\n:", ev.code, ev.value); CORE.Input.Gamepad.currentButtonState[i][ev.code] = ev.value; for (int lookupButton = 0; lookupButton < MAX_GAMEPAD_BUTTONS; lookupButton++) { From e5009550c429a42a71fad68a791d5a2a87d6ae62 Mon Sep 17 00:00:00 2001 From: Michael Date: Fri, 13 Oct 2023 20:11:26 -0400 Subject: [PATCH 30/33] Add FPS to gamepad info example and try for max FPS --- examples/core/core_input_gamepad_info.c | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/examples/core/core_input_gamepad_info.c b/examples/core/core_input_gamepad_info.c index 77a4a5da1..67a7a0102 100644 --- a/examples/core/core_input_gamepad_info.c +++ b/examples/core/core_input_gamepad_info.c @@ -30,7 +30,7 @@ int main(void) InitWindow(screenWidth, screenHeight, "raylib [core] example - gamepad information"); - SetTargetFPS(60); // Set our game to run at 60 frames-per-second + // SetTargetFPS(60); // Set our game to run at 60 frames-per-second // Main game loop while (!WindowShouldClose()) // Detect window close button or ESC key @@ -62,6 +62,8 @@ int main(void) } } + DrawFPS(100, 100); + EndDrawing(); } From d833ff02d76a660d63cbf017eab7147f4caec182 Mon Sep 17 00:00:00 2001 From: Michael Date: Fri, 13 Oct 2023 20:12:36 -0400 Subject: [PATCH 31/33] tweak --- examples/core/core_input_gamepad_info.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/examples/core/core_input_gamepad_info.c b/examples/core/core_input_gamepad_info.c index 67a7a0102..97c699611 100644 --- a/examples/core/core_input_gamepad_info.c +++ b/examples/core/core_input_gamepad_info.c @@ -62,8 +62,8 @@ int main(void) } } - DrawFPS(100, 100); - + DrawFPS(400, 100); + EndDrawing(); } From e071e7f0aa45bad4091abda24e26558db2084a3b Mon Sep 17 00:00:00 2001 From: Michael Date: Fri, 13 Oct 2023 20:14:07 -0400 Subject: [PATCH 32/33] Revert example --- examples/core/core_input_gamepad_info.c | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/examples/core/core_input_gamepad_info.c b/examples/core/core_input_gamepad_info.c index 97c699611..77a4a5da1 100644 --- a/examples/core/core_input_gamepad_info.c +++ b/examples/core/core_input_gamepad_info.c @@ -30,7 +30,7 @@ int main(void) InitWindow(screenWidth, screenHeight, "raylib [core] example - gamepad information"); - // SetTargetFPS(60); // Set our game to run at 60 frames-per-second + SetTargetFPS(60); // Set our game to run at 60 frames-per-second // Main game loop while (!WindowShouldClose()) // Detect window close button or ESC key @@ -62,8 +62,6 @@ int main(void) } } - DrawFPS(400, 100); - EndDrawing(); } From 9dcb92989682832f694cfaa5d7ed2e2e910c5476 Mon Sep 17 00:00:00 2001 From: Michael Date: Fri, 13 Oct 2023 20:57:56 -0400 Subject: [PATCH 33/33] Add fps back --- examples/core/core_input_gamepad_info.c | 2 ++ 1 file changed, 2 insertions(+) diff --git a/examples/core/core_input_gamepad_info.c b/examples/core/core_input_gamepad_info.c index 77a4a5da1..f3ac49fc9 100644 --- a/examples/core/core_input_gamepad_info.c +++ b/examples/core/core_input_gamepad_info.c @@ -62,6 +62,8 @@ int main(void) } } + DrawFPS(GetScreenWidth() - 100, 100); + EndDrawing(); }