Debian Codegraph @

src/platforms/rcore_drm.c

raw symbols SCIP
1 /**********************************************************************************************
2 *
3 * rcore_drm - Functions to manage window, graphics device and inputs
4 *
5 * PLATFORM: DRM
6 * - Raspberry Pi 0-5 (DRM/KMS)
7 * - Linux DRM subsystem (KMS mode)
8 *
9 * LIMITATIONS:
10 * - Most of the window/monitor functions are not implemented (not required)
11 *
12 * POSSIBLE IMPROVEMENTS:
13 * - Improvement 01
14 * - Improvement 02
15 *
16 * CONFIGURATION:
17 * #define SUPPORT_SSH_KEYBOARD_RPI (Raspberry Pi only)
18 * Reconfigure standard input to receive key inputs, works with SSH connection
19 * WARNING: Reconfiguring standard input could lead to undesired effects, like breaking other
20 * running processes orblocking the device if not restored properly. Use with care
21 *
22 * DEPENDENCIES:
23 * - DRM and GLM: System libraries for display initialization and configuration
24 * - gestures: Gestures system for touch-ready devices (or simulated from mouse inputs)
25 *
26 *
27 * LICENSE: zlib/libpng
28 *
29 * Copyright (c) 2013-2026 Ramon Santamaria (@raysan5) and contributors
30 *
31 * This software is provided "as-is", without any express or implied warranty. In no event
32 * will the authors be held liable for any damages arising from the use of this software.
33 *
34 * Permission is granted to anyone to use this software for any purpose, including commercial
35 * applications, and to alter it and redistribute it freely, subject to the following restrictions:
36 *
37 * 1. The origin of this software must not be misrepresented; you must not claim that you
38 * wrote the original software. If you use this software in a product, an acknowledgment
39 * in the product documentation would be appreciated but is not required.
40 *
41 * 2. Altered source versions must be plainly marked as such, and must not be misrepresented
42 * as being the original software.
43 *
44 * 3. This notice may not be removed or altered from any source distribution.
45 *
46 **********************************************************************************************/
47
48 #include <fcntl.h> // POSIX file control definitions - open(), creat(), fcntl()
49 #include <unistd.h> // POSIX standard function definitions - read(), close(), STDIN_FILENO
50 #include <termios.h> // POSIX terminal control definitions - tcgetattr(), tcsetattr()
51 #include <pthread.h> // POSIX threads management (inputs reading)
52 #include <dirent.h> // POSIX directory browsing
53 #include <limits.h> // INT_MAX
54
55 #include <sys/ioctl.h> // Required for: ioctl() - UNIX System call for device-specific input/output operations
56 #include <linux/kd.h> // Linux: KDSKBMODE, K_MEDIUMRAM constants definition
57 #include <linux/input.h> // Linux: Keycodes constants definition (KEY_A, ...)
58 #include <linux/joystick.h> // Linux: Joystick support library
59
60 // WARNING: Both 'linux/input.h' and 'raylib.h' define KEY_F12
61 // To avoid conflict with the capturing code in rcore.c, undefine the macro KEY_F12,
62 // so the enum KEY_F12 from raylib is used
63 #undef KEY_F12
64
65 #include <xf86drm.h> // Direct Rendering Manager user-level library interface
66 #include <xf86drmMode.h> // Direct Rendering Manager mode setting (KMS) interface
67
68 #if !defined(GRAPHICS_API_OPENGL_SOFTWARE)
69 #include <gbm.h> // Generic Buffer Management (native platform for EGL on DRM)
70 #include "EGL/egl.h" // Native platform windowing system interface
71 #include "EGL/eglext.h" // EGL extensions
72 #else
73 #include <sys/mman.h> // For mmap when copying to the dumb buffer
74 #include <errno.h> // For the conversion of certain error messages
75 #endif
76
77 // NOTE: DRM cache enables triple buffered DRM caching
78 #if defined(SUPPORT_DRM_CACHE)
79 #include <poll.h> // Required for: drmHandleEvent() poll
80 #include <errno.h> // Required for: EBUSY, EAGAIN
81
82 #define MAX_DRM_CACHED_BUFFERS 3
83 #endif
84
85 #ifndef EGL_OPENGL_ES3_BIT
86 #define EGL_OPENGL_ES3_BIT 0x40
87 #endif
88
89 #ifndef EGL_PLATFORM_GBM_KHR
90 #define EGL_PLATFORM_GBM_KHR 0x31D7
91 #endif
92
93 //----------------------------------------------------------------------------------
94 // Defines and Macros
95 //----------------------------------------------------------------------------------
96 #define USE_LAST_TOUCH_DEVICE // When multiple touchscreens are connected, only use the one with the highest event<N> number
97
98 #define DEFAULT_EVDEV_PATH "/dev/input/" // Path to the linux input events
99
100 // Actually biggest key is KEY_CNT but only mapping keys up to KEY_ALS_TOGGLE
101 #define KEYMAP_SIZE KEY_ALS_TOGGLE
102
103 //----------------------------------------------------------------------------------
104 // Types and Structures Definition
105 //----------------------------------------------------------------------------------
106 typedef struct {
107 // Display data
108 int fd; // File descriptor for /dev/dri/...
109 drmModeConnector *connector; // Direct Rendering Manager (DRM) mode connector
110 drmModeCrtc *crtc; // CRT Controller
111 int modeIndex; // Index of the used mode of connector->modes
112 uint32_t prevFB; // Previous DRM framebufer (during frame swapping)
113
114 #if !defined(GRAPHICS_API_OPENGL_SOFTWARE)
115 struct gbm_device *gbmDevice; // GBM device
116 struct gbm_surface *gbmSurface; // GBM surface
117 struct gbm_bo *prevBO; // Previous GBM buffer object (during frame swapping)
118 EGLDisplay device; // Native display device (physical screen connection)
119 EGLSurface surface; // Surface to draw on, framebuffers (connected to context)
120 EGLContext context; // Graphic context, mode in which drawing can be done
121 EGLConfig config; // Graphic config
122 #else
123 uint32_t prevDumbHandle; // Handle to the previous dumb buffer (during frame swapping)
124 #endif
125
126 // Keyboard data
127 int defaultKeyboardMode; // Default keyboard mode
128 bool eventKeyboardMode; // Keyboard in event mode
129 int defaultFileFlags; // Default IO file flags
130 struct termios defaultSettings; // Default keyboard settings
131 int keyboardFd; // File descriptor for the evdev keyboard
132
133 // Mouse data
134 Vector2 eventWheelMove; // Registers the event mouse wheel variation
135 // NOTE: currentButtonState[] can't be written directly due to multithreading, app could miss the update
136 char currentButtonStateEvdev[MAX_MOUSE_BUTTONS]; // Holds the new mouse state for the next polling event to grab
137 bool cursorRelative; // Relative cursor mode
138 int mouseFd; // File descriptor for the evdev mouse/touch/gestures
139 bool mouseIsTouch; // Check if the current mouse device is actually a touchscreen
140 Rectangle absRange; // Range of values for absolute pointing devices (touchscreens)
141 int touchSlot; // Hold the touch slot number of the currently being sent multitouch block
142 bool touchActive[MAX_TOUCH_POINTS]; // Track which touch points are currently active
143 Vector2 touchPosition[MAX_TOUCH_POINTS]; // Track touch positions for each slot
144 int touchId[MAX_TOUCH_POINTS]; // Track touch IDs for each slot
145
146 // Gamepad data
147 int gamepadStreamFd[MAX_GAMEPADS]; // Gamepad device file descriptor
148 int gamepadAbsAxisRange[MAX_GAMEPADS][MAX_GAMEPAD_AXES][2]; // [0] = min, [1] = range value of the axes
149 int gamepadAbsAxisMap[MAX_GAMEPADS][ABS_CNT]; // Maps the axes gamepads from the evdev api to a sequential one
150 int gamepadCount; // The number of gamepads registered
151 } PlatformData;
152
153 #if defined(SUPPORT_DRM_CACHE)
154 typedef struct {
155 struct gbm_bo *bo; // Graphics buffer object
156 uint32_t fbId; // DRM framebuffer ID
157 } FramebufferCache;
158
159 static FramebufferCache fbCache[MAX_DRM_CACHED_BUFFERS] = { 0 };
160 static volatile int fbCacheCount = 0;
161 static volatile bool pendingFlip = false;
162 static bool crtcSet = false;
163 #endif
164
165 //----------------------------------------------------------------------------------
166 // Global Variables Definition
167 //----------------------------------------------------------------------------------
168 extern CoreData CORE; // Global CORE state context
169
170 static PlatformData platform = { 0 }; // Platform specific data
171
172 //----------------------------------------------------------------------------------
173 // Global Variables Definition
174 //----------------------------------------------------------------------------------
175
176 // NOTE: The complete evdev EV_KEY list can be found at /usr/include/linux/input-event-codes.h
177 // TODO: Complete the LUT with all unicode decimal values
178 // TODO: Replace this with a keymap from the X11 to get the correct regional map for the keyboard:
179 // Currently non US keyboards will have the wrong mapping for some keys
180 // NOTE: Replacing this with the keymap from X11 would probably be useless, as people use the drm
181 // backend to *avoid* X11
182 static const int evkeyToUnicodeLUT[] = {
183 0, 27, 49, 50, 51, 52, 53, 54, 55, 56, 57, 48, 45, 61, 8, 0, 113, 119, 101, 114,
184 116, 121, 117, 105, 111, 112, 0, 0, 13, 0, 97, 115, 100, 102, 103, 104, 106, 107, 108, 59,
185 39, 96, 0, 92, 122, 120, 99, 118, 98, 110, 109, 44, 46, 47, 0, 0, 0, 32
186 // LUT currently incomplete, only mapped the most essential keys
187 };
188
189 // This is the map used to map any keycode returned from linux to a raylib code from 'raylib.h'
190 // NOTE: Use short here to save a little memory
191 static const short linuxToRaylibMap[KEYMAP_SIZE] = {
192 // Don't map with designated initialization,
193 // it will geenrate many naming conflicts
194 0, 256, 49, 50, 51, 52, 53, 54,
195 55, 56, 57, 48, 45, 61, 259, 258,
196 81, 87, 69, 82, 84, 89, 85, 73,
197 79, 80, 91, 93, 257, 341, 65, 83,
198 68, 70, 71, 72, 74, 75, 76, 59,
199 39, 96, 340, 92, 90, 88, 67, 86,
200 66, 78, 77, 44, 46, 47, 344, 332,
201 342, 32, 280, 290, 291, 292, 293, 294,
202 295, 296, 297, 298, 299, 282, 281, 327,
203 328, 329, 333, 324, 325, 326, 334, 321,
204 322, 323, 320, 330, 0, 85, 86, 300,
205 301, 89, 90, 91, 92, 93, 94, 95,
206 335, 345, 331, 283, 346, 101, 268, 265,
207 266, 263, 262, 269, 264, 267, 260, 261,
208 112, 113, 114, 115, 116, 117, 118, 119,
209 120, 121, 122, 123, 124, 125, 347, 127,
210 128, 129, 130, 131, 132, 133, 134, 135,
211 136, 137, 138, 139, 140, 141, 142, 143,
212 144, 145, 146, 147, 148, 149, 150, 151,
213 152, 153, 154, 155, 156, 157, 158, 159,
214 160, 161, 162, 163, 164, 165, 166, 167,
215 168, 169, 170, 171, 172, 173, 174, 175,
216 176, 177, 178, 179, 180, 181, 182, 183,
217 184, 185, 186, 187, 188, 189, 190, 191,
218 192, 193, 194, 0, 0, 0, 0, 0,
219 200, 201, 202, 203, 204, 205, 206, 207,
220 208, 209, 210, 211, 212, 213, 214, 215,
221 216, 217, 218, 219, 220, 221, 222, 223,
222 224, 225, 226, 227, 228, 229, 230, 231,
223 232, 233, 234, 235, 236, 237, 238, 239,
224 240, 241, 242, 243, 244, 245, 246, 247,
225 248, 0, 0, 0, 0, 0, 0, 0,
226
227 // Gamepads are mapped according to:
228 // REF: https://www.kernel.org/doc/html/next/input/gamepad.html
229 // Those mappings are standardized, but that doesn't mean people follow
230 // the standards, so this is more of an approximation
231 [BTN_DPAD_UP] = GAMEPAD_BUTTON_LEFT_FACE_UP,
232 [BTN_DPAD_RIGHT] = GAMEPAD_BUTTON_LEFT_FACE_RIGHT,
233 [BTN_DPAD_DOWN] = GAMEPAD_BUTTON_LEFT_FACE_DOWN,
234 [BTN_DPAD_LEFT] = GAMEPAD_BUTTON_LEFT_FACE_LEFT,
235 [BTN_Y] = GAMEPAD_BUTTON_RIGHT_FACE_UP,
236 [BTN_B] = GAMEPAD_BUTTON_RIGHT_FACE_RIGHT,
237 [BTN_A] = GAMEPAD_BUTTON_RIGHT_FACE_DOWN,
238 [BTN_X] = GAMEPAD_BUTTON_RIGHT_FACE_LEFT,
239 [BTN_TL] = GAMEPAD_BUTTON_LEFT_TRIGGER_1,
240 [BTN_TL2] = GAMEPAD_BUTTON_LEFT_TRIGGER_2,
241 [BTN_TR] = GAMEPAD_BUTTON_RIGHT_TRIGGER_1,
242 [BTN_TR2] = GAMEPAD_BUTTON_RIGHT_TRIGGER_2,
243 [BTN_SELECT] = GAMEPAD_BUTTON_MIDDLE_LEFT,
244 [BTN_MODE] = GAMEPAD_BUTTON_MIDDLE,
245 [BTN_START] = GAMEPAD_BUTTON_MIDDLE_RIGHT,
246 [BTN_THUMBL] = GAMEPAD_BUTTON_LEFT_THUMB,
247 [BTN_THUMBR] = GAMEPAD_BUTTON_RIGHT_THUMB,
248 };
249
250 //----------------------------------------------------------------------------------
251 // Module Internal Functions Declaration
252 //----------------------------------------------------------------------------------
253 int InitPlatform(void); // Initialize platform (graphics, inputs and more)
254 void ClosePlatform(void); // Close platform
255
256 #if SUPPORT_SSH_KEYBOARD_RPI
257 static void InitKeyboard(void); // Initialize raw keyboard system
258 static void RestoreKeyboard(void); // Restore keyboard system
259 static void ProcessKeyboard(void); // Process keyboard events
260 #endif
261
262 // Input management functions
263 static void InitEvdevInput(void); // Initialize evdev inputs
264 static void ConfigureEvdevDevice(char *device); // Identifies a input device and configures it for use if appropriate
265 static void PollKeyboardEvents(void); // Process evdev keyboard events
266 static void PollGamepadEvents(void); // Process evdev gamepad events
267 static void PollMouseEvents(void); // Process evdev mouse events
268
269 static int FindMatchingConnectorMode(const drmModeConnector *connector, const drmModeModeInfo *mode); // Search matching DRM mode in connector's mode list
270 static int FindExactConnectorMode(const drmModeConnector *connector, uint width, uint height, uint fps, bool allowInterlaced); // Search exactly matching DRM connector mode in connector's list
271 static int FindNearestConnectorMode(const drmModeConnector *connector, uint width, uint height, uint fps, bool allowInterlaced); // Search the nearest matching DRM connector mode in connector's list
272
273 static void SetupFramebuffer(int width, int height); // Setup main framebuffer (required by InitPlatform())
274
275 //----------------------------------------------------------------------------------
276 // Module Functions Declaration
277 //----------------------------------------------------------------------------------
278 // NOTE: Functions declaration is provided by raylib.h
279
280 //----------------------------------------------------------------------------------
281 // Module Functions Definition: Window and Graphics Device
282 //----------------------------------------------------------------------------------
283
284 // Check if application should close
285 // NOTE: By default, if KEY_ESCAPE pressed
286 bool WindowShouldClose(void)
287 {
288 if (CORE.Window.ready) return CORE.Window.shouldClose;
289 else return true;
290 }
291
292 // Toggle fullscreen mode
293 void ToggleFullscreen(void)
294 {
295 TRACELOG(LOG_WARNING, "ToggleFullscreen() not available on target platform");
296 }
297
298 // Toggle borderless windowed mode
299 void ToggleBorderlessWindowed(void)
300 {
301 TRACELOG(LOG_WARNING, "ToggleBorderlessWindowed() not available on target platform");
302 }
303
304 // Set window state: maximized, if resizable
305 void MaximizeWindow(void)
306 {
307 TRACELOG(LOG_WARNING, "MaximizeWindow() not available on target platform");
308 }
309
310 // Set window state: minimized
311 void MinimizeWindow(void)
312 {
313 TRACELOG(LOG_WARNING, "MinimizeWindow() not available on target platform");
314 }
315
316 // Restore window from being minimized/maximized
317 void RestoreWindow(void)
318 {
319 TRACELOG(LOG_WARNING, "RestoreWindow() not available on target platform");
320 }
321
322 // Set window configuration state using flags
323 void SetWindowState(unsigned int flags)
324 {
325 TRACELOG(LOG_WARNING, "SetWindowState() not available on target platform");
326 }
327
328 // Clear window configuration state flags
329 void ClearWindowState(unsigned int flags)
330 {
331 TRACELOG(LOG_WARNING, "ClearWindowState() not available on target platform");
332 }
333
334 // Set icon for window
335 void SetWindowIcon(Image image)
336 {
337 TRACELOG(LOG_WARNING, "SetWindowIcon() not available on target platform");
338 }
339
340 // Set icon for window
341 void SetWindowIcons(Image *images, int count)
342 {
343 TRACELOG(LOG_WARNING, "SetWindowIcons() not available on target platform");
344 }
345
346 // Set title for window
347 void SetWindowTitle(const char *title)
348 {
349 CORE.Window.title = title;
350 }
351
352 // Set window position on screen (windowed mode)
353 void SetWindowPosition(int x, int y)
354 {
355 TRACELOG(LOG_WARNING, "SetWindowPosition() not available on target platform");
356 }
357
358 // Set monitor for the current window
359 void SetWindowMonitor(int monitor)
360 {
361 TRACELOG(LOG_WARNING, "SetWindowMonitor() not available on target platform");
362 }
363
364 // Set window minimum dimensions (FLAG_WINDOW_RESIZABLE)
365 void SetWindowMinSize(int width, int height)
366 {
367 CORE.Window.screenMin.width = width;
368 CORE.Window.screenMin.height = height;
369 }
370
371 // Set window maximum dimensions (FLAG_WINDOW_RESIZABLE)
372 void SetWindowMaxSize(int width, int height)
373 {
374 CORE.Window.screenMax.width = width;
375 CORE.Window.screenMax.height = height;
376 }
377
378 // Set window dimensions
379 void SetWindowSize(int width, int height)
380 {
381 TRACELOG(LOG_WARNING, "SetWindowSize() not available on target platform");
382 }
383
384 // Set window opacity, value opacity is between 0.0 and 1.0
385 void SetWindowOpacity(float opacity)
386 {
387 TRACELOG(LOG_WARNING, "SetWindowOpacity() not available on target platform");
388 }
389
390 // Set window focused
391 void SetWindowFocused(void)
392 {
393 TRACELOG(LOG_WARNING, "SetWindowFocused() not available on target platform");
394 }
395
396 // Get native window handle
397 void *GetWindowHandle(void)
398 {
399 TRACELOG(LOG_WARNING, "GetWindowHandle() not implemented on target platform");
400 return NULL;
401 }
402
403 // Get number of monitors
404 int GetMonitorCount(void)
405 {
406 TRACELOG(LOG_WARNING, "GetMonitorCount() not implemented on target platform");
407 return 1;
408 }
409
410 // Get current monitor where window is placed
411 int GetCurrentMonitor(void)
412 {
413 TRACELOG(LOG_WARNING, "GetCurrentMonitor() not implemented on target platform");
414 return 0;
415 }
416
417 // Get selected monitor position
418 Vector2 GetMonitorPosition(int monitor)
419 {
420 TRACELOG(LOG_WARNING, "GetMonitorPosition() not implemented on target platform");
421 return (Vector2){ 0, 0 };
422 }
423
424 // Get selected monitor width (currently used by monitor)
425 int GetMonitorWidth(int monitor)
426 {
427 int width = 0;
428
429 if (monitor != 0)
430 {
431 TRACELOG(LOG_WARNING, "GetMonitorWidth() implemented for first monitor only");
432 }
433 else if ((platform.connector) && (platform.modeIndex >= 0))
434 {
435 width = platform.connector->modes[platform.modeIndex].hdisplay;
436 }
437
438 return width;
439 }
440
441 // Get selected monitor height (currently used by monitor)
442 int GetMonitorHeight(int monitor)
443 {
444 int height = 0;
445
446 if (monitor != 0)
447 {
448 TRACELOG(LOG_WARNING, "GetMonitorHeight() implemented for first monitor only");
449 }
450 else if ((platform.connector) && (platform.modeIndex >= 0))
451 {
452 height = platform.connector->modes[platform.modeIndex].vdisplay;
453 }
454
455 return height;
456 }
457
458 // Get selected monitor physical width in millimetres
459 int GetMonitorPhysicalWidth(int monitor)
460 {
461 int physicalWidth = 0;
462
463 if (monitor != 0)
464 {
465 TRACELOG(LOG_WARNING, "GetMonitorPhysicalWidth() implemented for first monitor only");
466 }
467 else if ((platform.connector) && (platform.modeIndex >= 0))
468 {
469 physicalWidth = platform.connector->mmWidth;
470 }
471
472 return physicalWidth;
473 }
474
475 // Get selected monitor physical height in millimetres
476 int GetMonitorPhysicalHeight(int monitor)
477 {
478 int physicalHeight = 0;
479
480 if (monitor != 0)
481 {
482 TRACELOG(LOG_WARNING, "GetMonitorPhysicalHeight() implemented for first monitor only");
483 }
484 else if ((platform.connector) && (platform.modeIndex >= 0))
485 {
486 physicalHeight = platform.connector->mmHeight;
487 }
488
489 return physicalHeight;
490 }
491
492 // Get selected monitor refresh rate
493 int GetMonitorRefreshRate(int monitor)
494 {
495 int refresh = 0;
496
497 if ((platform.connector) && (platform.modeIndex >= 0))
498 {
499 refresh = platform.connector->modes[platform.modeIndex].vrefresh;
500 }
501
502 return refresh;
503 }
504
505 // Get the human-readable, UTF-8 encoded name of the selected monitor
506 const char *GetMonitorName(int monitor)
507 {
508 const char *name = "";
509
510 if (monitor != 0)
511 {
512 TRACELOG(LOG_WARNING, "GetMonitorName() implemented for first monitor only");
513 }
514 else if ((platform.connector) && (platform.modeIndex >= 0))
515 {
516 name = platform.connector->modes[platform.modeIndex].name;
517 }
518
519 return name;
520 }
521
522 // Get window position XY on monitor
523 Vector2 GetWindowPosition(void)
524 {
525 return (Vector2){ 0, 0 };
526 }
527
528 // Get window scale DPI factor for current monitor
529 Vector2 GetWindowScaleDPI(void)
530 {
531 return (Vector2){ 1.0f, 1.0f };
532 }
533
534 // Set clipboard text content
535 void SetClipboardText(const char *text)
536 {
537 TRACELOG(LOG_WARNING, "SetClipboardText() not implemented on target platform");
538 }
539
540 // Get clipboard text content
541 // NOTE: returned string is allocated and freed by GLFW
542 const char *GetClipboardText(void)
543 {
544 TRACELOG(LOG_WARNING, "GetClipboardText() not implemented on target platform");
545 return NULL;
546 }
547
548 // Get clipboard image
549 Image GetClipboardImage(void)
550 {
551 Image image = { 0 };
552
553 TRACELOG(LOG_WARNING, "GetClipboardImage() not implemented on target platform");
554
555 return image;
556 }
557
558 // Show mouse cursor
559 void ShowCursor(void)
560 {
561 CORE.Input.Mouse.cursorHidden = false;
562 }
563
564 // Hides mouse cursor
565 void HideCursor(void)
566 {
567 CORE.Input.Mouse.cursorHidden = true;
568 }
569
570 // Enables cursor (unlock cursor)
571 void EnableCursor(void)
572 {
573 // Set cursor position in the middle
574 SetMousePosition(CORE.Window.screen.width/2, CORE.Window.screen.height/2);
575
576 platform.cursorRelative = false;
577 CORE.Input.Mouse.cursorLocked = false;
578 }
579
580 // Disables cursor (lock cursor)
581 void DisableCursor(void)
582 {
583 // Set cursor position in the middle
584 SetMousePosition(0, 0);
585
586 platform.cursorRelative = true;
587 CORE.Input.Mouse.cursorLocked = true;
588 }
589
590 #if defined(SUPPORT_DRM_CACHE)
591
592 // Destroy cached framebuffer callback, set by gbm_bo_set_user_data()
593 static void DestroyFrameBufferCallback(struct gbm_bo *bo, void *data)
594 {
595 uint32_t fbId = (uintptr_t)data;
596
597 // Remove from cache
598 for (int i = 0; i < fbCacheCount; i++)
599 {
600 if (fbCache[i].bo == bo)
601 {
602 TRACELOG(LOG_INFO, "DISPLAY: DRM: Framebuffer removed [%u]", (uintptr_t)fbId);
603 drmModeRmFB(platform.fd, fbCache[i].fbId); // Release DRM FB
604
605 // Shift remaining entries
606 for (int j = i; j < fbCacheCount - 1; j++) fbCache[j] = fbCache[j + 1];
607
608 fbCacheCount--;
609 break;
610 }
611 }
612 }
613
614 // Create or retrieve cached DRM FB for BO
615 static uint32_t GetOrCreateFbForBo(struct gbm_bo *bo)
616 {
617 // Try to find existing cache entry
618 for (int i = 0; i < fbCacheCount; i++)
619 {
620 if (fbCache[i].bo == bo) return fbCache[i].fbId;
621 }
622
623 // Create new entry if cache not full
624 if (fbCacheCount >= MAX_DRM_CACHED_BUFFERS) return 0; // FB cache full
625
626 uint32_t handle = gbm_bo_get_handle(bo).u32;
627 uint32_t stride = gbm_bo_get_stride(bo);
628 uint32_t width = gbm_bo_get_width(bo);
629 uint32_t height = gbm_bo_get_height(bo);
630
631 uint32_t fbId = 0;
632 if (drmModeAddFB(platform.fd, width, height, 24, 32, stride, handle, &fbId)) return 0;
633
634 // Store in cache
635 fbCache[fbCacheCount] = (FramebufferCache){ .bo = bo, .fbId = fbId };
636 fbCacheCount++;
637
638 // Set destroy callback to auto-cleanup
639 gbm_bo_set_user_data(bo, (void *)(uintptr_t)fbId, DestroyFrameBufferCallback);
640
641 TRACELOG(LOG_INFO, "DISPLAY: DRM: Added new buffer object [%u]" , (uintptr_t)fbId);
642
643 return fbId;
644 }
645
646 // Renders a blank frame to allocate initial buffers
647 // TODO: WARNING: Platform backend should not include OpenGL code
648 void RenderBlankFrame()
649 {
650 glClearColor(0, 0, 0, 1);
651 glClear(GL_COLOR_BUFFER_BIT);
652 eglSwapBuffers(platform.device, platform.surface);
653 glFinish(); // Ensure the buffer is processed
654 }
655
656 // Initialize with first buffer only
657 int InitSwapScreenBuffer()
658 {
659 if (!platform.gbmSurface || (platform.fd < 0))
660 {
661 TRACELOG(LOG_ERROR, "DISPLAY: DRM: Swap buffers can not be initialized");
662 return -1;
663 }
664
665 // Render a blank frame to allocate buffers
666 RenderBlankFrame();
667
668 // Get first buffer
669 struct gbm_bo *bo = gbm_surface_lock_front_buffer(platform.gbmSurface);
670 if (!bo)
671 {
672 TRACELOG(LOG_ERROR, "DISPLAY: DRM: Failed to lock initial swap buffer");
673 return -1;
674 }
675
676 // Create FB for first buffer
677 uint32_t fbId = GetOrCreateFbForBo(bo);
678 if (!fbId)
679 {
680 gbm_surface_release_buffer(platform.gbmSurface, bo);
681 return -1;
682 }
683
684 // Initial CRTC setup
685 if (drmModeSetCrtc(platform.fd, platform.crtc->crtc_id, fbId, 0, 0, &platform.connector->connector_id, 1, &platform.connector->modes[platform.modeIndex]))
686 {
687 TRACELOG(LOG_ERROR, "DISPLAY: DRM: Failed to initialize CRTC setup. ERROR: %s", strerror(errno));
688 gbm_surface_release_buffer(platform.gbmSurface, bo);
689 return -1;
690 }
691
692 // Keep first buffer locked until flipped
693 platform.prevBO = bo;
694 crtcSet = true;
695
696 return 0;
697 }
698
699 // Static page flip handler
700 // NOTE: Called once the drmModePageFlip() finished from the drmHandleEvent() context
701 static void PageFlipHandler(int fd, unsigned int frame, unsigned int sec, unsigned int usec, void *data)
702 {
703 // Unused inputs
704 (void)fd;
705 (void)frame;
706 (void)sec;
707 (void)usec;
708
709 pendingFlip = false;
710 struct gbm_bo *boToRelease = (struct gbm_bo *)data;
711
712 // Buffers are released after the flip completes (via page_flip_handler), ensuring they're no longer in use
713 // Prevents the GPU from writing to a buffer being scanned out
714 if (boToRelease) gbm_surface_release_buffer(platform.gbmSurface, boToRelease);
715 }
716
717 // Swap implementation with proper caching
718 void SwapScreenBuffer()
719 {
720 if (!crtcSet || !platform.gbmSurface) return;
721
722 static int loopCnt = 0;
723 static int errCnt[5] = { 0 };
724 loopCnt++;
725
726 // Call this only, if pendingFlip is not set
727 eglSwapBuffers(platform.device, platform.surface);
728
729 // Process pending events non-blocking
730 drmEventContext evctx = {
731 .version = DRM_EVENT_CONTEXT_VERSION,
732 .page_flip_handler = PageFlipHandler
733 };
734
735 struct pollfd pfd = { .fd = platform.fd, .events = POLLIN };
736
737 // Polling for event for 0ms
738 while (poll(&pfd, 1, 0) > 0) drmHandleEvent(platform.fd, &evctx);
739
740 // Skip if previous flip pending
741 if (pendingFlip)
742 {
743 errCnt[0]++; // Skip frame: flip pending
744 return;
745 }
746
747 // Get new front buffer
748 struct gbm_bo *nextBO = gbm_surface_lock_front_buffer(platform.gbmSurface);
749 if (!nextBO) // Failed to lock front buffer
750 {
751 errCnt[1]++;
752 return;
753 }
754
755 // Get FB ID (creates new one if needed)
756 uint32_t fbId = GetOrCreateFbForBo(nextBO);
757 if (!fbId)
758 {
759 gbm_surface_release_buffer(platform.gbmSurface, nextBO);
760 errCnt[2]++;
761 return;
762 }
763
764 // Attempt page flip
765 // NOTE: rmModePageFlip() schedules a buffer-flip for the next vblank and then notifies us about it
766 // It takes a CRTC-id, fb-id and an arbitrary data-pointer and then schedules the page-flip
767 // This is fully asynchronous and when the page-flip happens, the DRM-fd will become readable and drmHandleEvent() can be called
768 // This will read all vblank/page-flip events and call our modeset_page_flip_event() callback with the data-pointer passed to drmModePageFlip()
769 // Simply call modeset_draw_dev() then so the next frame is rendered... returns immediately
770 if (drmModePageFlip(platform.fd, platform.crtc->crtc_id, fbId, DRM_MODE_PAGE_FLIP_EVENT, platform.prevBO))
771 {
772 if (errno == EBUSY) errCnt[3]++; // Display busy - skip flip
773 else errCnt[4]++; // Page flip failed
774
775 gbm_surface_release_buffer(platform.gbmSurface, nextBO);
776 return;
777 }
778
779 // Success: update state
780 pendingFlip = true;
781 platform.prevBO = nextBO;
782
783 /*
784 // Some benchmarking code
785 if (loopCnt >= 600)
786 {
787 TRACELOG(LOG_INFO, "DRM: Error counters: %d, %d, %d, %d, %d, %d", errCnt[0], errCnt[1], errCnt[2], errCnt[3], errCnt[4], loopCnt);
788 for (int i = 0; i < 5; i++) errCnt[i] = 0;
789 loopCnt = 0;
790 }
791 */
792 }
793
794 #else // !SUPPORT_DRM_CACHE
795
796 // Swap back buffer with front buffer (screen drawing)
797 void SwapScreenBuffer(void)
798 {
799 #if !defined(GRAPHICS_API_OPENGL_SOFTWARE)
800 // Hardware rendering buffer swap with EGL
801 eglSwapBuffers(platform.device, platform.surface);
802
803 if (!platform.gbmSurface || (-1 == platform.fd) || !platform.connector || !platform.crtc) TRACELOG(LOG_ERROR, "DISPLAY: DRM initialization failed to swap");
804
805 struct gbm_bo *bo = gbm_surface_lock_front_buffer(platform.gbmSurface);
806 if (!bo) TRACELOG(LOG_ERROR, "DISPLAY: Failed GBM to lock front buffer");
807
808 uint32_t fb = 0;
809 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);
810 if (result != 0) TRACELOG(LOG_ERROR, "DISPLAY: drmModeAddFB() failed with result: %d", result);
811
812 result = drmModeSetCrtc(platform.fd, platform.crtc->crtc_id, fb, 0, 0, &platform.connector->connector_id, 1, &platform.connector->modes[platform.modeIndex]);
813 if (result != 0) TRACELOG(LOG_ERROR, "DISPLAY: drmModeSetCrtc() failed with result: %d", result);
814
815 if (platform.prevFB)
816 {
817 result = drmModeRmFB(platform.fd, platform.prevFB);
818 if (result != 0) TRACELOG(LOG_ERROR, "DISPLAY: drmModeRmFB() failed with result: %d", result);
819 }
820
821 platform.prevFB = fb;
822
823 if (platform.prevBO) gbm_surface_release_buffer(platform.gbmSurface, platform.prevBO);
824
825 platform.prevBO = bo;
826 #else
827 // Software rendering buffer swap
828 if ((platform.fd == -1) || !platform.connector || (platform.modeIndex < 0))
829 {
830 TRACELOG(LOG_ERROR, "DISPLAY: DRM initialization failed to swap");
831 return;
832 }
833
834 // Retrieving the dimensions of the display mode used
835 drmModeModeInfo *mode = &platform.connector->modes[platform.modeIndex];
836 uint32_t width = mode->hdisplay;
837 uint32_t height = mode->vdisplay;
838
839 // Dumb buffers use a fixed format based on bpp
840 const uint32_t bpp = 32; // 32 bits per pixel (XRGB8888 format)
841 const uint32_t depth = 24; // Color depth, here only 24 bits, alpha is not used
842
843 // Create a dumb buffer for software rendering
844 struct drm_mode_create_dumb creq = { 0 };
845 creq.width = width;
846 creq.height = height;
847 creq.bpp = bpp;
848
849 int result = drmIoctl(platform.fd, DRM_IOCTL_MODE_CREATE_DUMB, &creq);
850 if (result < 0)
851 {
852 TRACELOG(LOG_ERROR, "DISPLAY: Failed to create dumb buffer: %s", strerror(errno));
853 return;
854 }
855
856 // Create framebuffer with the correct format
857 uint32_t fb = 0;
858 result = drmModeAddFB(platform.fd, width, height, depth, bpp, creq.pitch, creq.handle, &fb);
859 if (result != 0)
860 {
861 TRACELOG(LOG_ERROR, "DISPLAY: drmModeAddFB() failed with result: %d (%s)", result, strerror(errno));
862 struct drm_mode_destroy_dumb dreq = { 0 };
863 dreq.handle = creq.handle;
864 drmIoctl(platform.fd, DRM_IOCTL_MODE_DESTROY_DUMB, &dreq);
865 return;
866 }
867
868 // Map the dumb buffer to copy our software rendered buffer
869 struct drm_mode_map_dumb mreq = { 0 };
870 mreq.handle = creq.handle;
871 result = drmIoctl(platform.fd, DRM_IOCTL_MODE_MAP_DUMB, &mreq);
872 if (result != 0)
873 {
874 TRACELOG(LOG_ERROR, "DISPLAY: Failed to map dumb buffer: %s", strerror(errno));
875 drmModeRmFB(platform.fd, fb);
876 struct drm_mode_destroy_dumb dreq = { 0 };
877 dreq.handle = creq.handle;
878 drmIoctl(platform.fd, DRM_IOCTL_MODE_DESTROY_DUMB, &dreq);
879 return;
880 }
881
882 // Map the buffer into userspace
883 void *dumbBuffer = mmap(0, creq.size, PROT_READ | PROT_WRITE, MAP_SHARED, platform.fd, mreq.offset);
884 if (dumbBuffer == MAP_FAILED)
885 {
886 TRACELOG(LOG_ERROR, "DISPLAY: Failed to mmap dumb buffer: %s", strerror(errno));
887 drmModeRmFB(platform.fd, fb);
888 struct drm_mode_destroy_dumb dreq = { 0 };
889 dreq.handle = creq.handle;
890 drmIoctl(platform.fd, DRM_IOCTL_MODE_DESTROY_DUMB, &dreq);
891 return;
892 }
893
894 // Copy the software rendered buffer to the dumb buffer with scaling if needed
895 // NOTE: RLSW will make a simple copy if the dimensions match
896 swBlitPixels(0, 0, width, height, 0, 0, width, height, SW_RGBA, SW_UNSIGNED_BYTE, dumbBuffer);
897
898 // Unmap the buffer
899 munmap(dumbBuffer, creq.size);
900
901 // Find a CRTC compatible with the connector
902 uint32_t crtcId = 0;
903 if (platform.crtc) crtcId = platform.crtc->crtc_id;
904 else
905 {
906 // Find a CRTC that's compatible with this connector
907 drmModeRes *res = drmModeGetResources(platform.fd);
908 if (!res)
909 {
910 TRACELOG(LOG_ERROR, "DISPLAY: Failed to get DRM resources");
911 drmModeRmFB(platform.fd, fb);
912 struct drm_mode_destroy_dumb dreq = { 0 };
913 dreq.handle = creq.handle;
914 drmIoctl(platform.fd, DRM_IOCTL_MODE_DESTROY_DUMB, &dreq);
915 return;
916 }
917
918 // Check which CRTCs are compatible with this connector
919 drmModeEncoder *encoder = NULL;
920 if (platform.connector->encoder_id) encoder = drmModeGetEncoder(platform.fd, platform.connector->encoder_id);
921
922 if (encoder && encoder->crtc_id)
923 {
924 crtcId = encoder->crtc_id;
925 platform.crtc = drmModeGetCrtc(platform.fd, crtcId);
926 }
927 else
928 {
929 // Find a free CRTC
930 for (int i = 0; i < res->count_crtcs; i++)
931 {
932 drmModeCrtc *crtc = drmModeGetCrtc(platform.fd, res->crtcs[i]);
933 if (crtc && !crtc->buffer_id) // CRTC is free
934 {
935 crtcId = res->crtcs[i];
936 if (platform.crtc) drmModeFreeCrtc(platform.crtc);
937 platform.crtc = crtc;
938 break;
939 }
940
941 if (crtc) drmModeFreeCrtc(crtc);
942 }
943 }
944
945 if (encoder) drmModeFreeEncoder(encoder);
946 drmModeFreeResources(res);
947
948 if (!crtcId)
949 {
950 TRACELOG(LOG_ERROR, "DISPLAY: No compatible CRTC found");
951 drmModeRmFB(platform.fd, fb);
952 struct drm_mode_destroy_dumb dreq = { 0 };
953 dreq.handle = creq.handle;
954 drmIoctl(platform.fd, DRM_IOCTL_MODE_DESTROY_DUMB, &dreq);
955 return;
956 }
957 }
958
959 // Set CRTC with better error handling
960 result = drmModeSetCrtc(platform.fd, crtcId, fb, 0, 0, &platform.connector->connector_id, 1, mode);
961 if (result != 0)
962 {
963 TRACELOG(LOG_ERROR, "DISPLAY: drmModeSetCrtc() failed with result: %d (%s)", result, strerror(errno));
964 TRACELOG(LOG_ERROR, "DISPLAY: CRTC ID: %u, FB ID: %u, Connector ID: %u", crtcId, fb, platform.connector->connector_id);
965 TRACELOG(LOG_ERROR, "DISPLAY: Mode: %dx%d@%d", mode->hdisplay, mode->vdisplay, mode->vrefresh);
966
967 drmModeRmFB(platform.fd, fb);
968 struct drm_mode_destroy_dumb dreq = { 0 };
969 dreq.handle = creq.handle;
970 drmIoctl(platform.fd, DRM_IOCTL_MODE_DESTROY_DUMB, &dreq);
971 return;
972 }
973
974 // Clean up previous framebuffer
975 if (platform.prevFB)
976 {
977 result = drmModeRmFB(platform.fd, platform.prevFB);
978 if (result != 0) TRACELOG(LOG_WARNING, "DISPLAY: drmModeRmFB() failed with result: %d", result);
979 }
980
981 platform.prevFB = fb;
982
983 // Clean up previous dumb buffer
984 if (platform.prevDumbHandle)
985 {
986 struct drm_mode_destroy_dumb dreq = { 0 };
987 dreq.handle = platform.prevDumbHandle;
988 drmIoctl(platform.fd, DRM_IOCTL_MODE_DESTROY_DUMB, &dreq);
989 }
990
991 platform.prevDumbHandle = creq.handle;
992 #endif
993 }
994 #endif // SUPPORT_DRM_CACHE
995
996 //----------------------------------------------------------------------------------
997 // Module Functions Definition: Misc
998 //----------------------------------------------------------------------------------
999
1000 // Get elapsed time measure in seconds since InitTimer()
1001 double GetTime(void)
1002 {
1003 double time = 0.0;
1004 struct timespec ts = { 0 };
1005 clock_gettime(CLOCK_MONOTONIC, &ts);
1006 unsigned long long int nanoSeconds = (unsigned long long int)ts.tv_sec*1000000000LLU + (unsigned long long int)ts.tv_nsec;
1007
1008 time = (double)(nanoSeconds - CORE.Time.base)*1e-9; // Elapsed time since InitTimer()
1009
1010 return time;
1011 }
1012
1013 // Open URL with default system browser (if available)
1014 // NOTE: This function is only safe to use if the provided URL is safe
1015 // A user could craft a malicious string performing another action
1016 // Avoid calling this function with user input non-validated strings
1017 void OpenURL(const char *url)
1018 {
1019 TRACELOG(LOG_WARNING, "OpenURL() not implemented on target platform");
1020 }
1021
1022 //----------------------------------------------------------------------------------
1023 // Module Functions Definition: Inputs
1024 //----------------------------------------------------------------------------------
1025
1026 // Set internal gamepad mappings
1027 int SetGamepadMappings(const char *mappings)
1028 {
1029 TRACELOG(LOG_WARNING, "SetGamepadMappings() not implemented on target platform");
1030 return 0;
1031 }
1032
1033 // Set gamepad vibration
1034 void SetGamepadVibration(int gamepad, float leftMotor, float rightMotor, float duration)
1035 {
1036 TRACELOG(LOG_WARNING, "SetGamepadVibration() not implemented on target platform");
1037 }
1038
1039 // Set mouse position XY
1040 void SetMousePosition(int x, int y)
1041 {
1042 CORE.Input.Mouse.currentPosition = (Vector2){ (float)x, (float)y };
1043 CORE.Input.Mouse.previousPosition = CORE.Input.Mouse.currentPosition;
1044 }
1045
1046 // Set mouse cursor
1047 void SetMouseCursor(int cursor)
1048 {
1049 TRACELOG(LOG_WARNING, "SetMouseCursor() not implemented on target platform");
1050 }
1051
1052 // Get physical key name
1053 const char *GetKeyName(int key)
1054 {
1055 TRACELOG(LOG_WARNING, "GetKeyName() not implemented on target platform");
1056 return "";
1057 }
1058
1059 // Register all input events
1060 void PollInputEvents(void)
1061 {
1062 #if SUPPORT_GESTURES_SYSTEM
1063 // NOTE: Gestures update must be called every frame to reset gestures correctly
1064 // because ProcessGestureEvent() is called on an event, not every frame
1065 UpdateGestures();
1066 #endif
1067
1068 // Reset keys/chars pressed registered
1069 CORE.Input.Keyboard.keyPressedQueueCount = 0;
1070 CORE.Input.Keyboard.charPressedQueueCount = 0;
1071
1072 // Reset last gamepad button/axis registered state
1073 CORE.Input.Gamepad.lastButtonPressed = 0; // GAMEPAD_BUTTON_UNKNOWN
1074 //CORE.Input.Gamepad.axisCount = 0;
1075
1076 // Register previous keys states
1077 for (int i = 0; i < MAX_KEYBOARD_KEYS; i++)
1078 {
1079 CORE.Input.Keyboard.previousKeyState[i] = CORE.Input.Keyboard.currentKeyState[i];
1080 CORE.Input.Keyboard.keyRepeatInFrame[i] = 0;
1081 }
1082
1083 PollKeyboardEvents();
1084
1085 #if SUPPORT_SSH_KEYBOARD_RPI
1086 // NOTE: Keyboard reading could be done using input_event(s) or read from stdin, both methods are used here
1087 // stdin reading is still used for legacy purposes, it allows keyboard input trough SSH console
1088 if (!platform.eventKeyboardMode) ProcessKeyboard();
1089 #endif
1090
1091 // Check exit key
1092 if (CORE.Input.Keyboard.currentKeyState[CORE.Input.Keyboard.exitKey] == 1) CORE.Window.shouldClose = true;
1093
1094 // Register previous mouse position
1095 if (platform.cursorRelative) CORE.Input.Mouse.currentPosition = (Vector2){ 0.0f, 0.0f };
1096 else CORE.Input.Mouse.previousPosition = CORE.Input.Mouse.currentPosition;
1097
1098 // Register previous mouse states
1099 CORE.Input.Mouse.previousWheelMove = CORE.Input.Mouse.currentWheelMove;
1100 CORE.Input.Mouse.currentWheelMove = platform.eventWheelMove;
1101 platform.eventWheelMove = (Vector2){ 0.0f, 0.0f };
1102
1103 for (int i = 0; i < MAX_MOUSE_BUTTONS; i++)
1104 {
1105 CORE.Input.Mouse.previousButtonState[i] = CORE.Input.Mouse.currentButtonState[i];
1106 CORE.Input.Mouse.currentButtonState[i] = platform.currentButtonStateEvdev[i];
1107 CORE.Input.Touch.currentTouchState[i] = platform.currentButtonStateEvdev[i];
1108 }
1109
1110 // Register gamepads buttons events
1111 PollGamepadEvents();
1112
1113 // Register previous touch states
1114 for (int i = 0; i < MAX_TOUCH_POINTS; i++) CORE.Input.Touch.previousTouchState[i] = CORE.Input.Touch.currentTouchState[i];
1115
1116 // Map touch position to mouse position for convenience
1117 // NOTE: For DRM touchscreen devices, this mapping is disabled to avoid false touch detection
1118 // CORE.Input.Touch.position[0] = CORE.Input.Mouse.currentPosition;
1119
1120 // Handle the mouse/touch/gestures events:
1121 PollMouseEvents();
1122 }
1123
1124 //----------------------------------------------------------------------------------
1125 // Module Internal Functions Definition
1126 //----------------------------------------------------------------------------------
1127
1128 // Initialize platform: graphics, inputs and more
1129 int InitPlatform(void)
1130 {
1131 platform.fd = -1;
1132 platform.connector = NULL;
1133 platform.modeIndex = -1;
1134 platform.crtc = NULL;
1135 platform.prevFB = 0;
1136
1137 #if !defined(GRAPHICS_API_OPENGL_SOFTWARE)
1138 platform.gbmDevice = NULL;
1139 platform.gbmSurface = NULL;
1140 platform.prevBO = NULL;
1141 #else
1142 platform.prevDumbHandle = 0;
1143 #endif
1144
1145 // Initialize graphic device: display/window and graphic context
1146 //----------------------------------------------------------------------------
1147 FLAG_SET(CORE.Window.flags, FLAG_FULLSCREEN_MODE);
1148
1149 #if defined(DEFAULT_GRAPHIC_DEVICE_DRM)
1150 platform.fd = open(DEFAULT_GRAPHIC_DEVICE_DRM, O_RDWR);
1151 if (platform.fd != -1) TRACELOG(LOG_INFO, "DISPLAY: Default graphic device DRM opened successfully");
1152 #else
1153 TRACELOG(LOG_WARNING, "DISPLAY: No graphic card set, trying platform-gpu-card");
1154 platform.fd = open("/dev/dri/by-path/platform-gpu-card", O_RDWR); // VideoCore VI (Raspberry Pi 4)
1155 if (platform.fd != -1) TRACELOG(LOG_INFO, "DISPLAY: platform-gpu-card opened successfully");
1156
1157 drmModeRes *res = NULL;
1158 if ((platform.fd == -1) || ((res = drmModeGetResources(platform.fd)) == NULL))
1159 {
1160 if (platform.fd != -1) close(platform.fd);
1161 TRACELOG(LOG_WARNING, "DISPLAY: Failed to open platform-gpu-card, trying card1");
1162 platform.fd = open("/dev/dri/card1", O_RDWR); // Other Embedded
1163 if (platform.fd != -1) TRACELOG(LOG_INFO, "DISPLAY: card1 opened successfully");
1164 }
1165
1166 if ((platform.fd == -1) || ((res = drmModeGetResources(platform.fd)) == NULL))
1167 {
1168 if (platform.fd != -1) close(platform.fd);
1169 TRACELOG(LOG_WARNING, "DISPLAY: Failed to open graphic card1, trying card0");
1170 platform.fd = open("/dev/dri/card0", O_RDWR); // VideoCore IV (Raspberry Pi 1-3)
1171 if (platform.fd != -1) TRACELOG(LOG_INFO, "DISPLAY: card0 opened successfully");
1172 }
1173
1174 if ((platform.fd == -1) || ((res = drmModeGetResources(platform.fd)) == NULL))
1175 {
1176 if (platform.fd != -1) close(platform.fd);
1177 TRACELOG(LOG_WARNING, "DISPLAY: Failed to open graphic card0, trying card2");
1178 platform.fd = open("/dev/dri/card2", O_RDWR);
1179 if (platform.fd != -1) TRACELOG(LOG_INFO, "DISPLAY: card2 opened successfully");
1180 }
1181 #endif
1182
1183 if (platform.fd == -1)
1184 {
1185 TRACELOG(LOG_WARNING, "DISPLAY: Failed to open graphic card");
1186 return -1;
1187 }
1188
1189 if (!res)
1190 {
1191 TRACELOG(LOG_WARNING, "DISPLAY: Failed get DRM resources");
1192 close(platform.fd);
1193 return -1;
1194 }
1195
1196 TRACELOG(LOG_TRACE, "DISPLAY: Connectors found: %i", res->count_connectors);
1197
1198 // Connector detection
1199 for (size_t i = 0; i < res->count_connectors; i++)
1200 {
1201 TRACELOG(LOG_TRACE, "DISPLAY: Connector index %i", i);
1202
1203 drmModeConnector *con = drmModeGetConnector(platform.fd, res->connectors[i]);
1204 if (!con)
1205 {
1206 TRACELOG(LOG_WARNING, "DISPLAY: Failed to get connector %i", i);
1207 continue;
1208 }
1209
1210 TRACELOG(LOG_TRACE, "DISPLAY: Connector %i modes detected: %i", i, con->count_modes);
1211 TRACELOG(LOG_TRACE, "DISPLAY: Connector %i status: %s", i,
1212 (con->connection == DRM_MODE_CONNECTED)? "CONNECTED" :
1213 (con->connection == DRM_MODE_DISCONNECTED)? "DISCONNECTED" :
1214 (con->connection == DRM_MODE_UNKNOWNCONNECTION)? "UNKNOWN" : "OTHER");
1215
1216 // In certain cases the status of the conneciton is reported as UKNOWN, but it is still connected
1217 // This might be a hardware or software limitation like on Raspberry Pi Zero with composite output
1218 // WARNING: Accept CONNECTED, UNKNOWN and even those without encoder_id connectors for software mode
1219 if (((con->connection == DRM_MODE_CONNECTED) || (con->connection == DRM_MODE_UNKNOWNCONNECTION)) && (con->count_modes > 0))
1220 {
1221 #if !defined(GRAPHICS_API_OPENGL_SOFTWARE)
1222 // For hardware rendering, an encoder_id is needed
1223 if (con->encoder_id)
1224 {
1225 TRACELOG(LOG_TRACE, "DISPLAY: DRM connector %i connected with encoder", i);
1226 platform.connector = con;
1227 break;
1228 }
1229 else TRACELOG(LOG_TRACE, "DISPLAY: DRM connector %i connected but no encoder", i);
1230 #else
1231 // For software rendering, accept even without encoder_id
1232 TRACELOG(LOG_TRACE, "DISPLAY: DRM connector %i suitable for software rendering", i);
1233 platform.connector = con;
1234 break;
1235 #endif
1236 }
1237
1238 if (!platform.connector)
1239 {
1240 TRACELOG(LOG_TRACE, "DISPLAY: DRM connector %i NOT suitable (deleting)", i);
1241 drmModeFreeConnector(con);
1242 }
1243 }
1244
1245 if (!platform.connector)
1246 {
1247 TRACELOG(LOG_WARNING, "DISPLAY: No suitable DRM connector found");
1248 drmModeFreeResources(res);
1249 close(platform.fd);
1250 return -1;
1251 }
1252
1253 #if !defined(GRAPHICS_API_OPENGL_SOFTWARE)
1254 drmModeEncoder *enc = drmModeGetEncoder(platform.fd, platform.connector->encoder_id);
1255 if (!enc)
1256 {
1257 TRACELOG(LOG_WARNING, "DISPLAY: Failed to get DRM mode encoder");
1258 drmModeFreeConnector(platform.connector);
1259 drmModeFreeResources(res);
1260 close(platform.fd);
1261 return -1;
1262 }
1263
1264 platform.crtc = drmModeGetCrtc(platform.fd, enc->crtc_id);
1265 if (!platform.crtc)
1266 {
1267 TRACELOG(LOG_WARNING, "DISPLAY: Failed to get DRM mode crtc");
1268 drmModeFreeEncoder(enc);
1269 drmModeFreeConnector(platform.connector);
1270 drmModeFreeResources(res);
1271 close(platform.fd);
1272 return -1;
1273 }
1274
1275 // If InitWindow should use the current mode find it in the connector's mode list
1276 if ((CORE.Window.screen.width <= 0) || (CORE.Window.screen.height <= 0))
1277 {
1278 TRACELOG(LOG_TRACE, "DISPLAY: Selecting DRM connector mode for current used mode...");
1279
1280 platform.modeIndex = FindMatchingConnectorMode(platform.connector, &platform.crtc->mode);
1281
1282 if (platform.modeIndex < 0)
1283 {
1284 TRACELOG(LOG_WARNING, "DISPLAY: No matching DRM connector mode found");
1285 drmModeFreeEncoder(enc);
1286 drmModeFreeConnector(platform.connector);
1287 drmModeFreeResources(res);
1288 close(platform.fd);
1289 return -1;
1290 }
1291
1292 CORE.Window.screen.width = CORE.Window.display.width;
1293 CORE.Window.screen.height = CORE.Window.display.height;
1294 }
1295
1296 const bool allowInterlaced = FLAG_IS_SET(CORE.Window.flags, FLAG_INTERLACED_HINT);
1297 const int fps = (CORE.Time.target > 0)? (1.0/CORE.Time.target) : 60;
1298
1299 // Try to find an exact matching mode
1300 platform.modeIndex = FindExactConnectorMode(platform.connector, CORE.Window.screen.width, CORE.Window.screen.height, fps, allowInterlaced);
1301
1302 // If nothing found, try to find a nearly matching mode
1303 if (platform.modeIndex < 0) platform.modeIndex = FindNearestConnectorMode(platform.connector, CORE.Window.screen.width, CORE.Window.screen.height, fps, allowInterlaced);
1304
1305 // If nothing found, try to find an exactly matching mode including interlaced
1306 if (platform.modeIndex < 0) platform.modeIndex = FindExactConnectorMode(platform.connector, CORE.Window.screen.width, CORE.Window.screen.height, fps, true);
1307
1308 // If nothing found, try to find a nearly matching mode including interlaced
1309 if (platform.modeIndex < 0) platform.modeIndex = FindNearestConnectorMode(platform.connector, CORE.Window.screen.width, CORE.Window.screen.height, fps, true);
1310
1311 // If nothing found, there is no suitable mode
1312 if (platform.modeIndex < 0)
1313 {
1314 TRACELOG(LOG_WARNING, "DISPLAY: Failed to find a suitable DRM connector mode");
1315 drmModeFreeEncoder(enc);
1316 drmModeFreeConnector(platform.connector);
1317 drmModeFreeResources(res);
1318 close(platform.fd);
1319 return -1;
1320 }
1321
1322 CORE.Window.display.width = platform.connector->modes[platform.modeIndex].hdisplay;
1323 CORE.Window.display.height = platform.connector->modes[platform.modeIndex].vdisplay;
1324
1325 TRACELOG(LOG_INFO, "DISPLAY: Selected DRM connector mode %s (%ux%u%c@%u)", platform.connector->modes[platform.modeIndex].name,
1326 platform.connector->modes[platform.modeIndex].hdisplay, platform.connector->modes[platform.modeIndex].vdisplay,
1327 FLAG_IS_SET(platform.connector->modes[platform.modeIndex].flags, DRM_MODE_FLAG_INTERLACE)? 'i' : 'p',
1328 platform.connector->modes[platform.modeIndex].vrefresh);
1329
1330 drmModeFreeEncoder(enc);
1331 enc = NULL;
1332 #else
1333 // For software rendering, the first available mode can be used
1334 if (platform.connector->count_modes > 0)
1335 {
1336 platform.modeIndex = 0;
1337 CORE.Window.display.width = platform.connector->modes[0].hdisplay;
1338 CORE.Window.display.height = platform.connector->modes[0].vdisplay;
1339
1340 TRACELOG(LOG_INFO, "DISPLAY: Selected DRM connector mode %s (%ux%u%c@%u) for software rendering",
1341 platform.connector->modes[0].name,
1342 platform.connector->modes[0].hdisplay,
1343 platform.connector->modes[0].vdisplay,
1344 (platform.connector->modes[0].flags & DRM_MODE_FLAG_INTERLACE)? 'i' : 'p',
1345 platform.connector->modes[0].vrefresh);
1346 }
1347 else
1348 {
1349 TRACELOG(LOG_WARNING, "DISPLAY: No modes available for connector");
1350 drmModeFreeConnector(platform.connector);
1351 drmModeFreeResources(res);
1352 close(platform.fd);
1353 return -1;
1354 }
1355 #endif
1356
1357 // Use the width and height of the surface for render
1358 CORE.Window.render.width = CORE.Window.screen.width;
1359 CORE.Window.render.height = CORE.Window.screen.height;
1360
1361 drmModeFreeResources(res);
1362 res = NULL;
1363
1364 #if !defined(GRAPHICS_API_OPENGL_SOFTWARE)
1365 // Hardware rendering initialization with EGL
1366 platform.gbmDevice = gbm_create_device(platform.fd);
1367 if (!platform.gbmDevice)
1368 {
1369 TRACELOG(LOG_WARNING, "DISPLAY: Failed to create GBM device");
1370 return -1;
1371 }
1372
1373 platform.gbmSurface = gbm_surface_create(platform.gbmDevice, platform.connector->modes[platform.modeIndex].hdisplay,
1374 platform.connector->modes[platform.modeIndex].vdisplay, GBM_FORMAT_ARGB8888, GBM_BO_USE_SCANOUT | GBM_BO_USE_RENDERING);
1375 if (!platform.gbmSurface)
1376 {
1377 TRACELOG(LOG_WARNING, "DISPLAY: Failed to create GBM surface");
1378 return -1;
1379 }
1380
1381 EGLint samples = 0;
1382 EGLint sampleBuffer = 0;
1383 if (FLAG_IS_SET(CORE.Window.flags, FLAG_MSAA_4X_HINT))
1384 {
1385 samples = 4;
1386 sampleBuffer = 1;
1387 TRACELOG(LOG_INFO, "DISPLAY: Trying to enable MSAA x4");
1388 }
1389
1390 const EGLint framebufferAttribs[] = {
1391 EGL_RENDERABLE_TYPE, (rlGetVersion() == RL_OPENGL_ES_30)? EGL_OPENGL_ES3_BIT : EGL_OPENGL_ES2_BIT, // Type of context support
1392 EGL_SURFACE_TYPE, EGL_WINDOW_BIT, // Don't use it on Android!
1393 EGL_RED_SIZE, 8, // RED color bit depth (alternative: 5)
1394 EGL_GREEN_SIZE, 8, // GREEN color bit depth (alternative: 6)
1395 EGL_BLUE_SIZE, 8, // BLUE color bit depth (alternative: 5)
1396 EGL_ALPHA_SIZE, 8, // ALPHA bit depth (required for transparent framebuffer)
1397 //EGL_TRANSPARENT_TYPE, EGL_NONE, // Request transparent framebuffer (EGL_TRANSPARENT_RGB does not work on RPI)
1398 EGL_DEPTH_SIZE, 24, // Depth buffer size (Required to use Depth testing!)
1399 //EGL_STENCIL_SIZE, 8, // Stencil buffer size
1400 EGL_SAMPLE_BUFFERS, sampleBuffer, // Activate MSAA
1401 EGL_SAMPLES, samples, // 4x Antialiasing if activated (Free on MALI GPUs)
1402 EGL_NONE
1403 };
1404
1405 const EGLint contextAttribs[] = {
1406 EGL_CONTEXT_CLIENT_VERSION, 2,
1407 EGL_NONE
1408 };
1409
1410 EGLint numConfigs = 0;
1411 const char *eglClientExtensions = NULL;
1412
1413 // Get an EGL device connection
1414 // NOTE: eglGetPlatformDisplay() is preferred over eglGetDisplay() legacy call
1415 platform.device = EGL_NO_DISPLAY;
1416 #if defined(EGL_VERSION_1_5)
1417 platform.device = eglGetPlatformDisplay(EGL_PLATFORM_GBM_KHR, platform.gbmDevice, NULL);
1418 #else
1419 // Check if extension is available for eglGetPlatformDisplayEXT()
1420 // NOTE: Better compatibility with some drivers (e.g. Mali Midgard)
1421 eglClientExtensions = eglQueryString(EGL_NO_DISPLAY, EGL_EXTENSIONS);
1422 if ((eglClientExtensions != NULL) && (strstr(eglClientExtensions, "EGL_EXT_platform_base") != NULL))
1423 {
1424 PFNEGLGETPLATFORMDISPLAYEXTPROC eglGetPlatformDisplayEXT = (PFNEGLGETPLATFORMDISPLAYEXTPROC)eglGetProcAddress("eglGetPlatformDisplayEXT");
1425
1426 if (eglGetPlatformDisplayEXT != NULL) platform.device = eglGetPlatformDisplayEXT(EGL_PLATFORM_GBM_KHR, platform.gbmDevice, NULL);
1427 }
1428
1429 // In case extension not found or display could not be retrieved, try using legacy version
1430 if (platform.device == EGL_NO_DISPLAY) platform.device = eglGetDisplay((EGLNativeDisplayType)platform.gbmDevice);
1431 #endif
1432 if (platform.device == EGL_NO_DISPLAY)
1433 {
1434 TRACELOG(LOG_WARNING, "DISPLAY: Failed to initialize EGL device");
1435 return -1;
1436 }
1437
1438 // Initialize the EGL device connection
1439 if (eglInitialize(platform.device, NULL, NULL) == EGL_FALSE)
1440 {
1441 // If all of the calls to eglInitialize returned EGL_FALSE then an error has occurred
1442 TRACELOG(LOG_WARNING, "DISPLAY: Failed to initialize EGL device");
1443 return -1;
1444 }
1445
1446 if (!eglChooseConfig(platform.device, NULL, NULL, 0, &numConfigs))
1447 {
1448 TRACELOG(LOG_WARNING, "DISPLAY: Failed to get EGL config count: 0x%x", eglGetError());
1449 return -1;
1450 }
1451
1452 TRACELOG(LOG_TRACE, "DISPLAY: EGL configs available: %d", numConfigs);
1453
1454 EGLConfig *configs = (EGLConfig *)RL_CALLOC(numConfigs, sizeof(*configs));
1455 if (!configs)
1456 {
1457 TRACELOG(LOG_WARNING, "DISPLAY: Failed to get memory for EGL configs");
1458 return -1;
1459 }
1460
1461 EGLint matchingNumConfigs = 0;
1462 if (!eglChooseConfig(platform.device, framebufferAttribs, configs, numConfigs, &matchingNumConfigs))
1463 {
1464 TRACELOG(LOG_WARNING, "DISPLAY: Failed to choose EGL config: 0x%x", eglGetError());
1465 RL_FREE(configs);
1466 return -1;
1467 }
1468
1469 TRACELOG(LOG_TRACE, "DISPLAY: EGL matching configs available: %d", matchingNumConfigs);
1470
1471 // find the EGL config that matches the previously setup GBM format
1472 int found = 0;
1473 for (EGLint i = 0; i < matchingNumConfigs; i++)
1474 {
1475 EGLint id = 0;
1476 if (!eglGetConfigAttrib(platform.device, configs[i], EGL_NATIVE_VISUAL_ID, &id))
1477 {
1478 TRACELOG(LOG_WARNING, "DISPLAY: Failed to get EGL config attribute: 0x%x", eglGetError());
1479 continue;
1480 }
1481
1482 if (GBM_FORMAT_ARGB8888 == id)
1483 {
1484 TRACELOG(LOG_TRACE, "DISPLAY: Using EGL config: %d", i);
1485 platform.config = configs[i];
1486 found = 1;
1487 break;
1488 }
1489 }
1490
1491 RL_FREE(configs);
1492
1493 if (!found)
1494 {
1495 TRACELOG(LOG_WARNING, "DISPLAY: Failed to find a suitable EGL config");
1496 return -1;
1497 }
1498
1499 // Set rendering API
1500 eglBindAPI(EGL_OPENGL_ES_API);
1501
1502 // Create an EGL rendering context
1503 platform.context = eglCreateContext(platform.device, platform.config, EGL_NO_CONTEXT, contextAttribs);
1504 if (platform.context == EGL_NO_CONTEXT)
1505 {
1506 TRACELOG(LOG_WARNING, "DISPLAY: Failed to create EGL context");
1507 return -1;
1508 }
1509
1510 // Create an EGL window surface
1511 platform.surface = EGL_NO_SURFACE;
1512
1513 if ((eglClientExtensions != NULL) && (strstr(eglClientExtensions, "EGL_EXT_platform_base") != NULL))
1514 {
1515 PFNEGLCREATEPLATFORMWINDOWSURFACEEXTPROC eglCreatePlatformWindowSurfaceEXT = (PFNEGLCREATEPLATFORMWINDOWSURFACEEXTPROC)eglGetProcAddress("eglCreatePlatformWindowSurfaceEXT");
1516
1517 if (eglCreatePlatformWindowSurfaceEXT != NULL) platform.surface = eglCreatePlatformWindowSurfaceEXT(platform.device, platform.config, platform.gbmSurface, NULL);
1518 }
1519
1520 if (platform.surface == EGL_NO_SURFACE)
1521 {
1522 platform.surface = eglCreateWindowSurface(platform.device, platform.config, (EGLNativeWindowType)platform.gbmSurface, NULL);
1523 }
1524
1525 if (platform.surface == EGL_NO_SURFACE)
1526 {
1527 TRACELOG(LOG_WARNING, "DISPLAY: Failed to create EGL window surface: 0x%04x", eglGetError());
1528 return -1;
1529 }
1530
1531 // At this point, manage render size vs screen size
1532 // NOTE: This function use and modify global module variables:
1533 // -> CORE.Window.screen.width/CORE.Window.screen.height
1534 // -> CORE.Window.render.width/CORE.Window.render.height
1535 // -> CORE.Window.screenScale
1536 SetupFramebuffer(CORE.Window.display.width, CORE.Window.display.height);
1537
1538 // There must be at least one frame displayed before the buffers are swapped
1539 //eglSwapInterval(platform.device, 1);
1540
1541 EGLBoolean result = eglMakeCurrent(platform.device, platform.surface, platform.surface, platform.context);
1542
1543 // Check surface and context activation
1544 if (result != EGL_FALSE)
1545 {
1546 CORE.Window.ready = true;
1547
1548 CORE.Window.render.width = CORE.Window.screen.width;
1549 CORE.Window.render.height = CORE.Window.screen.height;
1550 CORE.Window.currentFbo.width = CORE.Window.render.width;
1551 CORE.Window.currentFbo.height = CORE.Window.render.height;
1552 }
1553 else
1554 {
1555 TRACELOG(LOG_FATAL, "PLATFORM: Failed to initialize graphics device");
1556 return -1;
1557 }
1558
1559 // Load OpenGL extensions
1560 // NOTE: GL procedures address loader is required to load extensions
1561 rlLoadExtensions(eglGetProcAddress);
1562 #else
1563 // At this point, manage render size vs screen size
1564 // NOTE: This function use and modify global module variables:
1565 // -> CORE.Window.screen.width/CORE.Window.screen.height
1566 // -> CORE.Window.render.width/CORE.Window.render.height
1567 // -> CORE.Window.screenScale
1568 SetupFramebuffer(CORE.Window.display.width, CORE.Window.display.height);
1569
1570 // Setup window ready state for software rendering
1571 CORE.Window.ready = true;
1572
1573 CORE.Window.render.width = CORE.Window.screen.width;
1574 CORE.Window.render.height = CORE.Window.screen.height;
1575 CORE.Window.currentFbo.width = CORE.Window.render.width;
1576 CORE.Window.currentFbo.height = CORE.Window.render.height;
1577 #endif
1578
1579 TRACELOG(LOG_INFO, "DISPLAY: Device initialized successfully %s",
1580 FLAG_IS_SET(CORE.Window.flags, FLAG_WINDOW_HIGHDPI)? "(HighDPI)" : "");
1581 TRACELOG(LOG_INFO, " > Display size: %i x %i", CORE.Window.display.width, CORE.Window.display.height);
1582 TRACELOG(LOG_INFO, " > Screen size: %i x %i", CORE.Window.screen.width, CORE.Window.screen.height);
1583 TRACELOG(LOG_INFO, " > Render size: %i x %i", CORE.Window.render.width, CORE.Window.render.height);
1584 TRACELOG(LOG_INFO, " > Viewport offsets: %i, %i", CORE.Window.renderOffset.x, CORE.Window.renderOffset.y);
1585
1586 if (FLAG_IS_SET(CORE.Window.flags, FLAG_WINDOW_MINIMIZED)) MinimizeWindow();
1587
1588 // If graphic device is no properly initialized, end program
1589 if (!CORE.Window.ready)
1590 {
1591 TRACELOG(LOG_FATAL, "PLATFORM: Failed to initialize graphic device");
1592 return -1;
1593 }
1594 else SetWindowPosition(GetMonitorWidth(GetCurrentMonitor())/2 - CORE.Window.screen.width/2, GetMonitorHeight(GetCurrentMonitor())/2 - CORE.Window.screen.height/2);
1595
1596 // Set some default window flags
1597 FLAG_CLEAR(CORE.Window.flags, FLAG_WINDOW_HIDDEN); // false
1598 FLAG_CLEAR(CORE.Window.flags, FLAG_WINDOW_MINIMIZED); // false
1599 FLAG_SET(CORE.Window.flags, FLAG_WINDOW_MAXIMIZED); // true
1600 FLAG_CLEAR(CORE.Window.flags, FLAG_WINDOW_UNFOCUSED); // false
1601
1602 //----------------------------------------------------------------------------
1603 // Initialize timing system
1604 //----------------------------------------------------------------------------
1605 // NOTE: timing system must be initialized before the input events system
1606 InitTimer();
1607 //----------------------------------------------------------------------------
1608
1609 // Initialize input events system
1610 //----------------------------------------------------------------------------
1611 InitEvdevInput(); // Evdev inputs initialization
1612
1613 #if SUPPORT_SSH_KEYBOARD_RPI
1614 InitKeyboard(); // Keyboard init (stdin)
1615 #endif
1616 //----------------------------------------------------------------------------
1617
1618 // Initialize storage system
1619 //----------------------------------------------------------------------------
1620 CORE.Storage.basePath = GetWorkingDirectory();
1621 //----------------------------------------------------------------------------
1622
1623 #if defined(SUPPORT_DRM_CACHE)
1624 if (InitSwapScreenBuffer() == 0)
1625 {
1626 TRACELOG(LOG_INFO, "PLATFORM: DRM: Initialized successfully");
1627 return 0;
1628 }
1629 else
1630 {
1631 TRACELOG(LOG_INFO, "PLATFORM: DRM: Initialized failed");
1632 return -1;
1633 }
1634 #else // !SUPPORT_DRM_CACHE
1635 TRACELOG(LOG_INFO, "PLATFORM: DRM: Initialized successfully");
1636 return 0;
1637 #endif
1638 }
1639
1640 // Close platform
1641 void ClosePlatform(void)
1642 {
1643 if (platform.prevFB)
1644 {
1645 drmModeRmFB(platform.fd, platform.prevFB);
1646 platform.prevFB = 0;
1647 }
1648
1649 #if !defined(GRAPHICS_API_OPENGL_SOFTWARE)
1650 if (platform.prevBO)
1651 {
1652 gbm_surface_release_buffer(platform.gbmSurface, platform.prevBO);
1653 platform.prevBO = NULL;
1654 }
1655
1656 if (platform.gbmSurface)
1657 {
1658 gbm_surface_destroy(platform.gbmSurface);
1659 platform.gbmSurface = NULL;
1660 }
1661
1662 if (platform.gbmDevice)
1663 {
1664 gbm_device_destroy(platform.gbmDevice);
1665 platform.gbmDevice = NULL;
1666 }
1667 #endif
1668
1669 if (platform.crtc)
1670 {
1671 if (platform.connector)
1672 {
1673 drmModeSetCrtc(platform.fd, platform.crtc->crtc_id, platform.crtc->buffer_id,
1674 platform.crtc->x, platform.crtc->y, &platform.connector->connector_id, 1, &platform.crtc->mode);
1675 drmModeFreeConnector(platform.connector);
1676 platform.connector = NULL;
1677 }
1678
1679 drmModeFreeCrtc(platform.crtc);
1680 platform.crtc = NULL;
1681 }
1682
1683 if (platform.fd != -1)
1684 {
1685 close(platform.fd);
1686 platform.fd = -1;
1687 }
1688
1689 #if !defined(GRAPHICS_API_OPENGL_SOFTWARE)
1690 // Close surface, context and display
1691 if (platform.device != EGL_NO_DISPLAY)
1692 {
1693 if (platform.surface != EGL_NO_SURFACE)
1694 {
1695 eglDestroySurface(platform.device, platform.surface);
1696 platform.surface = EGL_NO_SURFACE;
1697 }
1698
1699 if (platform.context != EGL_NO_CONTEXT)
1700 {
1701 eglDestroyContext(platform.device, platform.context);
1702 platform.context = EGL_NO_CONTEXT;
1703 }
1704
1705 eglTerminate(platform.device);
1706 platform.device = EGL_NO_DISPLAY;
1707 }
1708 #endif
1709
1710 CORE.Window.shouldClose = true; // Added to force threads to exit when the close window is called
1711
1712 // Close the evdev devices
1713
1714 if (platform.mouseFd != -1)
1715 {
1716 close(platform.mouseFd);
1717 platform.mouseFd = -1;
1718 }
1719
1720 for (int i = 0; i < platform.gamepadCount; i++)
1721 {
1722 close(platform.gamepadStreamFd[i]);
1723 platform.gamepadStreamFd[i] = -1;
1724 }
1725
1726 if (platform.keyboardFd != -1)
1727 {
1728 close(platform.keyboardFd);
1729 platform.keyboardFd = -1;
1730 }
1731 }
1732
1733 #if SUPPORT_SSH_KEYBOARD_RPI
1734 // Initialize Keyboard system (using standard input)
1735 static void InitKeyboard(void)
1736 {
1737 // NOTE: Read directly from Standard Input (stdin) - STDIN_FILENO file descriptor,
1738 // Reading directly from stdin will give chars already key-mapped by kernel to ASCII or UNICODE
1739
1740 // Save terminal keyboard settings
1741 tcgetattr(STDIN_FILENO, &platform.defaultSettings);
1742
1743 // Reconfigure terminal with new settings
1744 struct termios keyboardNewSettings = { 0 };
1745 keyboardNewSettings = platform.defaultSettings;
1746
1747 // New terminal settings for keyboard: turn off buffering (non-canonical mode), echo and key processing
1748 // NOTE: ISIG controls if ^C and ^Z generate break signals or not
1749 FLAG_CLEAR(keyboardNewSettings.c_lflag, ICANON | ECHO | ISIG);
1750 //FLAG_CLEAR(keyboardNewSettings.c_iflag, ISTRIP | INLCR | ICRNL | IGNCR | IXON | IXOFF);
1751 keyboardNewSettings.c_cc[VMIN] = 1;
1752 keyboardNewSettings.c_cc[VTIME] = 0;
1753
1754 // Set new keyboard settings (change occurs immediately)
1755 tcsetattr(STDIN_FILENO, TCSANOW, &keyboardNewSettings);
1756
1757 // Save old keyboard mode to restore it at the end
1758 platform.defaultFileFlags = fcntl(STDIN_FILENO, F_GETFL, 0); // F_GETFL: Get the file access mode and the file status flags
1759 fcntl(STDIN_FILENO, F_SETFL, platform.defaultFileFlags | O_NONBLOCK); // F_SETFL: Set the file status flags to the value specified
1760
1761 // NOTE: If ioctl() returns -1, it means the call failed for some reason (error code set in errno)
1762 int result = ioctl(STDIN_FILENO, KDGKBMODE, &platform.defaultKeyboardMode);
1763
1764 // In case of failure, it could mean a remote keyboard is used (SSH)
1765 if (result < 0) TRACELOG(LOG_WARNING, "DRM: Failed to change keyboard mode, an SSH keyboard is probably used");
1766 else
1767 {
1768 // Reconfigure keyboard mode to get:
1769 // - scancodes (K_RAW)
1770 // - keycodes (K_MEDIUMRAW)
1771 // - ASCII chars (K_XLATE)
1772 // - UNICODE chars (K_UNICODE)
1773 ioctl(STDIN_FILENO, KDSKBMODE, K_XLATE); // ASCII chars
1774 }
1775
1776 // Register keyboard restore when program finishes
1777 atexit(RestoreKeyboard);
1778 }
1779
1780 // Restore default keyboard input
1781 static void RestoreKeyboard(void)
1782 {
1783 // Reset to default keyboard settings
1784 tcsetattr(STDIN_FILENO, TCSANOW, &platform.defaultSettings);
1785
1786 // Reconfigure keyboard to default mode
1787 fcntl(STDIN_FILENO, F_SETFL, platform.defaultFileFlags);
1788 ioctl(STDIN_FILENO, KDSKBMODE, platform.defaultKeyboardMode);
1789 }
1790
1791 // Process keyboard inputs
1792 static void ProcessKeyboard(void)
1793 {
1794 #define MAX_KEYBUFFER_SIZE 32 // Max size in bytes to read
1795
1796 // Keyboard input polling (fill keys[256] array with status)
1797 int bufferByteCount = 0; // Bytes available on the buffer
1798 char keysBuffer[MAX_KEYBUFFER_SIZE] = { 0 }; // Max keys to be read at a time
1799
1800 // Read availables keycodes from stdin
1801 bufferByteCount = read(STDIN_FILENO, keysBuffer, MAX_KEYBUFFER_SIZE); // POSIX system call
1802
1803 // Reset pressed keys array (it will be filled below)
1804 for (int i = 0; i < MAX_KEYBOARD_KEYS; i++)
1805 {
1806 CORE.Input.Keyboard.currentKeyState[i] = 0;
1807 CORE.Input.Keyboard.keyRepeatInFrame[i] = 0;
1808 }
1809
1810 // Fill all read bytes (looking for keys)
1811 for (int i = 0; i < bufferByteCount; i++)
1812 {
1813 // NOTE: If (key == 0x1b), depending on next key, it could be a special keymap code!
1814 // Up -> 1b 5b 41 / Left -> 1b 5b 44 / Right -> 1b 5b 43 / Down -> 1b 5b 42
1815 if (keysBuffer[i] == 0x1b)
1816 {
1817 // Check if ESCAPE key has been pressed to stop program
1818 if (bufferByteCount == 1) CORE.Input.Keyboard.currentKeyState[CORE.Input.Keyboard.exitKey] = 1;
1819 else
1820 {
1821 if (keysBuffer[i + 1] == 0x5b) // Special function key
1822 {
1823 if ((keysBuffer[i + 2] == 0x5b) || (keysBuffer[i + 2] == 0x31) || (keysBuffer[i + 2] == 0x32))
1824 {
1825 // Process special function keys (F1 - F12)
1826 switch (keysBuffer[i + 3])
1827 {
1828 case 0x41: CORE.Input.Keyboard.currentKeyState[290] = 1; break; // raylib KEY_F1
1829 case 0x42: CORE.Input.Keyboard.currentKeyState[291] = 1; break; // raylib KEY_F2
1830 case 0x43: CORE.Input.Keyboard.currentKeyState[292] = 1; break; // raylib KEY_F3
1831 case 0x44: CORE.Input.Keyboard.currentKeyState[293] = 1; break; // raylib KEY_F4
1832 case 0x45: CORE.Input.Keyboard.currentKeyState[294] = 1; break; // raylib KEY_F5
1833 case 0x37: CORE.Input.Keyboard.currentKeyState[295] = 1; break; // raylib KEY_F6
1834 case 0x38: CORE.Input.Keyboard.currentKeyState[296] = 1; break; // raylib KEY_F7
1835 case 0x39: CORE.Input.Keyboard.currentKeyState[297] = 1; break; // raylib KEY_F8
1836 case 0x30: CORE.Input.Keyboard.currentKeyState[298] = 1; break; // raylib KEY_F9
1837 case 0x31: CORE.Input.Keyboard.currentKeyState[299] = 1; break; // raylib KEY_F10
1838 case 0x33: CORE.Input.Keyboard.currentKeyState[300] = 1; break; // raylib KEY_F11
1839 case 0x34: CORE.Input.Keyboard.currentKeyState[301] = 1; break; // raylib KEY_F12
1840 default: break;
1841 }
1842
1843 if (keysBuffer[i + 2] == 0x5b) i += 4;
1844 else if ((keysBuffer[i + 2] == 0x31) || (keysBuffer[i + 2] == 0x32)) i += 5;
1845 }
1846 else
1847 {
1848 switch (keysBuffer[i + 2])
1849 {
1850 case 0x41: CORE.Input.Keyboard.currentKeyState[265] = 1; break; // raylib KEY_UP
1851 case 0x42: CORE.Input.Keyboard.currentKeyState[264] = 1; break; // raylib KEY_DOWN
1852 case 0x43: CORE.Input.Keyboard.currentKeyState[262] = 1; break; // raylib KEY_RIGHT
1853 case 0x44: CORE.Input.Keyboard.currentKeyState[263] = 1; break; // raylib KEY_LEFT
1854 default: break;
1855 }
1856
1857 i += 3; // Jump to next key
1858 }
1859
1860 // NOTE: Some keys are not directly keymapped (CTRL, ALT, SHIFT)
1861 }
1862 }
1863 }
1864 else if (keysBuffer[i] == 0x0a) // raylib KEY_ENTER (don't mix with <linux/input.h> KEY_*)
1865 {
1866 CORE.Input.Keyboard.currentKeyState[257] = 1;
1867
1868 CORE.Input.Keyboard.keyPressedQueue[CORE.Input.Keyboard.keyPressedQueueCount] = 257; // Add keys pressed into queue
1869 CORE.Input.Keyboard.keyPressedQueueCount++;
1870 }
1871 else if (keysBuffer[i] == 0x7f) // raylib KEY_BACKSPACE
1872 {
1873 CORE.Input.Keyboard.currentKeyState[259] = 1;
1874
1875 CORE.Input.Keyboard.keyPressedQueue[CORE.Input.Keyboard.keyPressedQueueCount] = 259; // Add keys pressed into queue
1876 CORE.Input.Keyboard.keyPressedQueueCount++;
1877 }
1878 else
1879 {
1880 // Translate lowercase a-z letters to A-Z
1881 if ((keysBuffer[i] >= 97) && (keysBuffer[i] <= 122))
1882 {
1883 CORE.Input.Keyboard.currentKeyState[(int)keysBuffer[i] - 32] = 1;
1884 }
1885 else CORE.Input.Keyboard.currentKeyState[(int)keysBuffer[i]] = 1;
1886
1887 CORE.Input.Keyboard.keyPressedQueue[CORE.Input.Keyboard.keyPressedQueueCount] = keysBuffer[i]; // Add keys pressed into queue
1888 CORE.Input.Keyboard.keyPressedQueueCount++;
1889 }
1890 }
1891 }
1892 #endif // SUPPORT_SSH_KEYBOARD_RPI
1893
1894 // Initialize user input from evdev(/dev/input/event<N>)
1895 // this means mouse, keyboard or gamepad devices
1896 static void InitEvdevInput(void)
1897 {
1898 char path[MAX_FILEPATH_LENGTH] = { 0 };
1899 DIR *directory = NULL;
1900 struct dirent *entity = NULL;
1901
1902 // Initialize keyboard file descriptor
1903 platform.keyboardFd = -1;
1904 platform.mouseFd = -1;
1905
1906 // Reset variables
1907 for (int i = 0; i < MAX_TOUCH_POINTS; i++)
1908 {
1909 CORE.Input.Touch.position[i].x = -1;
1910 CORE.Input.Touch.position[i].y = -1;
1911 platform.touchActive[i] = false;
1912 platform.touchPosition[i].x = -1;
1913 platform.touchPosition[i].y = -1;
1914 platform.touchId[i] = -1;
1915 }
1916
1917 // Initialize touch slot
1918 platform.touchSlot = 0;
1919
1920 // Reset keyboard key state
1921 for (int i = 0; i < MAX_KEYBOARD_KEYS; i++)
1922 {
1923 CORE.Input.Keyboard.currentKeyState[i] = 0;
1924 CORE.Input.Keyboard.keyRepeatInFrame[i] = 0;
1925 }
1926
1927 // Open the linux directory of "/dev/input"
1928 directory = opendir(DEFAULT_EVDEV_PATH);
1929
1930 if (directory)
1931 {
1932 while ((entity = readdir(directory)) != NULL)
1933 {
1934 if ((strncmp("event", entity->d_name, strlen("event")) == 0) || // Search for devices named "event*"
1935 (strncmp("mouse", entity->d_name, strlen("mouse")) == 0)) // Search for devices named "mouse*"
1936 {
1937 snprintf(path, MAX_FILEPATH_LENGTH, "%s%s", DEFAULT_EVDEV_PATH, entity->d_name);
1938 ConfigureEvdevDevice(path); // Configure the device if appropriate
1939 }
1940 }
1941
1942 closedir(directory);
1943 }
1944 else TRACELOG(LOG_WARNING, "INPUT: Failed to open linux event directory: %s", DEFAULT_EVDEV_PATH);
1945 }
1946
1947 // Identifies a input device and configures it for use if appropriate
1948 static void ConfigureEvdevDevice(char *device)
1949 {
1950 #define BITS_PER_LONG (8*sizeof(long))
1951 #define NBITS(x) ((((x) - 1)/BITS_PER_LONG) + 1)
1952 #define OFF(x) ((x)%BITS_PER_LONG)
1953 #define BIT(x) (1UL<<OFF(x))
1954 #define LONG(x) ((x)/BITS_PER_LONG)
1955 #define TEST_BIT(array, bit) ((array[LONG(bit)] >> OFF(bit)) & 1)
1956
1957 unsigned long evBits[NBITS(EV_MAX)] = { 0 };
1958 unsigned long absBits[NBITS(ABS_MAX)] = { 0 };
1959 unsigned long relBits[NBITS(REL_MAX)] = { 0 };
1960 unsigned long keyBits[NBITS(KEY_MAX)] = { 0 };
1961
1962 // Open the device
1963 int fd = open(device, O_RDONLY | O_NONBLOCK);
1964 if (fd < 0)
1965 {
1966 TRACELOG(LOG_WARNING, "SYSTEM: Failed to open input device: %s", device);
1967 return;
1968 }
1969
1970 // At this point, a connection to the device has been stablished, but still left to know what the device is,
1971 // it could be many things, even as simple as a power button...
1972 //-------------------------------------------------------------------------------------------------------
1973
1974 // Identify the device
1975 //-------------------------------------------------------------------------------------------------------
1976 struct {
1977 bool exist;
1978 struct input_absinfo info;
1979 } absinfo[ABS_CNT] = { 0 };
1980
1981 // These flags aren't really a one of
1982 // Some devices could have properties associated with keyboards
1983 // as well as properties associated with mice
1984 bool isKeyboard = false;
1985 bool isMouse = false;
1986 bool isTouch = false;
1987 bool isGamepad = false;
1988
1989 int absAxisCount = 0;
1990
1991 ioctl(fd, EVIOCGBIT(0, sizeof(evBits)), evBits);
1992 ioctl(fd, EVIOCGBIT(EV_KEY, sizeof(keyBits)), keyBits);
1993
1994 if (TEST_BIT(evBits, EV_ABS))
1995 {
1996 ioctl(fd, EVIOCGBIT(EV_ABS, sizeof(absBits)), absBits);
1997
1998 // If the device has an X an Y axis it's either a touch device, a special mouse or a gamepad
1999 bool hasAbsXY = TEST_BIT(absBits, ABS_X) && TEST_BIT(absBits, ABS_Y);
2000
2001 if (hasAbsXY)
2002 {
2003 absAxisCount += 2;
2004
2005 absinfo[ABS_X].exist = true;
2006 absinfo[ABS_Y].exist = true;
2007
2008 ioctl(fd, EVIOCGABS(ABS_X), &absinfo[ABS_X].info);
2009 ioctl(fd, EVIOCGABS(ABS_Y), &absinfo[ABS_Y].info);
2010 }
2011
2012 // If it has any of these buttons it's a touch device
2013 if (hasAbsXY &&
2014 (TEST_BIT(keyBits, BTN_STYLUS) ||
2015 TEST_BIT(keyBits, BTN_TOOL_PEN) ||
2016 TEST_BIT(keyBits, BTN_TOOL_FINGER) ||
2017 TEST_BIT(keyBits, BTN_TOUCH))) isTouch = true;
2018
2019 // Absolute mice should really only exist with VMWare
2020 else if (hasAbsXY && TEST_BIT(keyBits, BTN_MOUSE)) isMouse = true;
2021
2022 // If any of the common joystick axes are present, assume it's a gamepad
2023 else
2024 {
2025 for (int axis = (hasAbsXY? ABS_Z : ABS_X); axis < ABS_PRESSURE; axis++)
2026 {
2027 if (TEST_BIT(absBits, axis))
2028 {
2029 absinfo[axis].exist = true;
2030 isGamepad = true;
2031 absAxisCount++;
2032
2033 ioctl(fd, EVIOCGABS(axis), &absinfo[axis].info);
2034 }
2035 }
2036 }
2037
2038 // If the device has multitouch axes, it's a touch device
2039 if (TEST_BIT(absBits, ABS_MT_POSITION_X) &&
2040 TEST_BIT(absBits, ABS_MT_POSITION_Y)) isTouch = true;
2041 }
2042
2043 if (TEST_BIT(evBits, EV_REL))
2044 {
2045 ioctl(fd, EVIOCGBIT(EV_REL, sizeof(relBits)), relBits);
2046
2047 // If it has any of the gamepad or touch features tested so far, it's not a mouse
2048 if (!isTouch &&
2049 !isGamepad &&
2050 TEST_BIT(relBits, REL_X) &&
2051 TEST_BIT(relBits, REL_Y) &&
2052 TEST_BIT(keyBits, BTN_MOUSE)) isMouse = true;
2053 }
2054
2055 if (TEST_BIT(evBits, EV_KEY))
2056 {
2057 // The first 32 keys as defined in input-event-codes.h are pretty much
2058 // exclusive to keyboards, so they can be tested using a mask
2059 // Leave out the first bit to not test KEY_RESERVED
2060 const unsigned long mask = 0xFFFFFFFE;
2061 if ((keyBits[0] & mask) == mask) isKeyboard = true;
2062
2063 // If any of the common gamepad buttons is found, assume it's a gamepad
2064 else
2065 {
2066 for (int button = BTN_JOYSTICK; button < BTN_DIGI; ++button)
2067 {
2068 if (TEST_BIT(keyBits, button)) isGamepad = true;
2069 }
2070
2071 for (int button = BTN_TRIGGER_HAPPY1; button <= BTN_TRIGGER_HAPPY40; button++)
2072 {
2073 if (TEST_BIT(keyBits, button)) isGamepad = true;
2074 }
2075 }
2076 }
2077
2078 const char *deviceKindStr = "unknown";
2079 if (isMouse || isTouch)
2080 {
2081 bool prioritize = false;
2082
2083 // Priority logic: touchscreens override Mice
2084 // 1. No device set yet? Take it
2085 if (platform.mouseFd == -1) prioritize = true;
2086 // 2. Current is mouse, new is touch? Upgrade to touch
2087 else if (isTouch && !platform.mouseIsTouch) prioritize = true;
2088 // 3. Current is touch, new is touch? Use the new one (last one found wins, standard behavior)
2089 else if (isTouch && platform.mouseIsTouch) prioritize = true;
2090 // 4. Current is mouse, new is mouse? Use the new one
2091 else if (!isTouch && !platform.mouseIsTouch) prioritize = true;
2092 // 5. Current is touch, new is mouse? Ignore the mouse, keep the touchscreen
2093 else prioritize = false;
2094
2095 if (prioritize)
2096 {
2097 deviceKindStr = isTouch? "touchscreen" : "mouse";
2098
2099 if (platform.mouseFd != -1)
2100 {
2101 TRACELOG(LOG_INFO, "INPUT: Overwriting previous input device with new %s", deviceKindStr);
2102 close(platform.mouseFd);
2103 }
2104
2105 platform.mouseFd = fd;
2106 platform.mouseIsTouch = isTouch;
2107
2108 if (absAxisCount > 0)
2109 {
2110 platform.absRange.x = absinfo[ABS_X].info.minimum;
2111 platform.absRange.width = absinfo[ABS_X].info.maximum - absinfo[ABS_X].info.minimum;
2112
2113 platform.absRange.y = absinfo[ABS_Y].info.minimum;
2114 platform.absRange.height = absinfo[ABS_Y].info.maximum - absinfo[ABS_Y].info.minimum;
2115 }
2116
2117 TRACELOG(LOG_INFO, "INPUT: Initialized input device %s as %s", device, deviceKindStr);
2118 }
2119 else
2120 {
2121 TRACELOG(LOG_INFO, "INPUT: Ignoring device %s (keeping higher priority %s device)", device, platform.mouseIsTouch ? "touchscreen" : "mouse");
2122 close(fd);
2123 return;
2124 }
2125 }
2126 else if (isGamepad && !isMouse && !isKeyboard && (platform.gamepadCount < MAX_GAMEPADS))
2127 {
2128 deviceKindStr = "gamepad";
2129 int index = platform.gamepadCount++;
2130
2131 platform.gamepadStreamFd[index] = fd;
2132 CORE.Input.Gamepad.ready[index] = true;
2133
2134 ioctl(platform.gamepadStreamFd[index], EVIOCGNAME(64), &CORE.Input.Gamepad.name[index]);
2135 CORE.Input.Gamepad.axisCount[index] = absAxisCount;
2136
2137 if (absAxisCount > 0)
2138 {
2139 // TODO: Review GamepadAxis enum matching
2140 // So gamepad axes (as in the actual linux joydev.c) are simply enumerated
2141 // and (at least for some input drivers like xpat) it's convention to use
2142 // ABS_X, ABX_Y for one joystick ABS_RX, ABS_RY for the other and the Z axes for the shoulder buttons
2143 // If these are now enumerated, it results to LJOY_X, LJOY_Y, LEFT_SHOULDERB, RJOY_X, ...
2144 int axisIndex = 0;
2145 for (int axis = ABS_X; axis < ABS_PRESSURE; axis++)
2146 {
2147 if (absinfo[axis].exist)
2148 {
2149 platform.gamepadAbsAxisRange[index][axisIndex][0] = absinfo[axisIndex].info.minimum;
2150 platform.gamepadAbsAxisRange[index][axisIndex][1] = absinfo[axisIndex].info.maximum - absinfo[axisIndex].info.minimum;
2151
2152 platform.gamepadAbsAxisMap[index][axis] = axisIndex;
2153 axisIndex++;
2154 }
2155 }
2156 }
2157 }
2158 else if (isKeyboard && (platform.keyboardFd == -1))
2159 {
2160 deviceKindStr = "keyboard";
2161 platform.keyboardFd = fd;
2162 }
2163 else
2164 {
2165 close(fd);
2166 return;
2167 }
2168
2169 TRACELOG(LOG_INFO, "INPUT: Initialized input device %s as %s", device, deviceKindStr);
2170 }
2171
2172 // Poll and process evdev keyboard events
2173 static void PollKeyboardEvents(void)
2174 {
2175 int fd = platform.keyboardFd;
2176 if (fd == -1) return;
2177
2178 struct input_event event = { 0 };
2179 int keycode = -1;
2180
2181 // Try to read data from the keyboard and only continue if successful
2182 while (read(fd, &event, sizeof(event)) == (int)sizeof(event))
2183 {
2184 // Check if the event is a key event
2185 if (event.type != EV_KEY) continue;
2186
2187 #if SUPPORT_SSH_KEYBOARD_RPI
2188 // If the event was a key, assume a working keyboard is connected, so disable the SSH keyboard
2189 platform.eventKeyboardMode = true;
2190 #endif
2191 // Keyboard keys appear for codes 1 to 255, ignore everthing else
2192 if ((event.code >= 1) && (event.code <= 255))
2193 {
2194 // Lookup the scancode in the keymap to get a keycode
2195 keycode = linuxToRaylibMap[event.code];
2196
2197 // Make sure a valid keycode is obtained
2198 if ((keycode > 0) && (keycode < MAX_KEYBOARD_KEYS))
2199 {
2200 // WARNING: https://www.kernel.org/doc/Documentation/input/input.txt
2201 // Event interface: 'value' is the value the event carries. Either a relative change for EV_REL,
2202 // absolute new value for EV_ABS (joysticks ...), or 0 for EV_KEY for release, 1 for keypress and 2 for autorepeat
2203 CORE.Input.Keyboard.currentKeyState[keycode] = (event.value >= 1);
2204 CORE.Input.Keyboard.keyRepeatInFrame[keycode] = (event.value == 2);
2205
2206 // If the key is pressed add it to the queues
2207 if (event.value == 1)
2208 {
2209 if (CORE.Input.Keyboard.keyPressedQueueCount < MAX_CHAR_PRESSED_QUEUE)
2210 {
2211 CORE.Input.Keyboard.keyPressedQueue[CORE.Input.Keyboard.keyPressedQueueCount] = keycode;
2212 CORE.Input.Keyboard.keyPressedQueueCount++;
2213 }
2214
2215 if (CORE.Input.Keyboard.charPressedQueueCount < MAX_CHAR_PRESSED_QUEUE)
2216 {
2217 // TODO/FIXME: This is not actually converting to unicode properly because it's not taking things like shift into account
2218 CORE.Input.Keyboard.charPressedQueue[CORE.Input.Keyboard.charPressedQueueCount] = evkeyToUnicodeLUT[event.code];
2219 CORE.Input.Keyboard.charPressedQueueCount++;
2220 }
2221 }
2222
2223 TRACELOG(LOG_DEBUG, "INPUT: KEY_%s Keycode(linux): %4i KeyCode(raylib): %4i", (event.value == 0)? "UP " : "DOWN", event.code, keycode);
2224 }
2225 }
2226 }
2227 }
2228
2229 // Poll gamepad input events
2230 static void PollGamepadEvents(void)
2231 {
2232 // Read gamepad event
2233 struct input_event event = { 0 };
2234
2235 for (int i = 0; i < platform.gamepadCount; i++)
2236 {
2237 if (!CORE.Input.Gamepad.ready[i]) continue;
2238
2239 // Register previous gamepad states
2240 for (int k = 0; k < MAX_GAMEPAD_BUTTONS; k++) CORE.Input.Gamepad.previousButtonState[i][k] = CORE.Input.Gamepad.currentButtonState[i][k];
2241
2242 while (read(platform.gamepadStreamFd[i], &event, sizeof(event)) == (int)sizeof(event))
2243 {
2244 if (event.type == EV_KEY)
2245 {
2246 if (event.code < KEYMAP_SIZE)
2247 {
2248 short keycode = linuxToRaylibMap[event.code]; // raylib keycode
2249
2250 TRACELOG(LOG_DEBUG, "INPUT: Gamepad %2i: KEY_%s Keycode(linux): %4i Keycode(raylib): %4i", i, (event.value == 0)? "UP" : "DOWN", event.code, keycode);
2251
2252 if ((keycode != 0) && (keycode < MAX_GAMEPAD_BUTTONS))
2253 {
2254 // 1 - button pressed, 0 - button released
2255 CORE.Input.Gamepad.currentButtonState[i][keycode] = event.value;
2256 CORE.Input.Gamepad.lastButtonPressed = (event.value == 1)? keycode : GAMEPAD_BUTTON_UNKNOWN;
2257 }
2258 }
2259 }
2260 else if (event.type == EV_ABS)
2261 {
2262 if (event.code < ABS_CNT)
2263 {
2264 int axisRaylib = platform.gamepadAbsAxisMap[i][event.code];
2265
2266 TRACELOG(LOG_DEBUG, "INPUT: Gamepad %2i: Axis: %2i Value: %i", i, axisRaylib, event.value);
2267
2268 if (axisRaylib < MAX_GAMEPAD_AXES)
2269 {
2270 int min = platform.gamepadAbsAxisRange[i][event.code][0];
2271 int range = platform.gamepadAbsAxisRange[i][event.code][1];
2272
2273 // NOTE: Scaling of event.value to get values between -1..1
2274 CORE.Input.Gamepad.axisState[i][axisRaylib] = (2*(float)(event.value - min)/range) - 1;
2275 }
2276 }
2277 }
2278 }
2279 }
2280 }
2281
2282 // Poll mouse input events
2283 static void PollMouseEvents(void)
2284 {
2285 int fd = platform.mouseFd;
2286 if (fd == -1) return;
2287
2288 struct input_event event = { 0 };
2289 int touchAction = -1; // 0-TOUCH_ACTION_UP, 1-TOUCH_ACTION_DOWN, 2-TOUCH_ACTION_MOVE
2290 static bool isMultitouch = false; // Detect if device supports MT events
2291
2292 // Try to read data from the mouse/touch/gesture and only continue if successful
2293 while (read(fd, &event, sizeof(event)) == (int)sizeof(event))
2294 {
2295 // Relative movement parsing
2296 if (event.type == EV_REL)
2297 {
2298 if (event.code == REL_X)
2299 {
2300 if (platform.cursorRelative)
2301 {
2302 CORE.Input.Mouse.currentPosition.x = event.value;
2303 CORE.Input.Mouse.previousPosition.x = 0.0f;
2304 }
2305 else CORE.Input.Mouse.currentPosition.x += event.value;
2306
2307 // NOTE: For DRM touchscreen, do not simulate touch from mouse movement
2308 // CORE.Input.Touch.position[0].x = CORE.Input.Mouse.currentPosition.x;
2309 touchAction = 2; // TOUCH_ACTION_MOVE
2310 }
2311
2312 if (event.code == REL_Y)
2313 {
2314 if (platform.cursorRelative)
2315 {
2316 CORE.Input.Mouse.currentPosition.y = event.value;
2317 CORE.Input.Mouse.previousPosition.y = 0.0f;
2318 }
2319 else CORE.Input.Mouse.currentPosition.y += event.value;
2320
2321 // NOTE: For DRM touchscreen, do not simulate touch from mouse movement
2322 // CORE.Input.Touch.position[0].y = CORE.Input.Mouse.currentPosition.y;
2323 touchAction = 2; // TOUCH_ACTION_MOVE
2324 }
2325
2326 if (event.code == REL_WHEEL) platform.eventWheelMove.y += event.value;
2327 }
2328
2329 // Absolute movement parsing
2330 if (event.type == EV_ABS)
2331 {
2332 // Basic movement
2333 if (event.code == ABS_X)
2334 {
2335 CORE.Input.Mouse.currentPosition.x = (event.value - platform.absRange.x)*CORE.Window.screen.width/platform.absRange.width; // Scale according to absRange
2336
2337 // Update single touch position only if it's active and no MT events are being used
2338 if (platform.touchActive[0] && !isMultitouch)
2339 {
2340 platform.touchPosition[0].x = (event.value - platform.absRange.x)*CORE.Window.screen.width/platform.absRange.width;
2341 if (touchAction == -1) touchAction = 2; // TOUCH_ACTION_MOVE
2342 }
2343 }
2344
2345 if (event.code == ABS_Y)
2346 {
2347 CORE.Input.Mouse.currentPosition.y = (event.value - platform.absRange.y)*CORE.Window.screen.height/platform.absRange.height; // Scale according to absRange
2348
2349 // Update single touch position only if it's active and no MT events are being used
2350 if (platform.touchActive[0] && !isMultitouch)
2351 {
2352 platform.touchPosition[0].y = (event.value - platform.absRange.y)*CORE.Window.screen.height/platform.absRange.height;
2353 if (touchAction == -1) touchAction = 2; // TOUCH_ACTION_MOVE
2354 }
2355 }
2356
2357 // Multitouch movement
2358 if (event.code == ABS_MT_SLOT)
2359 {
2360 platform.touchSlot = event.value;
2361 isMultitouch = true;
2362 }
2363
2364 if (event.code == ABS_MT_POSITION_X)
2365 {
2366 isMultitouch = true;
2367 if (platform.touchSlot < MAX_TOUCH_POINTS)
2368 {
2369 platform.touchPosition[platform.touchSlot].x = (event.value - platform.absRange.x)*CORE.Window.screen.width/platform.absRange.width;
2370
2371 // If this slot is active, it's a move; If not, update the buffer for when it becomes active
2372 // Only set to MOVE if a DOWN or UP event has not been detected this frame
2373 if (platform.touchActive[platform.touchSlot] && touchAction == -1) touchAction = 2; // TOUCH_ACTION_MOVE
2374 }
2375 }
2376
2377 if (event.code == ABS_MT_POSITION_Y)
2378 {
2379 if (platform.touchSlot < MAX_TOUCH_POINTS)
2380 {
2381 platform.touchPosition[platform.touchSlot].y = (event.value - platform.absRange.y)*CORE.Window.screen.height/platform.absRange.height;
2382
2383 // If this slot is active, it's a move; If not, update the buffer for when it becomes active
2384 // Only set to MOVE if a DOWN or UP event have not been detected this frame
2385 if (platform.touchActive[platform.touchSlot] && touchAction == -1) touchAction = 2; // TOUCH_ACTION_MOVE
2386 }
2387 }
2388
2389 if (event.code == ABS_MT_TRACKING_ID)
2390 {
2391 if (platform.touchSlot < MAX_TOUCH_POINTS)
2392 {
2393 if (event.value >= 0)
2394 {
2395
2396 platform.touchActive[platform.touchSlot] = true;
2397 platform.touchId[platform.touchSlot] = event.value; // Use Tracking ID for unique IDs
2398
2399 touchAction = 1; // TOUCH_ACTION_DOWN
2400 }
2401 else
2402 {
2403 // Touch has ended for this point
2404 platform.touchActive[platform.touchSlot] = false;
2405 platform.touchPosition[platform.touchSlot].x = -1;
2406 platform.touchPosition[platform.touchSlot].y = -1;
2407 platform.touchId[platform.touchSlot] = -1;
2408
2409 // Force UP action if DOWN action has not already been set
2410 // (DOWN takes priority over UP if both happen in one frame, though rare)
2411 if (touchAction != 1) touchAction = 0; // TOUCH_ACTION_UP
2412 }
2413 }
2414 }
2415
2416 // Handle ABS_MT_PRESSURE (0x3a) if available, as some devices use it for lift-off
2417 #ifndef ABS_MT_PRESSURE
2418 #define ABS_MT_PRESSURE 0x3a
2419 #endif
2420 if (event.code == ABS_MT_PRESSURE)
2421 {
2422 if (platform.touchSlot < MAX_TOUCH_POINTS)
2423 {
2424 if (event.value <= 0) // Pressure 0 means lift
2425 {
2426 platform.touchActive[platform.touchSlot] = false;
2427 platform.touchPosition[platform.touchSlot].x = -1;
2428 platform.touchPosition[platform.touchSlot].y = -1;
2429 platform.touchId[platform.touchSlot] = -1;
2430 if (touchAction != 1) touchAction = 0; // TOUCH_ACTION_UP
2431 }
2432 }
2433 }
2434
2435 // Touchscreen tap
2436 if (event.code == ABS_PRESSURE)
2437 {
2438 int previousMouseLeftButtonState = platform.currentButtonStateEvdev[MOUSE_BUTTON_LEFT];
2439
2440 if (!event.value && previousMouseLeftButtonState)
2441 {
2442 platform.currentButtonStateEvdev[MOUSE_BUTTON_LEFT] = 0;
2443 if (touchAction != 1) touchAction = 0; // TOUCH_ACTION_UP
2444 }
2445
2446 if (event.value && !previousMouseLeftButtonState)
2447 {
2448 platform.currentButtonStateEvdev[MOUSE_BUTTON_LEFT] = 1;
2449 touchAction = 1; // TOUCH_ACTION_DOWN
2450 }
2451 }
2452 }
2453
2454 // Button parsing
2455 if (event.type == EV_KEY)
2456 {
2457 // Mouse button parsing
2458 if ((event.code == BTN_TOUCH) || (event.code == BTN_LEFT))
2459 {
2460 platform.currentButtonStateEvdev[MOUSE_BUTTON_LEFT] = event.value;
2461
2462 if (event.value > 0)
2463 {
2464 bool activateSlot0 = false;
2465
2466 if (event.code == BTN_LEFT) activateSlot0 = true; // Mouse click always activates
2467 else if (event.code == BTN_TOUCH)
2468 {
2469 bool anyActive = false;
2470 for (int i = 0; i < MAX_TOUCH_POINTS; i++)
2471 {
2472 if (platform.touchActive[i]) { anyActive = true; break; }
2473 }
2474
2475 if (!anyActive) activateSlot0 = true;
2476 }
2477
2478 if (activateSlot0)
2479 {
2480 platform.touchActive[0] = true;
2481 platform.touchId[0] = 0;
2482 }
2483
2484 touchAction = 1; // TOUCH_ACTION_DOWN
2485 }
2486 else
2487 {
2488 // Only clear touch 0 for actual mouse clicks (BTN_LEFT)
2489 if (event.code == BTN_LEFT)
2490 {
2491 platform.touchActive[0] = false;
2492 platform.touchPosition[0].x = -1;
2493 platform.touchPosition[0].y = -1;
2494 }
2495 else if (event.code == BTN_TOUCH) platform.touchSlot = 0; // Reset slot index to 0
2496
2497 touchAction = 0; // TOUCH_ACTION_UP
2498 }
2499 }
2500
2501 if (event.code == BTN_RIGHT) platform.currentButtonStateEvdev[MOUSE_BUTTON_RIGHT] = event.value;
2502 if (event.code == BTN_MIDDLE) platform.currentButtonStateEvdev[MOUSE_BUTTON_MIDDLE] = event.value;
2503 if (event.code == BTN_SIDE) platform.currentButtonStateEvdev[MOUSE_BUTTON_SIDE] = event.value;
2504 if (event.code == BTN_EXTRA) platform.currentButtonStateEvdev[MOUSE_BUTTON_EXTRA] = event.value;
2505 if (event.code == BTN_FORWARD) platform.currentButtonStateEvdev[MOUSE_BUTTON_FORWARD] = event.value;
2506 if (event.code == BTN_BACK) platform.currentButtonStateEvdev[MOUSE_BUTTON_BACK] = event.value;
2507 }
2508
2509 // Screen confinement
2510 if (!CORE.Input.Mouse.cursorLocked)
2511 {
2512 if (CORE.Input.Mouse.currentPosition.x < 0) CORE.Input.Mouse.currentPosition.x = 0;
2513 if (CORE.Input.Mouse.currentPosition.x > CORE.Window.screen.width/CORE.Input.Mouse.scale.x)
2514 CORE.Input.Mouse.currentPosition.x = CORE.Window.screen.width/CORE.Input.Mouse.scale.x;
2515
2516 if (CORE.Input.Mouse.currentPosition.y < 0) CORE.Input.Mouse.currentPosition.y = 0;
2517 if (CORE.Input.Mouse.currentPosition.y > CORE.Window.screen.height/CORE.Input.Mouse.scale.y)
2518 CORE.Input.Mouse.currentPosition.y = CORE.Window.screen.height/CORE.Input.Mouse.scale.y;
2519 }
2520
2521 // Repack active touches into CORE.Input.Touch
2522 int k = 0;
2523 for (int i = 0; i < MAX_TOUCH_POINTS; i++)
2524 {
2525 if (platform.touchActive[i])
2526 {
2527 CORE.Input.Touch.position[k] = platform.touchPosition[i];
2528 CORE.Input.Touch.pointId[k] = platform.touchId[i];
2529 k++;
2530 }
2531 }
2532
2533 CORE.Input.Touch.pointCount = k;
2534
2535 // Clear remaining slots
2536 for (int i = k; i < MAX_TOUCH_POINTS; i++)
2537 {
2538 CORE.Input.Touch.position[i].x = -1;
2539 CORE.Input.Touch.position[i].y = -1;
2540 CORE.Input.Touch.pointId[i] = -1;
2541 }
2542
2543 #if SUPPORT_GESTURES_SYSTEM
2544 if (touchAction > -1)
2545 {
2546 GestureEvent gestureEvent = { 0 };
2547 gestureEvent.touchAction = touchAction;
2548 gestureEvent.pointCount = CORE.Input.Touch.pointCount;
2549
2550 for (int i = 0; i < MAX_TOUCH_POINTS; i++)
2551 {
2552 gestureEvent.pointId[i] = i;
2553 gestureEvent.position[i] = CORE.Input.Touch.position[i];
2554 }
2555
2556 ProcessGestureEvent(gestureEvent);
2557 touchAction = -1;
2558 }
2559 #endif
2560 }
2561 }
2562
2563 // Search matching DRM mode in connector's mode list
2564 static int FindMatchingConnectorMode(const drmModeConnector *connector, const drmModeModeInfo *mode)
2565 {
2566 if (NULL == connector) return -1;
2567 if (NULL == mode) return -1;
2568
2569 // safe bitwise comparison of two modes
2570 #define BINCMP(a, b) memcmp((a), (b), (sizeof(a) < sizeof(b))? sizeof(a) : sizeof(b))
2571
2572 for (size_t i = 0; i < connector->count_modes; i++)
2573 {
2574 TRACELOG(LOG_TRACE, "DISPLAY: DRM mode: %d %ux%u@%u %s", i, connector->modes[i].hdisplay, connector->modes[i].vdisplay,
2575 connector->modes[i].vrefresh, (FLAG_IS_SET(connector->modes[i].flags, DRM_MODE_FLAG_INTERLACE) > 0)? "interlaced" : "progressive");
2576
2577 if (0 == BINCMP(&platform.crtc->mode, &platform.connector->modes[i])) return i;
2578 }
2579
2580 return -1;
2581
2582 #undef BINCMP
2583 }
2584
2585 // Search exactly matching DRM connector mode in connector's list
2586 static int FindExactConnectorMode(const drmModeConnector *connector, uint width, uint height, uint fps, bool allowInterlaced)
2587 {
2588 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");
2589
2590 if (NULL == connector) return -1;
2591
2592 for (int i = 0; i < platform.connector->count_modes; i++)
2593 {
2594 const drmModeModeInfo *const mode = &platform.connector->modes[i];
2595
2596 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");
2597
2598 if ((FLAG_IS_SET(mode->flags, DRM_MODE_FLAG_INTERLACE) > 0) && !allowInterlaced) continue;
2599
2600 if ((mode->hdisplay == width) && (mode->vdisplay == height) && (mode->vrefresh == fps)) return i;
2601 }
2602
2603 TRACELOG(LOG_TRACE, "DISPLAY: No DRM exact matching mode found");
2604 return -1;
2605 }
2606
2607 // Search the nearest matching DRM connector mode in connector's list
2608 static int FindNearestConnectorMode(const drmModeConnector *connector, uint width, uint height, uint fps, bool allowInterlaced)
2609 {
2610 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");
2611
2612 if (NULL == connector) return -1;
2613
2614 int nearestIndex = -1;
2615 int minUnusedPixels = INT_MAX;
2616 int minFpsDiff = INT_MAX;
2617 for (int i = 0; i < platform.connector->count_modes; i++)
2618 {
2619 const drmModeModeInfo *const mode = &platform.connector->modes[i];
2620
2621 TRACELOG(LOG_TRACE, "DISPLAY: DRM mode: %d %ux%u@%u %s", i, mode->hdisplay, mode->vdisplay, mode->vrefresh,
2622 (FLAG_IS_SET(mode->flags, DRM_MODE_FLAG_INTERLACE) > 0)? "interlaced" : "progressive");
2623
2624 if ((mode->hdisplay < width) || (mode->vdisplay < height))
2625 {
2626 TRACELOG(LOG_TRACE, "DISPLAY: DRM mode is too small");
2627 continue;
2628 }
2629
2630 if ((FLAG_IS_SET(mode->flags, DRM_MODE_FLAG_INTERLACE) > 0) && !allowInterlaced)
2631 {
2632 TRACELOG(LOG_TRACE, "DISPLAY: DRM shouldn't choose an interlaced mode");
2633 continue;
2634 }
2635
2636 const int unusedPixels = (mode->hdisplay - width)*(mode->vdisplay - height);
2637 const int fpsDiff = mode->vrefresh - fps;
2638
2639 if ((unusedPixels < minUnusedPixels) ||
2640 ((unusedPixels == minUnusedPixels) && (abs(fpsDiff) < abs(minFpsDiff))) ||
2641 ((unusedPixels == minUnusedPixels) && (abs(fpsDiff) == abs(minFpsDiff)) && (fpsDiff > 0)))
2642 {
2643 nearestIndex = i;
2644 minUnusedPixels = unusedPixels;
2645 minFpsDiff = fpsDiff;
2646 }
2647 }
2648
2649 return nearestIndex;
2650 }
2651
2652 // Compute framebuffer size relative to screen size and display size
2653 // NOTE: Global variables CORE.Window.render.width/CORE.Window.render.height and CORE.Window.renderOffset.x/CORE.Window.renderOffset.y can be modified
2654 static void SetupFramebuffer(int width, int height)
2655 {
2656 // Calculate CORE.Window.render.width and CORE.Window.render.height, using the display size (input params) and the desired screen size (global var)
2657 if ((CORE.Window.screen.width > CORE.Window.display.width) || (CORE.Window.screen.height > CORE.Window.display.height))
2658 {
2659 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);
2660
2661 // Downscaling to fit display with border-bars
2662 float widthRatio = (float)CORE.Window.display.width/(float)CORE.Window.screen.width;
2663 float heightRatio = (float)CORE.Window.display.height/(float)CORE.Window.screen.height;
2664
2665 if (widthRatio <= heightRatio)
2666 {
2667 CORE.Window.render.width = CORE.Window.display.width;
2668 CORE.Window.render.height = (int)round((float)CORE.Window.screen.height*widthRatio);
2669 CORE.Window.renderOffset.x = 0;
2670 CORE.Window.renderOffset.y = (CORE.Window.display.height - CORE.Window.render.height);
2671 }
2672 else
2673 {
2674 CORE.Window.render.width = (int)round((float)CORE.Window.screen.width*heightRatio);
2675 CORE.Window.render.height = CORE.Window.display.height;
2676 CORE.Window.renderOffset.x = (CORE.Window.display.width - CORE.Window.render.width);
2677 CORE.Window.renderOffset.y = 0;
2678 }
2679
2680 // Screen scaling required
2681 float scaleRatio = (float)CORE.Window.render.width/(float)CORE.Window.screen.width;
2682 CORE.Window.screenScale = MatrixScale(scaleRatio, scaleRatio, 1.0f);
2683
2684 // NOTE: Rendering to full display resolution,
2685 // calculate above parameters for downscale matrix and offsets
2686 CORE.Window.render.width = CORE.Window.display.width;
2687 CORE.Window.render.height = CORE.Window.display.height;
2688
2689 TRACELOG(LOG_WARNING, "DISPLAY: Downscale matrix generated, content will be rendered at (%ix%i)", CORE.Window.render.width, CORE.Window.render.height);
2690 }
2691 else if ((CORE.Window.screen.width < CORE.Window.display.width) || (CORE.Window.screen.height < CORE.Window.display.height))
2692 {
2693 // Required screen size is smaller than display size
2694 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);
2695
2696 if ((CORE.Window.screen.width == 0) || (CORE.Window.screen.height == 0))
2697 {
2698 CORE.Window.screen.width = CORE.Window.display.width;
2699 CORE.Window.screen.height = CORE.Window.display.height;
2700 }
2701
2702 // Upscaling to fit display with border-bars
2703 float displayRatio = (float)CORE.Window.display.width/(float)CORE.Window.display.height;
2704 float screenRatio = (float)CORE.Window.screen.width/(float)CORE.Window.screen.height;
2705
2706 if (displayRatio <= screenRatio)
2707 {
2708 CORE.Window.render.width = CORE.Window.screen.width;
2709 CORE.Window.render.height = (int)round((float)CORE.Window.screen.width/displayRatio);
2710 CORE.Window.renderOffset.x = 0;
2711 CORE.Window.renderOffset.y = (CORE.Window.render.height - CORE.Window.screen.height);
2712 }
2713 else
2714 {
2715 CORE.Window.render.width = (int)round((float)CORE.Window.screen.height*displayRatio);
2716 CORE.Window.render.height = CORE.Window.screen.height;
2717 CORE.Window.renderOffset.x = (CORE.Window.render.width - CORE.Window.screen.width);
2718 CORE.Window.renderOffset.y = 0;
2719 }
2720 }
2721 else
2722 {
2723 CORE.Window.render.width = CORE.Window.screen.width;
2724 CORE.Window.render.height = CORE.Window.screen.height;
2725 CORE.Window.renderOffset.x = 0;
2726 CORE.Window.renderOffset.y = 0;
2727 }
2728 }
2729
2730 // EOF