#include <fcntl.h>
#include <unistd.h>
#include <termios.h>
#include <pthread.h>
#include <dirent.h>
#include <limits.h>
#include <sys/ioctl.h>
#include <linux/kd.h>
#include <linux/input.h>
#include <linux/joystick.h>
#undef KEY_F12
#include <xf86drm.h>
#include <xf86drmMode.h>
#if !defined(GRAPHICS_API_OPENGL_SOFTWARE)
#include <gbm.h>
#include "EGL/egl.h"
#include "EGL/eglext.h"
#else
#include <sys/mman.h>
#include <errno.h>
#endif
#if defined(SUPPORT_DRM_CACHE)
#include <poll.h>
#include <errno.h>
#define MAX_DRM_CACHED_BUFFERS 3
#endif
#ifndef EGL_OPENGL_ES3_BIT
#define EGL_OPENGL_ES3_BIT 0x40
#endif
#ifndef EGL_PLATFORM_GBM_KHR
#define EGL_PLATFORM_GBM_KHR 0x31D7
#endif
#define USE_LAST_TOUCH_DEVICE
#define DEFAULT_EVDEV_PATH "/dev/input/"
#define KEYMAP_SIZE KEY_ALS_TOGGLE
typedef struct {
int fd; drmModeConnector *connector; drmModeCrtc *crtc; int modeIndex; uint32_t prevFB;
#if !defined(GRAPHICS_API_OPENGL_SOFTWARE)
struct gbm_device *gbmDevice; struct gbm_surface *gbmSurface; struct gbm_bo *prevBO; EGLDisplay device; EGLSurface surface; EGLContext context; EGLConfig config; #else
uint32_t prevDumbHandle; #endif
int defaultKeyboardMode; bool eventKeyboardMode; int defaultFileFlags; struct termios defaultSettings; int keyboardFd;
Vector2 eventWheelMove; char currentButtonStateEvdev[MAX_MOUSE_BUTTONS]; bool cursorRelative; int mouseFd; bool mouseIsTouch; Rectangle absRange; int touchSlot; bool touchActive[MAX_TOUCH_POINTS]; Vector2 touchPosition[MAX_TOUCH_POINTS]; int touchId[MAX_TOUCH_POINTS];
int gamepadStreamFd[MAX_GAMEPADS]; int gamepadAbsAxisRange[MAX_GAMEPADS][MAX_GAMEPAD_AXES][2]; int gamepadAbsAxisMap[MAX_GAMEPADS][ABS_CNT]; int gamepadCount; } PlatformData;
#if defined(SUPPORT_DRM_CACHE)
typedef struct {
struct gbm_bo *bo; uint32_t fbId; } FramebufferCache;
static FramebufferCache fbCache[MAX_DRM_CACHED_BUFFERS] = { 0 };
static volatile int fbCacheCount = 0;
static volatile bool pendingFlip = false;
static bool crtcSet = false;
#endif
extern CoreData CORE;
static PlatformData platform = { 0 };
static const int evkeyToUnicodeLUT[] = {
0, 27, 49, 50, 51, 52, 53, 54, 55, 56, 57, 48, 45, 61, 8, 0, 113, 119, 101, 114,
116, 121, 117, 105, 111, 112, 0, 0, 13, 0, 97, 115, 100, 102, 103, 104, 106, 107, 108, 59,
39, 96, 0, 92, 122, 120, 99, 118, 98, 110, 109, 44, 46, 47, 0, 0, 0, 32
};
static const short linuxToRaylibMap[KEYMAP_SIZE] = {
0, 256, 49, 50, 51, 52, 53, 54,
55, 56, 57, 48, 45, 61, 259, 258,
81, 87, 69, 82, 84, 89, 85, 73,
79, 80, 91, 93, 257, 341, 65, 83,
68, 70, 71, 72, 74, 75, 76, 59,
39, 96, 340, 92, 90, 88, 67, 86,
66, 78, 77, 44, 46, 47, 344, 332,
342, 32, 280, 290, 291, 292, 293, 294,
295, 296, 297, 298, 299, 282, 281, 327,
328, 329, 333, 324, 325, 326, 334, 321,
322, 323, 320, 330, 0, 85, 86, 300,
301, 89, 90, 91, 92, 93, 94, 95,
335, 345, 331, 283, 346, 101, 268, 265,
266, 263, 262, 269, 264, 267, 260, 261,
112, 113, 114, 115, 116, 117, 118, 119,
120, 121, 122, 123, 124, 125, 347, 127,
128, 129, 130, 131, 132, 133, 134, 135,
136, 137, 138, 139, 140, 141, 142, 143,
144, 145, 146, 147, 148, 149, 150, 151,
152, 153, 154, 155, 156, 157, 158, 159,
160, 161, 162, 163, 164, 165, 166, 167,
168, 169, 170, 171, 172, 173, 174, 175,
176, 177, 178, 179, 180, 181, 182, 183,
184, 185, 186, 187, 188, 189, 190, 191,
192, 193, 194, 0, 0, 0, 0, 0,
200, 201, 202, 203, 204, 205, 206, 207,
208, 209, 210, 211, 212, 213, 214, 215,
216, 217, 218, 219, 220, 221, 222, 223,
224, 225, 226, 227, 228, 229, 230, 231,
232, 233, 234, 235, 236, 237, 238, 239,
240, 241, 242, 243, 244, 245, 246, 247,
248, 0, 0, 0, 0, 0, 0, 0,
[BTN_DPAD_UP] = GAMEPAD_BUTTON_LEFT_FACE_UP,
[BTN_DPAD_RIGHT] = GAMEPAD_BUTTON_LEFT_FACE_RIGHT,
[BTN_DPAD_DOWN] = GAMEPAD_BUTTON_LEFT_FACE_DOWN,
[BTN_DPAD_LEFT] = GAMEPAD_BUTTON_LEFT_FACE_LEFT,
[BTN_Y] = GAMEPAD_BUTTON_RIGHT_FACE_UP,
[BTN_B] = GAMEPAD_BUTTON_RIGHT_FACE_RIGHT,
[BTN_A] = GAMEPAD_BUTTON_RIGHT_FACE_DOWN,
[BTN_X] = GAMEPAD_BUTTON_RIGHT_FACE_LEFT,
[BTN_TL] = GAMEPAD_BUTTON_LEFT_TRIGGER_1,
[BTN_TL2] = GAMEPAD_BUTTON_LEFT_TRIGGER_2,
[BTN_TR] = GAMEPAD_BUTTON_RIGHT_TRIGGER_1,
[BTN_TR2] = GAMEPAD_BUTTON_RIGHT_TRIGGER_2,
[BTN_SELECT] = GAMEPAD_BUTTON_MIDDLE_LEFT,
[BTN_MODE] = GAMEPAD_BUTTON_MIDDLE,
[BTN_START] = GAMEPAD_BUTTON_MIDDLE_RIGHT,
[BTN_THUMBL] = GAMEPAD_BUTTON_LEFT_THUMB,
[BTN_THUMBR] = GAMEPAD_BUTTON_RIGHT_THUMB,
};
int InitPlatform(void); void ClosePlatform(void);
#if SUPPORT_SSH_KEYBOARD_RPI
static void InitKeyboard(void); static void RestoreKeyboard(void); static void ProcessKeyboard(void); #endif
static void InitEvdevInput(void); static void ConfigureEvdevDevice(char *device); static void PollKeyboardEvents(void); static void PollGamepadEvents(void); static void PollMouseEvents(void);
static int FindMatchingConnectorMode(const drmModeConnector *connector, const drmModeModeInfo *mode); static int FindExactConnectorMode(const drmModeConnector *connector, uint width, uint height, uint fps, bool allowInterlaced); static int FindNearestConnectorMode(const drmModeConnector *connector, uint width, uint height, uint fps, bool allowInterlaced);
static void SetupFramebuffer(int width, int height);
bool WindowShouldClose(void)
{
if (CORE.Window.ready) return CORE.Window.shouldClose;
else return true;
}
void ToggleFullscreen(void)
{
TRACELOG(LOG_WARNING, "ToggleFullscreen() not available on target platform");
}
void ToggleBorderlessWindowed(void)
{
TRACELOG(LOG_WARNING, "ToggleBorderlessWindowed() not available on target platform");
}
void MaximizeWindow(void)
{
TRACELOG(LOG_WARNING, "MaximizeWindow() not available on target platform");
}
void MinimizeWindow(void)
{
TRACELOG(LOG_WARNING, "MinimizeWindow() not available on target platform");
}
void RestoreWindow(void)
{
TRACELOG(LOG_WARNING, "RestoreWindow() not available on target platform");
}
void SetWindowState(unsigned int flags)
{
TRACELOG(LOG_WARNING, "SetWindowState() not available on target platform");
}
void ClearWindowState(unsigned int flags)
{
TRACELOG(LOG_WARNING, "ClearWindowState() not available on target platform");
}
void SetWindowIcon(Image image)
{
TRACELOG(LOG_WARNING, "SetWindowIcon() not available on target platform");
}
void SetWindowIcons(Image *images, int count)
{
TRACELOG(LOG_WARNING, "SetWindowIcons() not available on target platform");
}
void SetWindowTitle(const char *title)
{
CORE.Window.title = title;
}
void SetWindowPosition(int x, int y)
{
TRACELOG(LOG_WARNING, "SetWindowPosition() not available on target platform");
}
void SetWindowMonitor(int monitor)
{
TRACELOG(LOG_WARNING, "SetWindowMonitor() not available on target platform");
}
void SetWindowMinSize(int width, int height)
{
CORE.Window.screenMin.width = width;
CORE.Window.screenMin.height = height;
}
void SetWindowMaxSize(int width, int height)
{
CORE.Window.screenMax.width = width;
CORE.Window.screenMax.height = height;
}
void SetWindowSize(int width, int height)
{
TRACELOG(LOG_WARNING, "SetWindowSize() not available on target platform");
}
void SetWindowOpacity(float opacity)
{
TRACELOG(LOG_WARNING, "SetWindowOpacity() not available on target platform");
}
void SetWindowFocused(void)
{
TRACELOG(LOG_WARNING, "SetWindowFocused() not available on target platform");
}
void *GetWindowHandle(void)
{
TRACELOG(LOG_WARNING, "GetWindowHandle() not implemented on target platform");
return NULL;
}
int GetMonitorCount(void)
{
TRACELOG(LOG_WARNING, "GetMonitorCount() not implemented on target platform");
return 1;
}
int GetCurrentMonitor(void)
{
TRACELOG(LOG_WARNING, "GetCurrentMonitor() not implemented on target platform");
return 0;
}
Vector2 GetMonitorPosition(int monitor)
{
TRACELOG(LOG_WARNING, "GetMonitorPosition() not implemented on target platform");
return (Vector2){ 0, 0 };
}
int GetMonitorWidth(int monitor)
{
int width = 0;
if (monitor != 0)
{
TRACELOG(LOG_WARNING, "GetMonitorWidth() implemented for first monitor only");
}
else if ((platform.connector) && (platform.modeIndex >= 0))
{
width = platform.connector->modes[platform.modeIndex].hdisplay;
}
return width;
}
int GetMonitorHeight(int monitor)
{
int height = 0;
if (monitor != 0)
{
TRACELOG(LOG_WARNING, "GetMonitorHeight() implemented for first monitor only");
}
else if ((platform.connector) && (platform.modeIndex >= 0))
{
height = platform.connector->modes[platform.modeIndex].vdisplay;
}
return height;
}
int GetMonitorPhysicalWidth(int monitor)
{
int physicalWidth = 0;
if (monitor != 0)
{
TRACELOG(LOG_WARNING, "GetMonitorPhysicalWidth() implemented for first monitor only");
}
else if ((platform.connector) && (platform.modeIndex >= 0))
{
physicalWidth = platform.connector->mmWidth;
}
return physicalWidth;
}
int GetMonitorPhysicalHeight(int monitor)
{
int physicalHeight = 0;
if (monitor != 0)
{
TRACELOG(LOG_WARNING, "GetMonitorPhysicalHeight() implemented for first monitor only");
}
else if ((platform.connector) && (platform.modeIndex >= 0))
{
physicalHeight = platform.connector->mmHeight;
}
return physicalHeight;
}
int GetMonitorRefreshRate(int monitor)
{
int refresh = 0;
if ((platform.connector) && (platform.modeIndex >= 0))
{
refresh = platform.connector->modes[platform.modeIndex].vrefresh;
}
return refresh;
}
const char *GetMonitorName(int monitor)
{
const char *name = "";
if (monitor != 0)
{
TRACELOG(LOG_WARNING, "GetMonitorName() implemented for first monitor only");
}
else if ((platform.connector) && (platform.modeIndex >= 0))
{
name = platform.connector->modes[platform.modeIndex].name;
}
return name;
}
Vector2 GetWindowPosition(void)
{
return (Vector2){ 0, 0 };
}
Vector2 GetWindowScaleDPI(void)
{
return (Vector2){ 1.0f, 1.0f };
}
void SetClipboardText(const char *text)
{
TRACELOG(LOG_WARNING, "SetClipboardText() not implemented on target platform");
}
const char *GetClipboardText(void)
{
TRACELOG(LOG_WARNING, "GetClipboardText() not implemented on target platform");
return NULL;
}
Image GetClipboardImage(void)
{
Image image = { 0 };
TRACELOG(LOG_WARNING, "GetClipboardImage() not implemented on target platform");
return image;
}
void ShowCursor(void)
{
CORE.Input.Mouse.cursorHidden = false;
}
void HideCursor(void)
{
CORE.Input.Mouse.cursorHidden = true;
}
void EnableCursor(void)
{
SetMousePosition(CORE.Window.screen.width/2, CORE.Window.screen.height/2);
platform.cursorRelative = false;
CORE.Input.Mouse.cursorLocked = false;
}
void DisableCursor(void)
{
SetMousePosition(0, 0);
platform.cursorRelative = true;
CORE.Input.Mouse.cursorLocked = true;
}
#if defined(SUPPORT_DRM_CACHE)
static void DestroyFrameBufferCallback(struct gbm_bo *bo, void *data)
{
uint32_t fbId = (uintptr_t)data;
for (int i = 0; i < fbCacheCount; i++)
{
if (fbCache[i].bo == bo)
{
TRACELOG(LOG_INFO, "DISPLAY: DRM: Framebuffer removed [%u]", (uintptr_t)fbId);
drmModeRmFB(platform.fd, fbCache[i].fbId);
for (int j = i; j < fbCacheCount - 1; j++) fbCache[j] = fbCache[j + 1];
fbCacheCount--;
break;
}
}
}
static uint32_t GetOrCreateFbForBo(struct gbm_bo *bo)
{
for (int i = 0; i < fbCacheCount; i++)
{
if (fbCache[i].bo == bo) return fbCache[i].fbId;
}
if (fbCacheCount >= MAX_DRM_CACHED_BUFFERS) return 0;
uint32_t handle = gbm_bo_get_handle(bo).u32;
uint32_t stride = gbm_bo_get_stride(bo);
uint32_t width = gbm_bo_get_width(bo);
uint32_t height = gbm_bo_get_height(bo);
uint32_t fbId = 0;
if (drmModeAddFB(platform.fd, width, height, 24, 32, stride, handle, &fbId)) return 0;
fbCache[fbCacheCount] = (FramebufferCache){ .bo = bo, .fbId = fbId };
fbCacheCount++;
gbm_bo_set_user_data(bo, (void *)(uintptr_t)fbId, DestroyFrameBufferCallback);
TRACELOG(LOG_INFO, "DISPLAY: DRM: Added new buffer object [%u]" , (uintptr_t)fbId);
return fbId;
}
void RenderBlankFrame()
{
glClearColor(0, 0, 0, 1);
glClear(GL_COLOR_BUFFER_BIT);
eglSwapBuffers(platform.device, platform.surface);
glFinish(); }
int InitSwapScreenBuffer()
{
if (!platform.gbmSurface || (platform.fd < 0))
{
TRACELOG(LOG_ERROR, "DISPLAY: DRM: Swap buffers can not be initialized");
return -1;
}
RenderBlankFrame();
struct gbm_bo *bo = gbm_surface_lock_front_buffer(platform.gbmSurface);
if (!bo)
{
TRACELOG(LOG_ERROR, "DISPLAY: DRM: Failed to lock initial swap buffer");
return -1;
}
uint32_t fbId = GetOrCreateFbForBo(bo);
if (!fbId)
{
gbm_surface_release_buffer(platform.gbmSurface, bo);
return -1;
}
if (drmModeSetCrtc(platform.fd, platform.crtc->crtc_id, fbId, 0, 0, &platform.connector->connector_id, 1, &platform.connector->modes[platform.modeIndex]))
{
TRACELOG(LOG_ERROR, "DISPLAY: DRM: Failed to initialize CRTC setup. ERROR: %s", strerror(errno));
gbm_surface_release_buffer(platform.gbmSurface, bo);
return -1;
}
platform.prevBO = bo;
crtcSet = true;
return 0;
}
static void PageFlipHandler(int fd, unsigned int frame, unsigned int sec, unsigned int usec, void *data)
{
(void)fd;
(void)frame;
(void)sec;
(void)usec;
pendingFlip = false;
struct gbm_bo *boToRelease = (struct gbm_bo *)data;
if (boToRelease) gbm_surface_release_buffer(platform.gbmSurface, boToRelease);
}
void SwapScreenBuffer()
{
if (!crtcSet || !platform.gbmSurface) return;
static int loopCnt = 0;
static int errCnt[5] = { 0 };
loopCnt++;
eglSwapBuffers(platform.device, platform.surface);
drmEventContext evctx = {
.version = DRM_EVENT_CONTEXT_VERSION,
.page_flip_handler = PageFlipHandler
};
struct pollfd pfd = { .fd = platform.fd, .events = POLLIN };
while (poll(&pfd, 1, 0) > 0) drmHandleEvent(platform.fd, &evctx);
if (pendingFlip)
{
errCnt[0]++; return;
}
struct gbm_bo *nextBO = gbm_surface_lock_front_buffer(platform.gbmSurface);
if (!nextBO) {
errCnt[1]++;
return;
}
uint32_t fbId = GetOrCreateFbForBo(nextBO);
if (!fbId)
{
gbm_surface_release_buffer(platform.gbmSurface, nextBO);
errCnt[2]++;
return;
}
if (drmModePageFlip(platform.fd, platform.crtc->crtc_id, fbId, DRM_MODE_PAGE_FLIP_EVENT, platform.prevBO))
{
if (errno == EBUSY) errCnt[3]++; else errCnt[4]++;
gbm_surface_release_buffer(platform.gbmSurface, nextBO);
return;
}
pendingFlip = true;
platform.prevBO = nextBO;
}
#else
void SwapScreenBuffer(void)
{
#if !defined(GRAPHICS_API_OPENGL_SOFTWARE)
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;
#else
if ((platform.fd == -1) || !platform.connector || (platform.modeIndex < 0))
{
TRACELOG(LOG_ERROR, "DISPLAY: DRM initialization failed to swap");
return;
}
drmModeModeInfo *mode = &platform.connector->modes[platform.modeIndex];
uint32_t width = mode->hdisplay;
uint32_t height = mode->vdisplay;
const uint32_t bpp = 32; const uint32_t depth = 24;
struct drm_mode_create_dumb creq = { 0 };
creq.width = width;
creq.height = height;
creq.bpp = bpp;
int result = drmIoctl(platform.fd, DRM_IOCTL_MODE_CREATE_DUMB, &creq);
if (result < 0)
{
TRACELOG(LOG_ERROR, "DISPLAY: Failed to create dumb buffer: %s", strerror(errno));
return;
}
uint32_t fb = 0;
result = drmModeAddFB(platform.fd, width, height, depth, bpp, creq.pitch, creq.handle, &fb);
if (result != 0)
{
TRACELOG(LOG_ERROR, "DISPLAY: drmModeAddFB() failed with result: %d (%s)", result, strerror(errno));
struct drm_mode_destroy_dumb dreq = { 0 };
dreq.handle = creq.handle;
drmIoctl(platform.fd, DRM_IOCTL_MODE_DESTROY_DUMB, &dreq);
return;
}
struct drm_mode_map_dumb mreq = { 0 };
mreq.handle = creq.handle;
result = drmIoctl(platform.fd, DRM_IOCTL_MODE_MAP_DUMB, &mreq);
if (result != 0)
{
TRACELOG(LOG_ERROR, "DISPLAY: Failed to map dumb buffer: %s", strerror(errno));
drmModeRmFB(platform.fd, fb);
struct drm_mode_destroy_dumb dreq = { 0 };
dreq.handle = creq.handle;
drmIoctl(platform.fd, DRM_IOCTL_MODE_DESTROY_DUMB, &dreq);
return;
}
void *dumbBuffer = mmap(0, creq.size, PROT_READ | PROT_WRITE, MAP_SHARED, platform.fd, mreq.offset);
if (dumbBuffer == MAP_FAILED)
{
TRACELOG(LOG_ERROR, "DISPLAY: Failed to mmap dumb buffer: %s", strerror(errno));
drmModeRmFB(platform.fd, fb);
struct drm_mode_destroy_dumb dreq = { 0 };
dreq.handle = creq.handle;
drmIoctl(platform.fd, DRM_IOCTL_MODE_DESTROY_DUMB, &dreq);
return;
}
swBlitPixels(0, 0, width, height, 0, 0, width, height, SW_RGBA, SW_UNSIGNED_BYTE, dumbBuffer);
munmap(dumbBuffer, creq.size);
uint32_t crtcId = 0;
if (platform.crtc) crtcId = platform.crtc->crtc_id;
else
{
drmModeRes *res = drmModeGetResources(platform.fd);
if (!res)
{
TRACELOG(LOG_ERROR, "DISPLAY: Failed to get DRM resources");
drmModeRmFB(platform.fd, fb);
struct drm_mode_destroy_dumb dreq = { 0 };
dreq.handle = creq.handle;
drmIoctl(platform.fd, DRM_IOCTL_MODE_DESTROY_DUMB, &dreq);
return;
}
drmModeEncoder *encoder = NULL;
if (platform.connector->encoder_id) encoder = drmModeGetEncoder(platform.fd, platform.connector->encoder_id);
if (encoder && encoder->crtc_id)
{
crtcId = encoder->crtc_id;
platform.crtc = drmModeGetCrtc(platform.fd, crtcId);
}
else
{
for (int i = 0; i < res->count_crtcs; i++)
{
drmModeCrtc *crtc = drmModeGetCrtc(platform.fd, res->crtcs[i]);
if (crtc && !crtc->buffer_id) {
crtcId = res->crtcs[i];
if (platform.crtc) drmModeFreeCrtc(platform.crtc);
platform.crtc = crtc;
break;
}
if (crtc) drmModeFreeCrtc(crtc);
}
}
if (encoder) drmModeFreeEncoder(encoder);
drmModeFreeResources(res);
if (!crtcId)
{
TRACELOG(LOG_ERROR, "DISPLAY: No compatible CRTC found");
drmModeRmFB(platform.fd, fb);
struct drm_mode_destroy_dumb dreq = { 0 };
dreq.handle = creq.handle;
drmIoctl(platform.fd, DRM_IOCTL_MODE_DESTROY_DUMB, &dreq);
return;
}
}
result = drmModeSetCrtc(platform.fd, crtcId, fb, 0, 0, &platform.connector->connector_id, 1, mode);
if (result != 0)
{
TRACELOG(LOG_ERROR, "DISPLAY: drmModeSetCrtc() failed with result: %d (%s)", result, strerror(errno));
TRACELOG(LOG_ERROR, "DISPLAY: CRTC ID: %u, FB ID: %u, Connector ID: %u", crtcId, fb, platform.connector->connector_id);
TRACELOG(LOG_ERROR, "DISPLAY: Mode: %dx%d@%d", mode->hdisplay, mode->vdisplay, mode->vrefresh);
drmModeRmFB(platform.fd, fb);
struct drm_mode_destroy_dumb dreq = { 0 };
dreq.handle = creq.handle;
drmIoctl(platform.fd, DRM_IOCTL_MODE_DESTROY_DUMB, &dreq);
return;
}
if (platform.prevFB)
{
result = drmModeRmFB(platform.fd, platform.prevFB);
if (result != 0) TRACELOG(LOG_WARNING, "DISPLAY: drmModeRmFB() failed with result: %d", result);
}
platform.prevFB = fb;
if (platform.prevDumbHandle)
{
struct drm_mode_destroy_dumb dreq = { 0 };
dreq.handle = platform.prevDumbHandle;
drmIoctl(platform.fd, DRM_IOCTL_MODE_DESTROY_DUMB, &dreq);
}
platform.prevDumbHandle = creq.handle;
#endif
}
#endif
double GetTime(void)
{
double time = 0.0;
struct timespec ts = { 0 };
clock_gettime(CLOCK_MONOTONIC, &ts);
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;
return time;
}
void OpenURL(const char *url)
{
TRACELOG(LOG_WARNING, "OpenURL() not implemented on target platform");
}
int SetGamepadMappings(const char *mappings)
{
TRACELOG(LOG_WARNING, "SetGamepadMappings() not implemented on target platform");
return 0;
}
void SetGamepadVibration(int gamepad, float leftMotor, float rightMotor, float duration)
{
TRACELOG(LOG_WARNING, "SetGamepadVibration() not implemented on target platform");
}
void SetMousePosition(int x, int y)
{
CORE.Input.Mouse.currentPosition = (Vector2){ (float)x, (float)y };
CORE.Input.Mouse.previousPosition = CORE.Input.Mouse.currentPosition;
}
void SetMouseCursor(int cursor)
{
TRACELOG(LOG_WARNING, "SetMouseCursor() not implemented on target platform");
}
const char *GetKeyName(int key)
{
TRACELOG(LOG_WARNING, "GetKeyName() not implemented on target platform");
return "";
}
void PollInputEvents(void)
{
#if SUPPORT_GESTURES_SYSTEM
UpdateGestures();
#endif
CORE.Input.Keyboard.keyPressedQueueCount = 0;
CORE.Input.Keyboard.charPressedQueueCount = 0;
CORE.Input.Gamepad.lastButtonPressed = 0;
for (int i = 0; i < MAX_KEYBOARD_KEYS; i++)
{
CORE.Input.Keyboard.previousKeyState[i] = CORE.Input.Keyboard.currentKeyState[i];
CORE.Input.Keyboard.keyRepeatInFrame[i] = 0;
}
PollKeyboardEvents();
#if SUPPORT_SSH_KEYBOARD_RPI
if (!platform.eventKeyboardMode) ProcessKeyboard();
#endif
if (CORE.Input.Keyboard.currentKeyState[CORE.Input.Keyboard.exitKey] == 1) CORE.Window.shouldClose = true;
if (platform.cursorRelative) CORE.Input.Mouse.currentPosition = (Vector2){ 0.0f, 0.0f };
else CORE.Input.Mouse.previousPosition = CORE.Input.Mouse.currentPosition;
CORE.Input.Mouse.previousWheelMove = CORE.Input.Mouse.currentWheelMove;
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] = platform.currentButtonStateEvdev[i];
CORE.Input.Touch.currentTouchState[i] = platform.currentButtonStateEvdev[i];
}
PollGamepadEvents();
for (int i = 0; i < MAX_TOUCH_POINTS; i++) CORE.Input.Touch.previousTouchState[i] = CORE.Input.Touch.currentTouchState[i];
PollMouseEvents();
}
int InitPlatform(void)
{
platform.fd = -1;
platform.connector = NULL;
platform.modeIndex = -1;
platform.crtc = NULL;
platform.prevFB = 0;
#if !defined(GRAPHICS_API_OPENGL_SOFTWARE)
platform.gbmDevice = NULL;
platform.gbmSurface = NULL;
platform.prevBO = NULL;
#else
platform.prevDumbHandle = 0;
#endif
FLAG_SET(CORE.Window.flags, FLAG_FULLSCREEN_MODE);
#if defined(DEFAULT_GRAPHIC_DEVICE_DRM)
platform.fd = open(DEFAULT_GRAPHIC_DEVICE_DRM, O_RDWR);
if (platform.fd != -1) TRACELOG(LOG_INFO, "DISPLAY: Default graphic device DRM opened successfully");
#else
TRACELOG(LOG_WARNING, "DISPLAY: No graphic card set, trying platform-gpu-card");
platform.fd = open("/dev/dri/by-path/platform-gpu-card", O_RDWR); if (platform.fd != -1) TRACELOG(LOG_INFO, "DISPLAY: platform-gpu-card opened successfully");
drmModeRes *res = NULL;
if ((platform.fd == -1) || ((res = drmModeGetResources(platform.fd)) == NULL))
{
if (platform.fd != -1) close(platform.fd);
TRACELOG(LOG_WARNING, "DISPLAY: Failed to open platform-gpu-card, trying card1");
platform.fd = open("/dev/dri/card1", O_RDWR); if (platform.fd != -1) TRACELOG(LOG_INFO, "DISPLAY: card1 opened successfully");
}
if ((platform.fd == -1) || ((res = drmModeGetResources(platform.fd)) == NULL))
{
if (platform.fd != -1) close(platform.fd);
TRACELOG(LOG_WARNING, "DISPLAY: Failed to open graphic card1, trying card0");
platform.fd = open("/dev/dri/card0", O_RDWR); if (platform.fd != -1) TRACELOG(LOG_INFO, "DISPLAY: card0 opened successfully");
}
if ((platform.fd == -1) || ((res = drmModeGetResources(platform.fd)) == NULL))
{
if (platform.fd != -1) close(platform.fd);
TRACELOG(LOG_WARNING, "DISPLAY: Failed to open graphic card0, trying card2");
platform.fd = open("/dev/dri/card2", O_RDWR);
if (platform.fd != -1) TRACELOG(LOG_INFO, "DISPLAY: card2 opened successfully");
}
#endif
if (platform.fd == -1)
{
TRACELOG(LOG_WARNING, "DISPLAY: Failed to open graphic card");
return -1;
}
if (!res)
{
TRACELOG(LOG_WARNING, "DISPLAY: Failed get DRM resources");
close(platform.fd);
return -1;
}
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]);
if (!con)
{
TRACELOG(LOG_WARNING, "DISPLAY: Failed to get connector %i", i);
continue;
}
TRACELOG(LOG_TRACE, "DISPLAY: Connector %i modes detected: %i", i, con->count_modes);
TRACELOG(LOG_TRACE, "DISPLAY: Connector %i status: %s", i,
(con->connection == DRM_MODE_CONNECTED)? "CONNECTED" :
(con->connection == DRM_MODE_DISCONNECTED)? "DISCONNECTED" :
(con->connection == DRM_MODE_UNKNOWNCONNECTION)? "UNKNOWN" : "OTHER");
if (((con->connection == DRM_MODE_CONNECTED) || (con->connection == DRM_MODE_UNKNOWNCONNECTION)) && (con->count_modes > 0))
{
#if !defined(GRAPHICS_API_OPENGL_SOFTWARE)
if (con->encoder_id)
{
TRACELOG(LOG_TRACE, "DISPLAY: DRM connector %i connected with encoder", i);
platform.connector = con;
break;
}
else TRACELOG(LOG_TRACE, "DISPLAY: DRM connector %i connected but no encoder", i);
#else
TRACELOG(LOG_TRACE, "DISPLAY: DRM connector %i suitable for software rendering", i);
platform.connector = con;
break;
#endif
}
if (!platform.connector)
{
TRACELOG(LOG_TRACE, "DISPLAY: DRM connector %i NOT suitable (deleting)", i);
drmModeFreeConnector(con);
}
}
if (!platform.connector)
{
TRACELOG(LOG_WARNING, "DISPLAY: No suitable DRM connector found");
drmModeFreeResources(res);
close(platform.fd);
return -1;
}
#if !defined(GRAPHICS_API_OPENGL_SOFTWARE)
drmModeEncoder *enc = drmModeGetEncoder(platform.fd, platform.connector->encoder_id);
if (!enc)
{
TRACELOG(LOG_WARNING, "DISPLAY: Failed to get DRM mode encoder");
drmModeFreeConnector(platform.connector);
drmModeFreeResources(res);
close(platform.fd);
return -1;
}
platform.crtc = drmModeGetCrtc(platform.fd, enc->crtc_id);
if (!platform.crtc)
{
TRACELOG(LOG_WARNING, "DISPLAY: Failed to get DRM mode crtc");
drmModeFreeEncoder(enc);
drmModeFreeConnector(platform.connector);
drmModeFreeResources(res);
close(platform.fd);
return -1;
}
if ((CORE.Window.screen.width <= 0) || (CORE.Window.screen.height <= 0))
{
TRACELOG(LOG_TRACE, "DISPLAY: Selecting DRM connector mode for current used mode...");
platform.modeIndex = FindMatchingConnectorMode(platform.connector, &platform.crtc->mode);
if (platform.modeIndex < 0)
{
TRACELOG(LOG_WARNING, "DISPLAY: No matching DRM connector mode found");
drmModeFreeEncoder(enc);
drmModeFreeConnector(platform.connector);
drmModeFreeResources(res);
close(platform.fd);
return -1;
}
CORE.Window.screen.width = CORE.Window.display.width;
CORE.Window.screen.height = CORE.Window.display.height;
}
const bool allowInterlaced = FLAG_IS_SET(CORE.Window.flags, FLAG_INTERLACED_HINT);
const int fps = (CORE.Time.target > 0)? (1.0/CORE.Time.target) : 60;
platform.modeIndex = FindExactConnectorMode(platform.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 (platform.modeIndex < 0) platform.modeIndex = FindExactConnectorMode(platform.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 (platform.modeIndex < 0)
{
TRACELOG(LOG_WARNING, "DISPLAY: Failed to find a suitable DRM connector mode");
drmModeFreeEncoder(enc);
drmModeFreeConnector(platform.connector);
drmModeFreeResources(res);
close(platform.fd);
return -1;
}
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)", platform.connector->modes[platform.modeIndex].name,
platform.connector->modes[platform.modeIndex].hdisplay, platform.connector->modes[platform.modeIndex].vdisplay,
FLAG_IS_SET(platform.connector->modes[platform.modeIndex].flags, DRM_MODE_FLAG_INTERLACE)? 'i' : 'p',
platform.connector->modes[platform.modeIndex].vrefresh);
drmModeFreeEncoder(enc);
enc = NULL;
#else
if (platform.connector->count_modes > 0)
{
platform.modeIndex = 0;
CORE.Window.display.width = platform.connector->modes[0].hdisplay;
CORE.Window.display.height = platform.connector->modes[0].vdisplay;
TRACELOG(LOG_INFO, "DISPLAY: Selected DRM connector mode %s (%ux%u%c@%u) for software rendering",
platform.connector->modes[0].name,
platform.connector->modes[0].hdisplay,
platform.connector->modes[0].vdisplay,
(platform.connector->modes[0].flags & DRM_MODE_FLAG_INTERLACE)? 'i' : 'p',
platform.connector->modes[0].vrefresh);
}
else
{
TRACELOG(LOG_WARNING, "DISPLAY: No modes available for connector");
drmModeFreeConnector(platform.connector);
drmModeFreeResources(res);
close(platform.fd);
return -1;
}
#endif
CORE.Window.render.width = CORE.Window.screen.width;
CORE.Window.render.height = CORE.Window.screen.height;
drmModeFreeResources(res);
res = NULL;
#if !defined(GRAPHICS_API_OPENGL_SOFTWARE)
platform.gbmDevice = gbm_create_device(platform.fd);
if (!platform.gbmDevice)
{
TRACELOG(LOG_WARNING, "DISPLAY: Failed to create GBM device");
return -1;
}
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 -1;
}
EGLint samples = 0;
EGLint sampleBuffer = 0;
if (FLAG_IS_SET(CORE.Window.flags, FLAG_MSAA_4X_HINT))
{
samples = 4;
sampleBuffer = 1;
TRACELOG(LOG_INFO, "DISPLAY: Trying to enable MSAA x4");
}
const EGLint framebufferAttribs[] = {
EGL_RENDERABLE_TYPE, (rlGetVersion() == RL_OPENGL_ES_30)? EGL_OPENGL_ES3_BIT : EGL_OPENGL_ES2_BIT, EGL_SURFACE_TYPE, EGL_WINDOW_BIT, EGL_RED_SIZE, 8, EGL_GREEN_SIZE, 8, EGL_BLUE_SIZE, 8, EGL_ALPHA_SIZE, 8, EGL_DEPTH_SIZE, 24, EGL_SAMPLE_BUFFERS, sampleBuffer, EGL_SAMPLES, samples, EGL_NONE
};
const EGLint contextAttribs[] = {
EGL_CONTEXT_CLIENT_VERSION, 2,
EGL_NONE
};
EGLint numConfigs = 0;
const char *eglClientExtensions = NULL;
platform.device = EGL_NO_DISPLAY;
#if defined(EGL_VERSION_1_5)
platform.device = eglGetPlatformDisplay(EGL_PLATFORM_GBM_KHR, platform.gbmDevice, NULL);
#else
eglClientExtensions = eglQueryString(EGL_NO_DISPLAY, EGL_EXTENSIONS);
if ((eglClientExtensions != NULL) && (strstr(eglClientExtensions, "EGL_EXT_platform_base") != NULL))
{
PFNEGLGETPLATFORMDISPLAYEXTPROC eglGetPlatformDisplayEXT = (PFNEGLGETPLATFORMDISPLAYEXTPROC)eglGetProcAddress("eglGetPlatformDisplayEXT");
if (eglGetPlatformDisplayEXT != NULL) platform.device = eglGetPlatformDisplayEXT(EGL_PLATFORM_GBM_KHR, platform.gbmDevice, NULL);
}
if (platform.device == EGL_NO_DISPLAY) platform.device = eglGetDisplay((EGLNativeDisplayType)platform.gbmDevice);
#endif
if (platform.device == EGL_NO_DISPLAY)
{
TRACELOG(LOG_WARNING, "DISPLAY: Failed to initialize EGL device");
return -1;
}
if (eglInitialize(platform.device, NULL, NULL) == EGL_FALSE)
{
TRACELOG(LOG_WARNING, "DISPLAY: Failed to initialize EGL device");
return -1;
}
if (!eglChooseConfig(platform.device, NULL, NULL, 0, &numConfigs))
{
TRACELOG(LOG_WARNING, "DISPLAY: Failed to get EGL config count: 0x%x", eglGetError());
return -1;
}
TRACELOG(LOG_TRACE, "DISPLAY: EGL configs available: %d", numConfigs);
EGLConfig *configs = (EGLConfig *)RL_CALLOC(numConfigs, sizeof(*configs));
if (!configs)
{
TRACELOG(LOG_WARNING, "DISPLAY: Failed to get memory for EGL configs");
return -1;
}
EGLint matchingNumConfigs = 0;
if (!eglChooseConfig(platform.device, framebufferAttribs, configs, numConfigs, &matchingNumConfigs))
{
TRACELOG(LOG_WARNING, "DISPLAY: Failed to choose EGL config: 0x%x", eglGetError());
RL_FREE(configs);
return -1;
}
TRACELOG(LOG_TRACE, "DISPLAY: EGL matching configs available: %d", matchingNumConfigs);
int found = 0;
for (EGLint i = 0; i < matchingNumConfigs; i++)
{
EGLint id = 0;
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;
}
if (GBM_FORMAT_ARGB8888 == id)
{
TRACELOG(LOG_TRACE, "DISPLAY: Using EGL config: %d", i);
platform.config = configs[i];
found = 1;
break;
}
}
RL_FREE(configs);
if (!found)
{
TRACELOG(LOG_WARNING, "DISPLAY: Failed to find a suitable EGL config");
return -1;
}
eglBindAPI(EGL_OPENGL_ES_API);
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 -1;
}
platform.surface = EGL_NO_SURFACE;
if ((eglClientExtensions != NULL) && (strstr(eglClientExtensions, "EGL_EXT_platform_base") != NULL))
{
PFNEGLCREATEPLATFORMWINDOWSURFACEEXTPROC eglCreatePlatformWindowSurfaceEXT = (PFNEGLCREATEPLATFORMWINDOWSURFACEEXTPROC)eglGetProcAddress("eglCreatePlatformWindowSurfaceEXT");
if (eglCreatePlatformWindowSurfaceEXT != NULL) platform.surface = eglCreatePlatformWindowSurfaceEXT(platform.device, platform.config, platform.gbmSurface, NULL);
}
if (platform.surface == EGL_NO_SURFACE)
{
platform.surface = eglCreateWindowSurface(platform.device, platform.config, (EGLNativeWindowType)platform.gbmSurface, NULL);
}
if (platform.surface == EGL_NO_SURFACE)
{
TRACELOG(LOG_WARNING, "DISPLAY: Failed to create EGL window surface: 0x%04x", eglGetError());
return -1;
}
SetupFramebuffer(CORE.Window.display.width, CORE.Window.display.height);
EGLBoolean result = eglMakeCurrent(platform.device, platform.surface, platform.surface, platform.context);
if (result != EGL_FALSE)
{
CORE.Window.ready = true;
CORE.Window.render.width = CORE.Window.screen.width;
CORE.Window.render.height = CORE.Window.screen.height;
CORE.Window.currentFbo.width = CORE.Window.render.width;
CORE.Window.currentFbo.height = CORE.Window.render.height;
}
else
{
TRACELOG(LOG_FATAL, "PLATFORM: Failed to initialize graphics device");
return -1;
}
rlLoadExtensions(eglGetProcAddress);
#else
SetupFramebuffer(CORE.Window.display.width, CORE.Window.display.height);
CORE.Window.ready = true;
CORE.Window.render.width = CORE.Window.screen.width;
CORE.Window.render.height = CORE.Window.screen.height;
CORE.Window.currentFbo.width = CORE.Window.render.width;
CORE.Window.currentFbo.height = CORE.Window.render.height;
#endif
TRACELOG(LOG_INFO, "DISPLAY: Device initialized successfully %s",
FLAG_IS_SET(CORE.Window.flags, FLAG_WINDOW_HIGHDPI)? "(HighDPI)" : "");
TRACELOG(LOG_INFO, " > Display size: %i x %i", CORE.Window.display.width, CORE.Window.display.height);
TRACELOG(LOG_INFO, " > Screen size: %i x %i", CORE.Window.screen.width, CORE.Window.screen.height);
TRACELOG(LOG_INFO, " > Render size: %i x %i", CORE.Window.render.width, CORE.Window.render.height);
TRACELOG(LOG_INFO, " > Viewport offsets: %i, %i", CORE.Window.renderOffset.x, CORE.Window.renderOffset.y);
if (FLAG_IS_SET(CORE.Window.flags, FLAG_WINDOW_MINIMIZED)) MinimizeWindow();
if (!CORE.Window.ready)
{
TRACELOG(LOG_FATAL, "PLATFORM: Failed to initialize graphic device");
return -1;
}
else SetWindowPosition(GetMonitorWidth(GetCurrentMonitor())/2 - CORE.Window.screen.width/2, GetMonitorHeight(GetCurrentMonitor())/2 - CORE.Window.screen.height/2);
FLAG_CLEAR(CORE.Window.flags, FLAG_WINDOW_HIDDEN); FLAG_CLEAR(CORE.Window.flags, FLAG_WINDOW_MINIMIZED); FLAG_SET(CORE.Window.flags, FLAG_WINDOW_MAXIMIZED); FLAG_CLEAR(CORE.Window.flags, FLAG_WINDOW_UNFOCUSED);
InitTimer();
InitEvdevInput();
#if SUPPORT_SSH_KEYBOARD_RPI
InitKeyboard(); #endif
CORE.Storage.basePath = GetWorkingDirectory();
#if defined(SUPPORT_DRM_CACHE)
if (InitSwapScreenBuffer() == 0)
{
TRACELOG(LOG_INFO, "PLATFORM: DRM: Initialized successfully");
return 0;
}
else
{
TRACELOG(LOG_INFO, "PLATFORM: DRM: Initialized failed");
return -1;
}
#else
TRACELOG(LOG_INFO, "PLATFORM: DRM: Initialized successfully");
return 0;
#endif
}
void ClosePlatform(void)
{
if (platform.prevFB)
{
drmModeRmFB(platform.fd, platform.prevFB);
platform.prevFB = 0;
}
#if !defined(GRAPHICS_API_OPENGL_SOFTWARE)
if (platform.prevBO)
{
gbm_surface_release_buffer(platform.gbmSurface, platform.prevBO);
platform.prevBO = NULL;
}
if (platform.gbmSurface)
{
gbm_surface_destroy(platform.gbmSurface);
platform.gbmSurface = NULL;
}
if (platform.gbmDevice)
{
gbm_device_destroy(platform.gbmDevice);
platform.gbmDevice = NULL;
}
#endif
if (platform.crtc)
{
if (platform.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;
}
drmModeFreeCrtc(platform.crtc);
platform.crtc = NULL;
}
if (platform.fd != -1)
{
close(platform.fd);
platform.fd = -1;
}
#if !defined(GRAPHICS_API_OPENGL_SOFTWARE)
if (platform.device != EGL_NO_DISPLAY)
{
if (platform.surface != EGL_NO_SURFACE)
{
eglDestroySurface(platform.device, platform.surface);
platform.surface = EGL_NO_SURFACE;
}
if (platform.context != EGL_NO_CONTEXT)
{
eglDestroyContext(platform.device, platform.context);
platform.context = EGL_NO_CONTEXT;
}
eglTerminate(platform.device);
platform.device = EGL_NO_DISPLAY;
}
#endif
CORE.Window.shouldClose = true;
if (platform.mouseFd != -1)
{
close(platform.mouseFd);
platform.mouseFd = -1;
}
for (int i = 0; i < platform.gamepadCount; i++)
{
close(platform.gamepadStreamFd[i]);
platform.gamepadStreamFd[i] = -1;
}
if (platform.keyboardFd != -1)
{
close(platform.keyboardFd);
platform.keyboardFd = -1;
}
}
#if SUPPORT_SSH_KEYBOARD_RPI
static void InitKeyboard(void)
{
tcgetattr(STDIN_FILENO, &platform.defaultSettings);
struct termios keyboardNewSettings = { 0 };
keyboardNewSettings = platform.defaultSettings;
FLAG_CLEAR(keyboardNewSettings.c_lflag, ICANON | ECHO | ISIG);
keyboardNewSettings.c_cc[VMIN] = 1;
keyboardNewSettings.c_cc[VTIME] = 0;
tcsetattr(STDIN_FILENO, TCSANOW, &keyboardNewSettings);
platform.defaultFileFlags = fcntl(STDIN_FILENO, F_GETFL, 0); fcntl(STDIN_FILENO, F_SETFL, platform.defaultFileFlags | O_NONBLOCK);
int result = ioctl(STDIN_FILENO, KDGKBMODE, &platform.defaultKeyboardMode);
if (result < 0) TRACELOG(LOG_WARNING, "DRM: Failed to change keyboard mode, an SSH keyboard is probably used");
else
{
ioctl(STDIN_FILENO, KDSKBMODE, K_XLATE); }
atexit(RestoreKeyboard);
}
static void RestoreKeyboard(void)
{
tcsetattr(STDIN_FILENO, TCSANOW, &platform.defaultSettings);
fcntl(STDIN_FILENO, F_SETFL, platform.defaultFileFlags);
ioctl(STDIN_FILENO, KDSKBMODE, platform.defaultKeyboardMode);
}
static void ProcessKeyboard(void)
{
#define MAX_KEYBUFFER_SIZE 32
int bufferByteCount = 0; char keysBuffer[MAX_KEYBUFFER_SIZE] = { 0 };
bufferByteCount = read(STDIN_FILENO, keysBuffer, MAX_KEYBUFFER_SIZE);
for (int i = 0; i < MAX_KEYBOARD_KEYS; i++)
{
CORE.Input.Keyboard.currentKeyState[i] = 0;
CORE.Input.Keyboard.keyRepeatInFrame[i] = 0;
}
for (int i = 0; i < bufferByteCount; i++)
{
if (keysBuffer[i] == 0x1b)
{
if (bufferByteCount == 1) CORE.Input.Keyboard.currentKeyState[CORE.Input.Keyboard.exitKey] = 1;
else
{
if (keysBuffer[i + 1] == 0x5b) {
if ((keysBuffer[i + 2] == 0x5b) || (keysBuffer[i + 2] == 0x31) || (keysBuffer[i + 2] == 0x32))
{
switch (keysBuffer[i + 3])
{
case 0x41: CORE.Input.Keyboard.currentKeyState[290] = 1; break; case 0x42: CORE.Input.Keyboard.currentKeyState[291] = 1; break; case 0x43: CORE.Input.Keyboard.currentKeyState[292] = 1; break; case 0x44: CORE.Input.Keyboard.currentKeyState[293] = 1; break; case 0x45: CORE.Input.Keyboard.currentKeyState[294] = 1; break; case 0x37: CORE.Input.Keyboard.currentKeyState[295] = 1; break; case 0x38: CORE.Input.Keyboard.currentKeyState[296] = 1; break; case 0x39: CORE.Input.Keyboard.currentKeyState[297] = 1; break; case 0x30: CORE.Input.Keyboard.currentKeyState[298] = 1; break; case 0x31: CORE.Input.Keyboard.currentKeyState[299] = 1; break; case 0x33: CORE.Input.Keyboard.currentKeyState[300] = 1; break; case 0x34: CORE.Input.Keyboard.currentKeyState[301] = 1; break; default: break;
}
if (keysBuffer[i + 2] == 0x5b) i += 4;
else if ((keysBuffer[i + 2] == 0x31) || (keysBuffer[i + 2] == 0x32)) i += 5;
}
else
{
switch (keysBuffer[i + 2])
{
case 0x41: CORE.Input.Keyboard.currentKeyState[265] = 1; break; case 0x42: CORE.Input.Keyboard.currentKeyState[264] = 1; break; case 0x43: CORE.Input.Keyboard.currentKeyState[262] = 1; break; case 0x44: CORE.Input.Keyboard.currentKeyState[263] = 1; break; default: break;
}
i += 3; }
}
}
}
else if (keysBuffer[i] == 0x0a) {
CORE.Input.Keyboard.currentKeyState[257] = 1;
CORE.Input.Keyboard.keyPressedQueue[CORE.Input.Keyboard.keyPressedQueueCount] = 257; CORE.Input.Keyboard.keyPressedQueueCount++;
}
else if (keysBuffer[i] == 0x7f) {
CORE.Input.Keyboard.currentKeyState[259] = 1;
CORE.Input.Keyboard.keyPressedQueue[CORE.Input.Keyboard.keyPressedQueueCount] = 259; CORE.Input.Keyboard.keyPressedQueueCount++;
}
else
{
if ((keysBuffer[i] >= 97) && (keysBuffer[i] <= 122))
{
CORE.Input.Keyboard.currentKeyState[(int)keysBuffer[i] - 32] = 1;
}
else CORE.Input.Keyboard.currentKeyState[(int)keysBuffer[i]] = 1;
CORE.Input.Keyboard.keyPressedQueue[CORE.Input.Keyboard.keyPressedQueueCount] = keysBuffer[i]; CORE.Input.Keyboard.keyPressedQueueCount++;
}
}
}
#endif
static void InitEvdevInput(void)
{
char path[MAX_FILEPATH_LENGTH] = { 0 };
DIR *directory = NULL;
struct dirent *entity = NULL;
platform.keyboardFd = -1;
platform.mouseFd = -1;
for (int i = 0; i < MAX_TOUCH_POINTS; i++)
{
CORE.Input.Touch.position[i].x = -1;
CORE.Input.Touch.position[i].y = -1;
platform.touchActive[i] = false;
platform.touchPosition[i].x = -1;
platform.touchPosition[i].y = -1;
platform.touchId[i] = -1;
}
platform.touchSlot = 0;
for (int i = 0; i < MAX_KEYBOARD_KEYS; i++)
{
CORE.Input.Keyboard.currentKeyState[i] = 0;
CORE.Input.Keyboard.keyRepeatInFrame[i] = 0;
}
directory = opendir(DEFAULT_EVDEV_PATH);
if (directory)
{
while ((entity = readdir(directory)) != NULL)
{
if ((strncmp("event", entity->d_name, strlen("event")) == 0) || (strncmp("mouse", entity->d_name, strlen("mouse")) == 0)) {
snprintf(path, MAX_FILEPATH_LENGTH, "%s%s", DEFAULT_EVDEV_PATH, entity->d_name);
ConfigureEvdevDevice(path); }
}
closedir(directory);
}
else TRACELOG(LOG_WARNING, "INPUT: Failed to open linux event directory: %s", DEFAULT_EVDEV_PATH);
}
static void ConfigureEvdevDevice(char *device)
{
#define BITS_PER_LONG (8*sizeof(long))
#define NBITS(x) ((((x) - 1)/BITS_PER_LONG) + 1)
#define OFF(x) ((x)%BITS_PER_LONG)
#define BIT(x) (1UL<<OFF(x))
#define LONG(x) ((x)/BITS_PER_LONG)
#define TEST_BIT(array, bit) ((array[LONG(bit)] >> OFF(bit)) & 1)
unsigned long evBits[NBITS(EV_MAX)] = { 0 };
unsigned long absBits[NBITS(ABS_MAX)] = { 0 };
unsigned long relBits[NBITS(REL_MAX)] = { 0 };
unsigned long keyBits[NBITS(KEY_MAX)] = { 0 };
int fd = open(device, O_RDONLY | O_NONBLOCK);
if (fd < 0)
{
TRACELOG(LOG_WARNING, "SYSTEM: Failed to open input device: %s", device);
return;
}
struct {
bool exist;
struct input_absinfo info;
} absinfo[ABS_CNT] = { 0 };
bool isKeyboard = false;
bool isMouse = false;
bool isTouch = false;
bool isGamepad = false;
int absAxisCount = 0;
ioctl(fd, EVIOCGBIT(0, sizeof(evBits)), evBits);
ioctl(fd, EVIOCGBIT(EV_KEY, sizeof(keyBits)), keyBits);
if (TEST_BIT(evBits, EV_ABS))
{
ioctl(fd, EVIOCGBIT(EV_ABS, sizeof(absBits)), absBits);
bool hasAbsXY = TEST_BIT(absBits, ABS_X) && TEST_BIT(absBits, ABS_Y);
if (hasAbsXY)
{
absAxisCount += 2;
absinfo[ABS_X].exist = true;
absinfo[ABS_Y].exist = true;
ioctl(fd, EVIOCGABS(ABS_X), &absinfo[ABS_X].info);
ioctl(fd, EVIOCGABS(ABS_Y), &absinfo[ABS_Y].info);
}
if (hasAbsXY &&
(TEST_BIT(keyBits, BTN_STYLUS) ||
TEST_BIT(keyBits, BTN_TOOL_PEN) ||
TEST_BIT(keyBits, BTN_TOOL_FINGER) ||
TEST_BIT(keyBits, BTN_TOUCH))) isTouch = true;
else if (hasAbsXY && TEST_BIT(keyBits, BTN_MOUSE)) isMouse = true;
else
{
for (int axis = (hasAbsXY? ABS_Z : ABS_X); axis < ABS_PRESSURE; axis++)
{
if (TEST_BIT(absBits, axis))
{
absinfo[axis].exist = true;
isGamepad = true;
absAxisCount++;
ioctl(fd, EVIOCGABS(axis), &absinfo[axis].info);
}
}
}
if (TEST_BIT(absBits, ABS_MT_POSITION_X) &&
TEST_BIT(absBits, ABS_MT_POSITION_Y)) isTouch = true;
}
if (TEST_BIT(evBits, EV_REL))
{
ioctl(fd, EVIOCGBIT(EV_REL, sizeof(relBits)), relBits);
if (!isTouch &&
!isGamepad &&
TEST_BIT(relBits, REL_X) &&
TEST_BIT(relBits, REL_Y) &&
TEST_BIT(keyBits, BTN_MOUSE)) isMouse = true;
}
if (TEST_BIT(evBits, EV_KEY))
{
const unsigned long mask = 0xFFFFFFFE;
if ((keyBits[0] & mask) == mask) isKeyboard = true;
else
{
for (int button = BTN_JOYSTICK; button < BTN_DIGI; ++button)
{
if (TEST_BIT(keyBits, button)) isGamepad = true;
}
for (int button = BTN_TRIGGER_HAPPY1; button <= BTN_TRIGGER_HAPPY40; button++)
{
if (TEST_BIT(keyBits, button)) isGamepad = true;
}
}
}
const char *deviceKindStr = "unknown";
if (isMouse || isTouch)
{
bool prioritize = false;
if (platform.mouseFd == -1) prioritize = true;
else if (isTouch && !platform.mouseIsTouch) prioritize = true;
else if (isTouch && platform.mouseIsTouch) prioritize = true;
else if (!isTouch && !platform.mouseIsTouch) prioritize = true;
else prioritize = false;
if (prioritize)
{
deviceKindStr = isTouch? "touchscreen" : "mouse";
if (platform.mouseFd != -1)
{
TRACELOG(LOG_INFO, "INPUT: Overwriting previous input device with new %s", deviceKindStr);
close(platform.mouseFd);
}
platform.mouseFd = fd;
platform.mouseIsTouch = isTouch;
if (absAxisCount > 0)
{
platform.absRange.x = absinfo[ABS_X].info.minimum;
platform.absRange.width = absinfo[ABS_X].info.maximum - absinfo[ABS_X].info.minimum;
platform.absRange.y = absinfo[ABS_Y].info.minimum;
platform.absRange.height = absinfo[ABS_Y].info.maximum - absinfo[ABS_Y].info.minimum;
}
TRACELOG(LOG_INFO, "INPUT: Initialized input device %s as %s", device, deviceKindStr);
}
else
{
TRACELOG(LOG_INFO, "INPUT: Ignoring device %s (keeping higher priority %s device)", device, platform.mouseIsTouch ? "touchscreen" : "mouse");
close(fd);
return;
}
}
else if (isGamepad && !isMouse && !isKeyboard && (platform.gamepadCount < MAX_GAMEPADS))
{
deviceKindStr = "gamepad";
int index = platform.gamepadCount++;
platform.gamepadStreamFd[index] = fd;
CORE.Input.Gamepad.ready[index] = true;
ioctl(platform.gamepadStreamFd[index], EVIOCGNAME(64), &CORE.Input.Gamepad.name[index]);
CORE.Input.Gamepad.axisCount[index] = absAxisCount;
if (absAxisCount > 0)
{
int axisIndex = 0;
for (int axis = ABS_X; axis < ABS_PRESSURE; axis++)
{
if (absinfo[axis].exist)
{
platform.gamepadAbsAxisRange[index][axisIndex][0] = absinfo[axisIndex].info.minimum;
platform.gamepadAbsAxisRange[index][axisIndex][1] = absinfo[axisIndex].info.maximum - absinfo[axisIndex].info.minimum;
platform.gamepadAbsAxisMap[index][axis] = axisIndex;
axisIndex++;
}
}
}
}
else if (isKeyboard && (platform.keyboardFd == -1))
{
deviceKindStr = "keyboard";
platform.keyboardFd = fd;
}
else
{
close(fd);
return;
}
TRACELOG(LOG_INFO, "INPUT: Initialized input device %s as %s", device, deviceKindStr);
}
static void PollKeyboardEvents(void)
{
int fd = platform.keyboardFd;
if (fd == -1) return;
struct input_event event = { 0 };
int keycode = -1;
while (read(fd, &event, sizeof(event)) == (int)sizeof(event))
{
if (event.type != EV_KEY) continue;
#if SUPPORT_SSH_KEYBOARD_RPI
platform.eventKeyboardMode = true;
#endif
if ((event.code >= 1) && (event.code <= 255))
{
keycode = linuxToRaylibMap[event.code];
if ((keycode > 0) && (keycode < MAX_KEYBOARD_KEYS))
{
CORE.Input.Keyboard.currentKeyState[keycode] = (event.value >= 1);
CORE.Input.Keyboard.keyRepeatInFrame[keycode] = (event.value == 2);
if (event.value == 1)
{
if (CORE.Input.Keyboard.keyPressedQueueCount < MAX_CHAR_PRESSED_QUEUE)
{
CORE.Input.Keyboard.keyPressedQueue[CORE.Input.Keyboard.keyPressedQueueCount] = keycode;
CORE.Input.Keyboard.keyPressedQueueCount++;
}
if (CORE.Input.Keyboard.charPressedQueueCount < MAX_CHAR_PRESSED_QUEUE)
{
CORE.Input.Keyboard.charPressedQueue[CORE.Input.Keyboard.charPressedQueueCount] = evkeyToUnicodeLUT[event.code];
CORE.Input.Keyboard.charPressedQueueCount++;
}
}
TRACELOG(LOG_DEBUG, "INPUT: KEY_%s Keycode(linux): %4i KeyCode(raylib): %4i", (event.value == 0)? "UP " : "DOWN", event.code, keycode);
}
}
}
}
static void PollGamepadEvents(void)
{
struct input_event event = { 0 };
for (int i = 0; i < platform.gamepadCount; i++)
{
if (!CORE.Input.Gamepad.ready[i]) continue;
for (int k = 0; k < MAX_GAMEPAD_BUTTONS; k++) CORE.Input.Gamepad.previousButtonState[i][k] = CORE.Input.Gamepad.currentButtonState[i][k];
while (read(platform.gamepadStreamFd[i], &event, sizeof(event)) == (int)sizeof(event))
{
if (event.type == EV_KEY)
{
if (event.code < KEYMAP_SIZE)
{
short keycode = linuxToRaylibMap[event.code];
TRACELOG(LOG_DEBUG, "INPUT: Gamepad %2i: KEY_%s Keycode(linux): %4i Keycode(raylib): %4i", i, (event.value == 0)? "UP" : "DOWN", event.code, keycode);
if ((keycode != 0) && (keycode < MAX_GAMEPAD_BUTTONS))
{
CORE.Input.Gamepad.currentButtonState[i][keycode] = event.value;
CORE.Input.Gamepad.lastButtonPressed = (event.value == 1)? keycode : GAMEPAD_BUTTON_UNKNOWN;
}
}
}
else if (event.type == EV_ABS)
{
if (event.code < ABS_CNT)
{
int axisRaylib = platform.gamepadAbsAxisMap[i][event.code];
TRACELOG(LOG_DEBUG, "INPUT: Gamepad %2i: Axis: %2i Value: %i", i, axisRaylib, event.value);
if (axisRaylib < MAX_GAMEPAD_AXES)
{
int min = platform.gamepadAbsAxisRange[i][event.code][0];
int range = platform.gamepadAbsAxisRange[i][event.code][1];
CORE.Input.Gamepad.axisState[i][axisRaylib] = (2*(float)(event.value - min)/range) - 1;
}
}
}
}
}
}
static void PollMouseEvents(void)
{
int fd = platform.mouseFd;
if (fd == -1) return;
struct input_event event = { 0 };
int touchAction = -1; static bool isMultitouch = false;
while (read(fd, &event, sizeof(event)) == (int)sizeof(event))
{
if (event.type == EV_REL)
{
if (event.code == REL_X)
{
if (platform.cursorRelative)
{
CORE.Input.Mouse.currentPosition.x = event.value;
CORE.Input.Mouse.previousPosition.x = 0.0f;
}
else CORE.Input.Mouse.currentPosition.x += event.value;
touchAction = 2; }
if (event.code == REL_Y)
{
if (platform.cursorRelative)
{
CORE.Input.Mouse.currentPosition.y = event.value;
CORE.Input.Mouse.previousPosition.y = 0.0f;
}
else CORE.Input.Mouse.currentPosition.y += event.value;
touchAction = 2; }
if (event.code == REL_WHEEL) platform.eventWheelMove.y += event.value;
}
if (event.type == EV_ABS)
{
if (event.code == ABS_X)
{
CORE.Input.Mouse.currentPosition.x = (event.value - platform.absRange.x)*CORE.Window.screen.width/platform.absRange.width;
if (platform.touchActive[0] && !isMultitouch)
{
platform.touchPosition[0].x = (event.value - platform.absRange.x)*CORE.Window.screen.width/platform.absRange.width;
if (touchAction == -1) touchAction = 2; }
}
if (event.code == ABS_Y)
{
CORE.Input.Mouse.currentPosition.y = (event.value - platform.absRange.y)*CORE.Window.screen.height/platform.absRange.height;
if (platform.touchActive[0] && !isMultitouch)
{
platform.touchPosition[0].y = (event.value - platform.absRange.y)*CORE.Window.screen.height/platform.absRange.height;
if (touchAction == -1) touchAction = 2; }
}
if (event.code == ABS_MT_SLOT)
{
platform.touchSlot = event.value;
isMultitouch = true;
}
if (event.code == ABS_MT_POSITION_X)
{
isMultitouch = true;
if (platform.touchSlot < MAX_TOUCH_POINTS)
{
platform.touchPosition[platform.touchSlot].x = (event.value - platform.absRange.x)*CORE.Window.screen.width/platform.absRange.width;
if (platform.touchActive[platform.touchSlot] && touchAction == -1) touchAction = 2; }
}
if (event.code == ABS_MT_POSITION_Y)
{
if (platform.touchSlot < MAX_TOUCH_POINTS)
{
platform.touchPosition[platform.touchSlot].y = (event.value - platform.absRange.y)*CORE.Window.screen.height/platform.absRange.height;
if (platform.touchActive[platform.touchSlot] && touchAction == -1) touchAction = 2; }
}
if (event.code == ABS_MT_TRACKING_ID)
{
if (platform.touchSlot < MAX_TOUCH_POINTS)
{
if (event.value >= 0)
{
platform.touchActive[platform.touchSlot] = true;
platform.touchId[platform.touchSlot] = event.value;
touchAction = 1; }
else
{
platform.touchActive[platform.touchSlot] = false;
platform.touchPosition[platform.touchSlot].x = -1;
platform.touchPosition[platform.touchSlot].y = -1;
platform.touchId[platform.touchSlot] = -1;
if (touchAction != 1) touchAction = 0; }
}
}
#ifndef ABS_MT_PRESSURE
#define ABS_MT_PRESSURE 0x3a
#endif
if (event.code == ABS_MT_PRESSURE)
{
if (platform.touchSlot < MAX_TOUCH_POINTS)
{
if (event.value <= 0) {
platform.touchActive[platform.touchSlot] = false;
platform.touchPosition[platform.touchSlot].x = -1;
platform.touchPosition[platform.touchSlot].y = -1;
platform.touchId[platform.touchSlot] = -1;
if (touchAction != 1) touchAction = 0; }
}
}
if (event.code == ABS_PRESSURE)
{
int previousMouseLeftButtonState = platform.currentButtonStateEvdev[MOUSE_BUTTON_LEFT];
if (!event.value && previousMouseLeftButtonState)
{
platform.currentButtonStateEvdev[MOUSE_BUTTON_LEFT] = 0;
if (touchAction != 1) touchAction = 0; }
if (event.value && !previousMouseLeftButtonState)
{
platform.currentButtonStateEvdev[MOUSE_BUTTON_LEFT] = 1;
touchAction = 1; }
}
}
if (event.type == EV_KEY)
{
if ((event.code == BTN_TOUCH) || (event.code == BTN_LEFT))
{
platform.currentButtonStateEvdev[MOUSE_BUTTON_LEFT] = event.value;
if (event.value > 0)
{
bool activateSlot0 = false;
if (event.code == BTN_LEFT) activateSlot0 = true; else if (event.code == BTN_TOUCH)
{
bool anyActive = false;
for (int i = 0; i < MAX_TOUCH_POINTS; i++)
{
if (platform.touchActive[i]) { anyActive = true; break; }
}
if (!anyActive) activateSlot0 = true;
}
if (activateSlot0)
{
platform.touchActive[0] = true;
platform.touchId[0] = 0;
}
touchAction = 1; }
else
{
if (event.code == BTN_LEFT)
{
platform.touchActive[0] = false;
platform.touchPosition[0].x = -1;
platform.touchPosition[0].y = -1;
}
else if (event.code == BTN_TOUCH) platform.touchSlot = 0;
touchAction = 0; }
}
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 (!CORE.Input.Mouse.cursorLocked)
{
if (CORE.Input.Mouse.currentPosition.x < 0) CORE.Input.Mouse.currentPosition.x = 0;
if (CORE.Input.Mouse.currentPosition.x > CORE.Window.screen.width/CORE.Input.Mouse.scale.x)
CORE.Input.Mouse.currentPosition.x = CORE.Window.screen.width/CORE.Input.Mouse.scale.x;
if (CORE.Input.Mouse.currentPosition.y < 0) CORE.Input.Mouse.currentPosition.y = 0;
if (CORE.Input.Mouse.currentPosition.y > CORE.Window.screen.height/CORE.Input.Mouse.scale.y)
CORE.Input.Mouse.currentPosition.y = CORE.Window.screen.height/CORE.Input.Mouse.scale.y;
}
int k = 0;
for (int i = 0; i < MAX_TOUCH_POINTS; i++)
{
if (platform.touchActive[i])
{
CORE.Input.Touch.position[k] = platform.touchPosition[i];
CORE.Input.Touch.pointId[k] = platform.touchId[i];
k++;
}
}
CORE.Input.Touch.pointCount = k;
for (int i = k; i < MAX_TOUCH_POINTS; i++)
{
CORE.Input.Touch.position[i].x = -1;
CORE.Input.Touch.position[i].y = -1;
CORE.Input.Touch.pointId[i] = -1;
}
#if SUPPORT_GESTURES_SYSTEM
if (touchAction > -1)
{
GestureEvent gestureEvent = { 0 };
gestureEvent.touchAction = touchAction;
gestureEvent.pointCount = CORE.Input.Touch.pointCount;
for (int i = 0; i < MAX_TOUCH_POINTS; i++)
{
gestureEvent.pointId[i] = i;
gestureEvent.position[i] = CORE.Input.Touch.position[i];
}
ProcessGestureEvent(gestureEvent);
touchAction = -1;
}
#endif
}
}
static int FindMatchingConnectorMode(const drmModeConnector *connector, const drmModeModeInfo *mode)
{
if (NULL == connector) return -1;
if (NULL == mode) return -1;
#define BINCMP(a, b) memcmp((a), (b), (sizeof(a) < sizeof(b))? sizeof(a) : sizeof(b))
for (size_t i = 0; i < connector->count_modes; i++)
{
TRACELOG(LOG_TRACE, "DISPLAY: DRM mode: %d %ux%u@%u %s", i, connector->modes[i].hdisplay, connector->modes[i].vdisplay,
connector->modes[i].vrefresh, (FLAG_IS_SET(connector->modes[i].flags, DRM_MODE_FLAG_INTERLACE) > 0)? "interlaced" : "progressive");
if (0 == BINCMP(&platform.crtc->mode, &platform.connector->modes[i])) return i;
}
return -1;
#undef BINCMP
}
static int FindExactConnectorMode(const drmModeConnector *connector, uint width, uint height, uint fps, bool allowInterlaced)
{
TRACELOG(LOG_TRACE, "DISPLAY: Searching exact connector mode for %ux%u@%u, selecting an interlaced mode is allowed: %s", width, height, fps, allowInterlaced? "yes" : "no");
if (NULL == connector) return -1;
for (int i = 0; i < platform.connector->count_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, (FLAG_IS_SET(mode->flags, DRM_MODE_FLAG_INTERLACE) > 0)? "interlaced" : "progressive");
if ((FLAG_IS_SET(mode->flags, DRM_MODE_FLAG_INTERLACE) > 0) && !allowInterlaced) continue;
if ((mode->hdisplay == width) && (mode->vdisplay == height) && (mode->vrefresh == fps)) return i;
}
TRACELOG(LOG_TRACE, "DISPLAY: No DRM exact matching mode found");
return -1;
}
static int FindNearestConnectorMode(const drmModeConnector *connector, uint width, uint height, uint fps, bool allowInterlaced)
{
TRACELOG(LOG_TRACE, "DISPLAY: Searching nearest connector mode for %ux%u@%u, selecting an interlaced mode is allowed: %s", width, height, fps, allowInterlaced? "yes" : "no");
if (NULL == connector) return -1;
int nearestIndex = -1;
int minUnusedPixels = INT_MAX;
int minFpsDiff = INT_MAX;
for (int i = 0; i < platform.connector->count_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,
(FLAG_IS_SET(mode->flags, DRM_MODE_FLAG_INTERLACE) > 0)? "interlaced" : "progressive");
if ((mode->hdisplay < width) || (mode->vdisplay < height))
{
TRACELOG(LOG_TRACE, "DISPLAY: DRM mode is too small");
continue;
}
if ((FLAG_IS_SET(mode->flags, DRM_MODE_FLAG_INTERLACE) > 0) && !allowInterlaced)
{
TRACELOG(LOG_TRACE, "DISPLAY: DRM shouldn't choose an interlaced mode");
continue;
}
const int unusedPixels = (mode->hdisplay - width)*(mode->vdisplay - height);
const int fpsDiff = mode->vrefresh - fps;
if ((unusedPixels < minUnusedPixels) ||
((unusedPixels == minUnusedPixels) && (abs(fpsDiff) < abs(minFpsDiff))) ||
((unusedPixels == minUnusedPixels) && (abs(fpsDiff) == abs(minFpsDiff)) && (fpsDiff > 0)))
{
nearestIndex = i;
minUnusedPixels = unusedPixels;
minFpsDiff = fpsDiff;
}
}
return nearestIndex;
}
static void SetupFramebuffer(int width, int height)
{
if ((CORE.Window.screen.width > CORE.Window.display.width) || (CORE.Window.screen.height > CORE.Window.display.height))
{
TRACELOG(LOG_WARNING, "DISPLAY: Downscaling required: Screen size (%ix%i) is bigger than display size (%ix%i)", CORE.Window.screen.width, CORE.Window.screen.height, CORE.Window.display.width, CORE.Window.display.height);
float widthRatio = (float)CORE.Window.display.width/(float)CORE.Window.screen.width;
float heightRatio = (float)CORE.Window.display.height/(float)CORE.Window.screen.height;
if (widthRatio <= heightRatio)
{
CORE.Window.render.width = CORE.Window.display.width;
CORE.Window.render.height = (int)round((float)CORE.Window.screen.height*widthRatio);
CORE.Window.renderOffset.x = 0;
CORE.Window.renderOffset.y = (CORE.Window.display.height - CORE.Window.render.height);
}
else
{
CORE.Window.render.width = (int)round((float)CORE.Window.screen.width*heightRatio);
CORE.Window.render.height = CORE.Window.display.height;
CORE.Window.renderOffset.x = (CORE.Window.display.width - CORE.Window.render.width);
CORE.Window.renderOffset.y = 0;
}
float scaleRatio = (float)CORE.Window.render.width/(float)CORE.Window.screen.width;
CORE.Window.screenScale = MatrixScale(scaleRatio, scaleRatio, 1.0f);
CORE.Window.render.width = CORE.Window.display.width;
CORE.Window.render.height = CORE.Window.display.height;
TRACELOG(LOG_WARNING, "DISPLAY: Downscale matrix generated, content will be rendered at (%ix%i)", CORE.Window.render.width, CORE.Window.render.height);
}
else if ((CORE.Window.screen.width < CORE.Window.display.width) || (CORE.Window.screen.height < CORE.Window.display.height))
{
TRACELOG(LOG_INFO, "DISPLAY: Upscaling required: Screen size (%ix%i) smaller than display size (%ix%i)", CORE.Window.screen.width, CORE.Window.screen.height, CORE.Window.display.width, CORE.Window.display.height);
if ((CORE.Window.screen.width == 0) || (CORE.Window.screen.height == 0))
{
CORE.Window.screen.width = CORE.Window.display.width;
CORE.Window.screen.height = CORE.Window.display.height;
}
float displayRatio = (float)CORE.Window.display.width/(float)CORE.Window.display.height;
float screenRatio = (float)CORE.Window.screen.width/(float)CORE.Window.screen.height;
if (displayRatio <= screenRatio)
{
CORE.Window.render.width = CORE.Window.screen.width;
CORE.Window.render.height = (int)round((float)CORE.Window.screen.width/displayRatio);
CORE.Window.renderOffset.x = 0;
CORE.Window.renderOffset.y = (CORE.Window.render.height - CORE.Window.screen.height);
}
else
{
CORE.Window.render.width = (int)round((float)CORE.Window.screen.height*displayRatio);
CORE.Window.render.height = CORE.Window.screen.height;
CORE.Window.renderOffset.x = (CORE.Window.render.width - CORE.Window.screen.width);
CORE.Window.renderOffset.y = 0;
}
}
else
{
CORE.Window.render.width = CORE.Window.screen.width;
CORE.Window.render.height = CORE.Window.screen.height;
CORE.Window.renderOffset.x = 0;
CORE.Window.renderOffset.y = 0;
}
}