Debian Codegraph @

src/rcore.c

raw symbols SCIP
1 /**********************************************************************************************
2 *
3 * rcore - Window/display management, Graphic device/context management and input management
4 *
5 * PLATFORMS SUPPORTED:
6 * > PLATFORM_DESKTOP_GLFW (GLFW backend):
7 * - Windows (Win32, Win64)
8 * - Linux (X11/Wayland desktop mode)
9 * - macOS/OSX (x64, arm64)
10 * - FreeBSD, OpenBSD, NetBSD, DragonFly (X11 desktop)
11 * > PLATFORM_DESKTOP_SDL (SDL backend):
12 * - Windows (Win32, Win64)
13 * - Linux (X11/Wayland desktop mode)
14 * - Others (not tested)
15 * > PLATFORM_DESKTOP_RGFW (RGFW backend):
16 * - Windows (Win32, Win64)
17 * - Linux (X11/Wayland desktop mode)
18 * - macOS/OSX (x64, arm64)
19 * - Others (not tested)
20 * > PLATFORM_DESKTOP_WIN32 (native Win32):
21 * - Windows (Win32, Win64)
22 * > PLATFORM_WEB (GLFW + Emscripten):
23 * - HTML5 (WebAssembly)
24 * > PLATFORM_WEB_EMSCRIPTEN (Emscripten):
25 * - HTML5 (WebAssembly)
26 * > PLATFORM_WEB_RGFW (Emscripten):
27 * - HTML5 (WebAssembly)
28 * > PLATFORM_DRM (native DRM):
29 * - Raspberry Pi 0-5 (DRM/KMS)
30 * - Linux DRM subsystem (KMS mode)
31 * - Embedded devices (with GPU)
32 * > PLATFORM_ANDROID (native NDK):
33 * - Android (ARM, ARM64)
34 * > PLATFORM_MEMORY
35 * - Memory framebuffer output, using software renderer, no OS required
36 *
37 * CONFIGURATION:
38 * #define SUPPORT_CAMERA_SYSTEM 1
39 * Camera module is included (rcamera.h) and multiple predefined cameras are available:
40 * free, 1st/3rd person, orbital, custom
41 *
42 * #define SUPPORT_GESTURES_SYSTEM 1
43 * Gestures module is included (rgestures.h) to support gestures detection: tap, hold, swipe, drag
44 *
45 * #define SUPPORT_MOUSE_GESTURES 1
46 * Mouse gestures are directly mapped like touches and processed by gestures system
47 *
48 * #define SUPPORT_BUSY_WAIT_LOOP 1
49 * Use busy wait loop for timing sync, if not defined, a high-resolution timer is setup and used
50 *
51 * #define SUPPORT_PARTIALBUSY_WAIT_LOOP 0
52 * Use a partial-busy wait loop, in this case frame sleeps for most of the time and runs a busy-wait-loop at the end
53 *
54 * #define SUPPORT_SCREEN_CAPTURE 1
55 * Allow automatic screen capture of current screen pressing F12, defined in KeyCallback()
56 *
57 * #define SUPPORT_COMPRESSION_API 1
58 * Support CompressData() and DecompressData() functions, those functions use zlib implementation
59 * provided by stb_image and stb_image_write libraries, so, those libraries must be enabled on textures module
60 * for linkage
61 *
62 * #define SUPPORT_AUTOMATION_EVENTS 1
63 * Support automatic events recording and playing, useful for automated testing systems or AI based game playing
64 *
65 * DEPENDENCIES:
66 * raymath - 3D math functionality (Vector2, Vector3, Matrix, Quaternion)
67 * camera - Multiple 3D camera modes (free, orbital, 1st person, 3rd person)
68 * gestures - Gestures system for touch-ready devices (or simulated from mouse inputs)
69 *
70 *
71 * LICENSE: zlib/libpng
72 *
73 * Copyright (c) 2013-2026 Ramon Santamaria (@raysan5) and contributors
74 *
75 * This software is provided "as-is", without any express or implied warranty. In no event
76 * will the authors be held liable for any damages arising from the use of this software.
77 *
78 * Permission is granted to anyone to use this software for any purpose, including commercial
79 * applications, and to alter it and redistribute it freely, subject to the following restrictions:
80 *
81 * 1. The origin of this software must not be misrepresented; you must not claim that you
82 * wrote the original software. If you use this software in a product, an acknowledgment
83 * in the product documentation would be appreciated but is not required.
84 *
85 * 2. Altered source versions must be plainly marked as such, and must not be misrepresented
86 * as being the original software.
87 *
88 * 3. This notice may not be removed or altered from any source distribution.
89 *
90 **********************************************************************************************/
91
92 //----------------------------------------------------------------------------------
93 // Feature Test Macros required for this module
94 //----------------------------------------------------------------------------------
95 #if (defined(__linux__) || defined(PLATFORM_WEB) || defined(PLATFORM_WEB_RGFW)) && (_XOPEN_SOURCE < 500)
96 #undef _XOPEN_SOURCE
97 #define _XOPEN_SOURCE 500 // Required for: readlink if compiled with c99 without GNU extensions
98 #endif
99
100 #if (defined(__linux__) || defined(PLATFORM_WEB) || defined(PLATFORM_WEB_RGFW)) && (_POSIX_C_SOURCE < 199309L)
101 #undef _POSIX_C_SOURCE
102 #define _POSIX_C_SOURCE 199309L // Required for: CLOCK_MONOTONIC if compiled with c99 without GNU extensions
103 #endif
104
105 #include "raylib.h" // Declares module functions
106
107 #include "config.h" // Defines module configuration flags
108
109 #include <stdlib.h> // Required for: srand(), rand(), atexit(), exit()
110 #include <stdio.h> // Required for: FILE, fopen(), fseek(), ftell(), fread(), fwrite(), fprintf(), vprintf(), fclose(), sprintf() [Used in OpenURL()]
111 #include <string.h> // Required for: strlen(), strncpy(), strcmp(), strrchr(), memset(), strcat()
112 #include <stdarg.h> // Required for: va_list, va_start(), va_end() [Used in TraceLog()]
113 #include <time.h> // Required for: time() [Used in InitTimer()]
114 #include <math.h> // Required for: tan() [Used in BeginMode3D()], atan2f() [Used in LoadVrStereoConfig()]
115
116 #if defined(PLATFORM_MEMORY) || defined(PLATFORM_WEB)
117 #define SW_GL_FRAMEBUFFER_COPY_BGRA false
118 #endif
119 #define RLGL_IMPLEMENTATION
120 #include "rlgl.h" // OpenGL abstraction layer to OpenGL 1.1, 3.3+ or ES2
121
122 #define RAYMATH_IMPLEMENTATION
123 #include "raymath.h" // Vector2, Vector3, Quaternion and Matrix functionality
124
125 #if SUPPORT_GESTURES_SYSTEM
126 #define RGESTURES_IMPLEMENTATION
127 #include "rgestures.h" // Gestures detection functionality
128 #endif
129
130 #if SUPPORT_CAMERA_SYSTEM
131 #define RCAMERA_IMPLEMENTATION
132 #include "rcamera.h" // Camera system functionality
133 #endif
134
135 #if SUPPORT_COMPRESSION_API
136 #define SINFL_IMPLEMENTATION
137 #define SINFL_NO_SIMD
138 #include "external/sinfl.h" // Deflate (RFC 1951) decompressor
139
140 #define SDEFL_IMPLEMENTATION
141 #include "external/sdefl.h" // Deflate (RFC 1951) compressor
142 #endif
143
144 #if SUPPORT_RPRAND_GENERATOR
145 #define RPRAND_IMPLEMENTATION
146 #include "external/rprand.h"
147 #endif
148
149 #if defined(__linux__) && !defined(_GNU_SOURCE)
150 #define _GNU_SOURCE
151 #endif
152
153 // Platform specific defines to handle GetApplicationDirectory()
154 #if defined(_WIN32)
155 #if !defined(MAX_PATH)
156 #define MAX_PATH 260
157 #endif
158
159 struct HINSTANCE__;
160 #if defined(__cplusplus)
161 extern "C" {
162 #endif
163 __declspec(dllimport) unsigned long __stdcall GetModuleFileNameA(struct HINSTANCE__ *hModule, char *lpFilename, unsigned long nSize);
164 __declspec(dllimport) unsigned long __stdcall GetModuleFileNameW(struct HINSTANCE__ *hModule, wchar_t *lpFilename, unsigned long nSize);
165 __declspec(dllimport) int __stdcall WideCharToMultiByte(unsigned int cp, unsigned long flags, const wchar_t *widestr, int cchwide, char *str, int cbmb, const char *defchar, int *used_default);
166 __declspec(dllimport) unsigned int __stdcall timeBeginPeriod(unsigned int uPeriod);
167 __declspec(dllimport) unsigned int __stdcall timeEndPeriod(unsigned int uPeriod);
168 #if defined(__cplusplus)
169 }
170 #endif
171 #elif defined(__linux__)
172 #include <unistd.h>
173 #elif defined(__FreeBSD__)
174 #include <sys/types.h>
175 #include <sys/sysctl.h>
176 #include <unistd.h>
177 #elif defined(__APPLE__)
178 #include <sys/syslimits.h>
179 #include <mach-o/dyld.h>
180 #endif
181
182 #define _CRT_INTERNAL_NONSTDC_NAMES 1
183 #include <sys/stat.h> // Required for: stat(), S_ISREG [Used in GetFileModTime(), IsFilePath()]
184
185 #if !defined(S_ISREG) && defined(S_IFMT) && defined(S_IFREG)
186 #define S_ISREG(m) (((m) & S_IFMT) == S_IFREG)
187 #endif
188
189 #if defined(_WIN32) && (defined(_MSC_VER) || defined(__TINYC__))
190 #define DIRENT_MALLOC RL_MALLOC
191 #define DIRENT_FREE RL_FREE
192
193 #include "external/dirent.h" // Required for: DIR, opendir(), closedir() [Used in LoadDirectoryFiles()]
194 #else
195 #include <dirent.h> // Required for: DIR, opendir(), closedir() [Used in LoadDirectoryFiles()]
196 #endif
197
198 #if defined(_WIN32)
199 #include <io.h> // Required for: _access() [Used in FileExists()]
200 #include <direct.h> // Required for: _getch(), _chdir(), _mkdir()
201 #define GETCWD _getcwd // NOTE: MSDN recommends not to use getcwd(), chdir()
202 #define CHDIR _chdir
203 #define MKDIR(dir) _mkdir(dir)
204 #define ACCESS(fn) _access(fn, 0)
205 #else
206 #include <unistd.h> // Required for: getch(), chdir(), mkdir(), access()
207 #define GETCWD getcwd
208 #define CHDIR chdir
209 #define MKDIR(dir) mkdir(dir, 0777)
210 #define ACCESS(fn) access(fn, F_OK)
211 #endif
212
213 //----------------------------------------------------------------------------------
214 // Defines and Macros
215 //----------------------------------------------------------------------------------
216 #ifndef MAX_TRACELOG_MSG_LENGTH
217 #define MAX_TRACELOG_MSG_LENGTH 256 // Max length of one trace-log message
218 #endif
219
220 #ifndef MAX_FILEPATH_CAPACITY
221 #define MAX_FILEPATH_CAPACITY 8192 // Maximum capacity for filepath
222 #endif
223 #ifndef MAX_FILEPATH_LENGTH
224 #if defined(_WIN32)
225 #define MAX_FILEPATH_LENGTH 256 // On Win32, MAX_PATH = 260 (limits.h) but Windows 10, Version 1607 enables long paths...
226 #else
227 #define MAX_FILEPATH_LENGTH 4096 // On Linux, PATH_MAX = 4096 by default (limits.h)
228 #endif
229 #endif
230
231 #ifndef MAX_KEYBOARD_KEYS
232 #define MAX_KEYBOARD_KEYS 512 // Maximum number of keyboard keys supported
233 #endif
234 #ifndef MAX_MOUSE_BUTTONS
235 #define MAX_MOUSE_BUTTONS 8 // Maximum number of mouse buttons supported
236 #endif
237 #ifndef MAX_GAMEPADS
238 #define MAX_GAMEPADS 4 // Maximum number of gamepads supported
239 #endif
240 #ifndef MAX_GAMEPAD_NAME_LENGTH
241 #define MAX_GAMEPAD_NAME_LENGTH 128 // Maximum number of characters in a gamepad name (byte size)
242 #endif
243 #ifndef MAX_GAMEPAD_AXES
244 #define MAX_GAMEPAD_AXES 8 // Maximum number of axes supported (per gamepad)
245 #endif
246 #ifndef MAX_GAMEPAD_BUTTONS
247 #define MAX_GAMEPAD_BUTTONS 32 // Maximum number of buttons supported (per gamepad)
248 #endif
249 #ifndef MAX_GAMEPAD_VIBRATION_TIME
250 #define MAX_GAMEPAD_VIBRATION_TIME 2.0f // Maximum vibration time in seconds
251 #endif
252 #ifndef MAX_TOUCH_POINTS
253 #define MAX_TOUCH_POINTS 8 // Maximum number of touch points supported
254 #endif
255 #ifndef MAX_KEY_PRESSED_QUEUE
256 #define MAX_KEY_PRESSED_QUEUE 16 // Maximum number of keys in the key input queue
257 #endif
258 #ifndef MAX_CHAR_PRESSED_QUEUE
259 #define MAX_CHAR_PRESSED_QUEUE 16 // Maximum number of characters in the char input queue
260 #endif
261
262 #ifndef MAX_DECOMPRESSION_SIZE
263 #define MAX_DECOMPRESSION_SIZE 64 // Maximum size allocated for decompression in MB
264 #endif
265
266 #ifndef MAX_AUTOMATION_EVENTS
267 #define MAX_AUTOMATION_EVENTS 16384 // Maximum number of automation events to record
268 #endif
269
270 // File and directory scan filters
271 // NOTE: Used in ScanDirectoryFiles(), LoadDirectoryFilesEx() and GetDirectoryFileCountEx()
272 // WARNING: Custom file filters can be specified but following raylib IsFileExtension() convention: ".png;.wav;.glb"
273 #ifndef FILE_FILTER_TAG_ALL
274 #define FILE_FILTER_TAG_ALL "*.*" // Filter to include all file types and directories on scan
275 #endif
276 #ifndef FILE_FILTER_TAG_FILE_ONLY
277 #define FILE_FILTER_TAG_FILE_ONLY "FILES*" // Filter to include all file types on scan (no directories)
278 #endif
279 #ifndef FILE_FILTER_TAG_DIR_ONLY
280 #define FILE_FILTER_TAG_DIR_ONLY "DIRS*" // Filter to include only directories on scan
281 #endif
282
283 // Flags bitwise operation macros
284 #define FLAG_SET(n, f) ((n) |= (f))
285 #define FLAG_CLEAR(n, f) ((n) &= ~(f))
286 #define FLAG_TOGGLE(n, f) ((n) ^= (f))
287 #define FLAG_IS_SET(n, f) (((n) & (f)) == (f))
288
289 //----------------------------------------------------------------------------------
290 // Types and Structures Definition
291 //----------------------------------------------------------------------------------
292 typedef struct { int x; int y; } Point;
293 typedef struct { unsigned int width; unsigned int height; } Size;
294
295 // Core global state context data
296 typedef struct CoreData {
297 struct {
298 const char *title; // Window text title const pointer
299 unsigned int flags; // Configuration flags (bit based), keeps window state
300 bool ready; // Check if window has been initialized successfully
301 bool shouldClose; // Check if window set for closing
302 bool resizedLastFrame; // Check if window has been resized last frame
303 bool eventWaiting; // Wait for events before ending frame
304 bool usingFbo; // Using FBO (RenderTexture) for rendering instead of default framebuffer
305
306 Size display; // Display width and height (monitor, device-screen, LCD, ...)
307 Size screen; // Screen current width and height
308 Point position; // Window current position
309 Size previousScreen; // Screen previous width and height (required on fullscreen/borderless-windowed toggle)
310 Point previousPosition; // Window previous position (required on fullscreen/borderless-windowed toggle)
311 Size render; // Screen framebuffer width and height
312 Point renderOffset; // Screen framebuffer render offset (Not required anymore?)
313 Size currentFbo; // Current framebuffer render width and height (depends on active render texture)
314 Size screenMin; // Screen minimum width and height (for resizable window)
315 Size screenMax; // Screen maximum width and height (for resizable window)
316 Matrix screenScale; // Matrix to scale screen (framebuffer rendering)
317
318 char **dropFilepaths; // Store dropped files paths pointers (provided by GLFW)
319 unsigned int dropFileCount; // Count dropped files strings
320
321 } Window;
322 struct {
323 const char *basePath; // Base path for data storage
324
325 } Storage;
326 struct {
327 struct {
328 int exitKey; // Default exit key
329 char currentKeyState[MAX_KEYBOARD_KEYS]; // Registers current frame key state
330 char previousKeyState[MAX_KEYBOARD_KEYS]; // Registers previous frame key state
331
332 // NOTE: Since key press logic involves comparing previous vs current key state,
333 // key repeats needs to be handled specially
334 char keyRepeatInFrame[MAX_KEYBOARD_KEYS]; // Registers key repeats for current frame
335
336 int keyPressedQueue[MAX_KEY_PRESSED_QUEUE]; // Input keys queue
337 int keyPressedQueueCount; // Input keys queue count
338
339 int charPressedQueue[MAX_CHAR_PRESSED_QUEUE]; // Input characters queue (unicode)
340 int charPressedQueueCount; // Input characters queue count
341
342 } Keyboard;
343 struct {
344 Vector2 offset; // Mouse offset
345 Vector2 scale; // Mouse scaling
346 Vector2 currentPosition; // Mouse position on screen
347 Vector2 previousPosition; // Previous mouse position
348 Vector2 lockedPosition; // Mouse position when locked
349
350 int cursor; // Tracks current mouse cursor
351 bool cursorHidden; // Track if cursor is hidden
352 bool cursorLocked; // Track if cursor is locked (disabled)
353 bool cursorOnScreen; // Tracks if cursor is inside client area
354
355 char currentButtonState[MAX_MOUSE_BUTTONS]; // Registers current mouse button state
356 char previousButtonState[MAX_MOUSE_BUTTONS]; // Registers previous mouse button state
357 Vector2 currentWheelMove; // Registers current mouse wheel variation
358 Vector2 previousWheelMove; // Registers previous mouse wheel variation
359
360 } Mouse;
361 struct {
362 int pointCount; // Number of touch points active
363 int pointId[MAX_TOUCH_POINTS]; // Point identifiers
364 Vector2 position[MAX_TOUCH_POINTS]; // Touch position on screen
365 Vector2 previousPosition[MAX_TOUCH_POINTS]; // Previous touch position on screen
366 char currentTouchState[MAX_TOUCH_POINTS]; // Registers current touch state
367 char previousTouchState[MAX_TOUCH_POINTS]; // Registers previous touch state
368
369 } Touch;
370 struct {
371 int lastButtonPressed; // Register last gamepad button pressed
372 int axisCount[MAX_GAMEPADS]; // Register number of available gamepad axes
373 bool ready[MAX_GAMEPADS]; // Flag to know if gamepad is ready
374 char name[MAX_GAMEPADS][MAX_GAMEPAD_NAME_LENGTH]; // Gamepad name holder
375 char currentButtonState[MAX_GAMEPADS][MAX_GAMEPAD_BUTTONS]; // Current gamepad buttons state
376 char previousButtonState[MAX_GAMEPADS][MAX_GAMEPAD_BUTTONS]; // Previous gamepad buttons state
377 float axisState[MAX_GAMEPADS][MAX_GAMEPAD_AXES]; // Gamepad axes state
378
379 } Gamepad;
380 } Input;
381 struct {
382 double current; // Current time measure (seconds)
383 double previous; // Previous time measure (seconds)
384 double update; // Time measure for frame update (seconds)
385 double draw; // Time measure for frame draw (seconds)
386 double frame; // Time measure for one frame (seconds)
387 double target; // Desired time for one frame, if 0 not applied (seconds)
388 unsigned long long int base; // Base time measure for hi-res timer (ticks or nanoseconds)
389 unsigned int frameCounter; // Frame counter (frames)
390
391 } Time;
392 } CoreData;
393
394 //----------------------------------------------------------------------------------
395 // Global Variables Definition
396 //----------------------------------------------------------------------------------
397 RLAPI const char *raylib_version = RAYLIB_VERSION; // raylib version exported symbol, required for some bindings
398
399 CoreData CORE = { 0 }; // Global CORE state context
400
401 static int logTypeLevel = LOG_INFO; // Minimum log type level
402
403 static TraceLogCallback traceLog = NULL; // TraceLog callback function pointer
404 static LoadFileDataCallback loadFileData = NULL; // LoadFileData callback function pointer
405 static SaveFileDataCallback saveFileData = NULL; // SaveFileText callback function pointer
406 static LoadFileTextCallback loadFileText = NULL; // LoadFileText callback function pointer
407 static SaveFileTextCallback saveFileText = NULL; // SaveFileText callback function pointer
408
409 #if SUPPORT_SCREEN_CAPTURE
410 static int screenshotCounter = 0; // Screenshots counter
411 #endif
412
413 #if SUPPORT_AUTOMATION_EVENTS
414 // Automation events type
415 typedef enum AutomationEventType {
416 EVENT_NONE = 0,
417 // Input events
418 INPUT_KEY_UP, // param[0]: key
419 INPUT_KEY_DOWN, // param[0]: key
420 INPUT_KEY_PRESSED, // param[0]: key
421 INPUT_KEY_RELEASED, // param[0]: key
422 INPUT_MOUSE_BUTTON_UP, // param[0]: button
423 INPUT_MOUSE_BUTTON_DOWN, // param[0]: button
424 INPUT_MOUSE_POSITION, // param[0]: x, param[1]: y
425 INPUT_MOUSE_WHEEL_MOTION, // param[0]: x delta, param[1]: y delta
426 INPUT_GAMEPAD_CONNECT, // param[0]: gamepad
427 INPUT_GAMEPAD_DISCONNECT, // param[0]: gamepad
428 INPUT_GAMEPAD_BUTTON_UP, // param[0]: button
429 INPUT_GAMEPAD_BUTTON_DOWN, // param[0]: button
430 INPUT_GAMEPAD_AXIS_MOTION, // param[0]: axis, param[1]: delta
431 INPUT_TOUCH_UP, // param[0]: id
432 INPUT_TOUCH_DOWN, // param[0]: id
433 INPUT_TOUCH_POSITION, // param[0]: x, param[1]: y
434 INPUT_GESTURE, // param[0]: gesture
435 // Window events
436 WINDOW_CLOSE, // no params
437 WINDOW_MAXIMIZE, // no params
438 WINDOW_MINIMIZE, // no params
439 WINDOW_RESIZE, // param[0]: width, param[1]: height
440 // Custom events
441 ACTION_TAKE_SCREENSHOT, // no params
442 ACTION_SETTARGETFPS // param[0]: fps
443 } AutomationEventType;
444
445 // Event type to config events flags
446 // WARNING: Not used at the moment
447 typedef enum {
448 EVENT_INPUT_KEYBOARD = 0,
449 EVENT_INPUT_MOUSE = 1,
450 EVENT_INPUT_GAMEPAD = 2,
451 EVENT_INPUT_TOUCH = 4,
452 EVENT_INPUT_GESTURE = 8,
453 EVENT_WINDOW = 16,
454 EVENT_CUSTOM = 32
455 } EventType;
456
457 // Event type name strings, required for export
458 static const char *autoEventTypeName[] = {
459 "EVENT_NONE",
460 "INPUT_KEY_UP",
461 "INPUT_KEY_DOWN",
462 "INPUT_KEY_PRESSED",
463 "INPUT_KEY_RELEASED",
464 "INPUT_MOUSE_BUTTON_UP",
465 "INPUT_MOUSE_BUTTON_DOWN",
466 "INPUT_MOUSE_POSITION",
467 "INPUT_MOUSE_WHEEL_MOTION",
468 "INPUT_GAMEPAD_CONNECT",
469 "INPUT_GAMEPAD_DISCONNECT",
470 "INPUT_GAMEPAD_BUTTON_UP",
471 "INPUT_GAMEPAD_BUTTON_DOWN",
472 "INPUT_GAMEPAD_AXIS_MOTION",
473 "INPUT_TOUCH_UP",
474 "INPUT_TOUCH_DOWN",
475 "INPUT_TOUCH_POSITION",
476 "INPUT_GESTURE",
477 "WINDOW_CLOSE",
478 "WINDOW_MAXIMIZE",
479 "WINDOW_MINIMIZE",
480 "WINDOW_RESIZE",
481 "ACTION_TAKE_SCREENSHOT",
482 "ACTION_SETTARGETFPS"
483 };
484
485 /*
486 // Automation event (24 bytes)
487 // NOTE: Opaque struct, internal to raylib
488 struct AutomationEvent {
489 unsigned int frame; // Event frame
490 unsigned int type; // Event type (AutomationEventType)
491 int params[4]; // Event parameters (if required)
492 };
493 */
494
495 static AutomationEventList *currentEventList = NULL; // Current automation events list, set by user, keep internal pointer
496 static bool automationEventRecording = false; // Recording automation events flag
497 //static short automationEventEnabled = 0b0000001111111111; // TODO: Automation events enabled for recording/playing
498 #endif
499 //-----------------------------------------------------------------------------------
500
501 //----------------------------------------------------------------------------------
502 // Module Functions Declaration
503 // NOTE: Those functions are common for all platforms!
504 //----------------------------------------------------------------------------------
505 #if SUPPORT_MODULE_RTEXT
506 extern void LoadFontDefault(void); // [Module: text] Loads default font on InitWindow()
507 extern void UnloadFontDefault(void); // [Module: text] Unloads default font from GPU memory
508 #endif
509
510 extern int InitPlatform(void); // Initialize platform (graphics, inputs and more)
511 extern void ClosePlatform(void); // Close platform
512
513 static void InitTimer(void); // Initialize timer, hi-resolution if available (required by InitPlatform())
514 static void SetupViewport(int width, int height); // Set viewport for a provided width and height
515
516 static void ScanDirectoryFiles(const char *basePath, FilePathList *list, const char *filter, unsigned int expectedFileCount, bool scanSubdirs); // Scan all files and directories in a base path
517
518 #if SUPPORT_AUTOMATION_EVENTS
519 static void RecordAutomationEvent(void); // Record frame events (to internal events array)
520 #endif
521
522 #if defined(_WIN32) && !defined(PLATFORM_DESKTOP_RGFW)
523 // NOTE: Declaring Sleep() function symbol to avoid including windows.h (kernel32.lib linkage required)
524 __declspec(dllimport) void __stdcall Sleep(unsigned long msTimeout); // Required for: WaitTime()
525 #endif
526
527 #if !SUPPORT_MODULE_RTEXT
528 const char *TextFormat(const char *text, ...); // Formatting of text with variables to 'embed'
529 #endif
530
531 #if defined(PLATFORM_DESKTOP)
532 #define PLATFORM_DESKTOP_GLFW
533 #endif
534
535
536 // Include platform-specific submodules
537 #if defined(PLATFORM_DESKTOP_GLFW)
538 #include "platforms/rcore_desktop_glfw.c"
539 #elif defined(PLATFORM_DESKTOP_SDL)
540 #include "platforms/rcore_desktop_sdl.c"
541 #elif (defined(PLATFORM_DESKTOP_RGFW) || defined(PLATFORM_WEB_RGFW))
542 #include "platforms/rcore_desktop_rgfw.c"
543 #elif defined(PLATFORM_DESKTOP_WIN32)
544 #include "platforms/rcore_desktop_win32.c"
545 #elif defined(PLATFORM_WEB)
546 #include "platforms/rcore_web.c"
547 #elif defined(PLATFORM_DRM)
548 #include "platforms/rcore_drm.c"
549 #elif defined(PLATFORM_ANDROID)
550 #include "platforms/rcore_android.c"
551 #elif defined(PLATFORM_MEMORY)
552 #include "platforms/rcore_memory.c"
553 #else
554 // TODO: Include your custom platform backend!
555 // i.e software rendering backend or console backend!
556 #pragma message ("WARNING: No [rcore] platform defined")
557 #endif
558
559 //----------------------------------------------------------------------------------
560 // Module Functions Definition: Window and Graphics Device
561 //----------------------------------------------------------------------------------
562
563 // NOTE: Functions with a platform-specific implementation on rcore_<platform>.c
564 //bool WindowShouldClose(void)
565 //void ToggleFullscreen(void)
566 //void ToggleBorderlessWindowed(void)
567 //void MaximizeWindow(void)
568 //void MinimizeWindow(void)
569 //void RestoreWindow(void)
570
571 //void SetWindowState(unsigned int flags)
572 //void ClearWindowState(unsigned int flags)
573
574 //void SetWindowIcon(Image image)
575 //void SetWindowIcons(Image *images, int count)
576 //void SetWindowTitle(const char *title)
577 //void SetWindowPosition(int x, int y)
578 //void SetWindowMonitor(int monitor)
579 //void SetWindowMinSize(int width, int height)
580 //void SetWindowMaxSize(int width, int height)
581 //void SetWindowSize(int width, int height)
582 //void SetWindowOpacity(float opacity)
583 //void SetWindowFocused(void)
584 //void *GetWindowHandle(void)
585 //Vector2 GetWindowPosition(void)
586 //Vector2 GetWindowScaleDPI(void)
587
588 //int GetMonitorCount(void)
589 //int GetCurrentMonitor(void)
590 //int GetMonitorWidth(int monitor)
591 //int GetMonitorHeight(int monitor)
592 //int GetMonitorPhysicalWidth(int monitor)
593 //int GetMonitorPhysicalHeight(int monitor)
594 //int GetMonitorRefreshRate(int monitor)
595 //Vector2 GetMonitorPosition(int monitor)
596 //const char *GetMonitorName(int monitor)
597
598 //void SetClipboardText(const char *text)
599 //const char *GetClipboardText(void)
600
601 //void ShowCursor(void)
602 //void HideCursor(void)
603 //void EnableCursor(void)
604 //void DisableCursor(void)
605
606 // Initialize window and OpenGL context
607 void InitWindow(int width, int height, const char *title)
608 {
609 TRACELOG(LOG_INFO, "Initializing raylib %s", RAYLIB_VERSION);
610
611 #if defined(PLATFORM_DESKTOP_GLFW)
612 TRACELOG(LOG_INFO, "Platform backend: DESKTOP (GLFW)");
613 #elif defined(PLATFORM_DESKTOP_SDL)
614 TRACELOG(LOG_INFO, "Platform backend: DESKTOP (SDL)");
615 #elif defined(PLATFORM_DESKTOP_RGFW)
616 TRACELOG(LOG_INFO, "Platform backend: DESKTOP (RGFW)");
617 #elif defined(PLATFORM_DESKTOP_WIN32)
618 TRACELOG(LOG_INFO, "Platform backend: DESKTOP (WIN32)");
619 #elif defined(PLATFORM_WEB_RGFW)
620 TRACELOG(LOG_INFO, "Platform backend: WEB (RGFW) (HTML5)");
621 #elif defined(PLATFORM_WEB)
622 TRACELOG(LOG_INFO, "Platform backend: WEB (HTML5)");
623 #elif defined(PLATFORM_DRM)
624 TRACELOG(LOG_INFO, "Platform backend: NATIVE DRM");
625 #elif defined(PLATFORM_ANDROID)
626 TRACELOG(LOG_INFO, "Platform backend: ANDROID");
627 #elif defined(PLATFORM_MEMORY)
628 TRACELOG(LOG_INFO, "Platform backend: MEMORY (No OS)");
629 #else
630 // TODO: Include your custom platform backend!
631 // i.e software rendering backend or console backend!
632 TRACELOG(LOG_INFO, "Platform backend: CUSTOM");
633 #endif
634
635 TRACELOG(LOG_INFO, "Supported raylib modules:");
636 TRACELOG(LOG_INFO, " > rcore:..... loaded (mandatory)");
637 TRACELOG(LOG_INFO, " > rlgl:...... loaded (mandatory)");
638 #if SUPPORT_MODULE_RSHAPES
639 TRACELOG(LOG_INFO, " > rshapes:... loaded (optional)");
640 #else
641 TRACELOG(LOG_INFO, " > rshapes:... not loaded (optional)");
642 #endif
643 #if SUPPORT_MODULE_RTEXTURES
644 TRACELOG(LOG_INFO, " > rtextures:. loaded (optional)");
645 #else
646 TRACELOG(LOG_INFO, " > rtextures:. not loaded (optional)");
647 #endif
648 #if SUPPORT_MODULE_RTEXT
649 TRACELOG(LOG_INFO, " > rtext:..... loaded (optional)");
650 #else
651 TRACELOG(LOG_INFO, " > rtext:..... not loaded (optional)");
652 #endif
653 #if SUPPORT_MODULE_RMODELS
654 TRACELOG(LOG_INFO, " > rmodels:... loaded (optional)");
655 #else
656 TRACELOG(LOG_INFO, " > rmodels:... not loaded (optional)");
657 #endif
658 #if SUPPORT_MODULE_RAUDIO
659 TRACELOG(LOG_INFO, " > raudio:.... loaded (optional)");
660 #else
661 TRACELOG(LOG_INFO, " > raudio:.... not loaded (optional)");
662 #endif
663
664 // Initialize window data
665 CORE.Window.screen.width = width;
666 CORE.Window.screen.height = height;
667
668 CORE.Window.eventWaiting = false;
669 CORE.Window.screenScale = MatrixIdentity(); // No draw scaling required by default
670 if ((title != NULL) && (title[0] != 0)) CORE.Window.title = title;
671
672 // Initialize global input state
673 memset(&CORE.Input, 0, sizeof(CORE.Input)); // Reset CORE.Input structure to 0
674 CORE.Input.Keyboard.exitKey = KEY_ESCAPE;
675 CORE.Input.Mouse.scale = (Vector2){ 1.0f, 1.0f };
676 CORE.Input.Mouse.cursor = MOUSE_CURSOR_ARROW;
677 CORE.Input.Gamepad.lastButtonPressed = GAMEPAD_BUTTON_UNKNOWN;
678
679 // Initialize platform
680 //--------------------------------------------------------------
681 int result = InitPlatform();
682
683 if (result != 0)
684 {
685 TRACELOG(LOG_WARNING, "SYSTEM: Failed to initialize platform");
686 return;
687 }
688
689 // Initialize render dimensions for embedded platforms
690 // NOTE: On desktop platforms (GLFW, SDL, etc.), CORE.Window.render.width/height are set during window creation
691 // On embedded platforms with no window manager, InitPlatform() doesn't set these values, so they should be initialized
692 // here from screen dimensions (which are set from the InitWindow parameters)
693 if ((CORE.Window.render.width == 0) || (CORE.Window.render.height == 0))
694 {
695 CORE.Window.render.width = CORE.Window.screen.width;
696 CORE.Window.render.height = CORE.Window.screen.height;
697 }
698 //--------------------------------------------------------------
699
700 // Initialize rlgl default data (buffers and shaders)
701 // NOTE: Current fbo size stored as globals in rlgl for convenience
702 rlglInit(CORE.Window.render.width, CORE.Window.render.height);
703
704 // Setup default viewport
705 SetupViewport(CORE.Window.render.width, CORE.Window.render.height);
706
707 #if SUPPORT_MODULE_RTEXT
708 // Load default font
709 // WARNING: External function: Module required: rtext
710 LoadFontDefault();
711 #if SUPPORT_MODULE_RSHAPES
712 // Set font white rectangle for shapes drawing, so shapes and text can be batched together
713 // WARNING: rshapes module is required, if not available, default internal white rectangle is used
714 Rectangle rec = GetFontDefault().recs[95];
715 if (FLAG_IS_SET(CORE.Window.flags, FLAG_MSAA_4X_HINT))
716 {
717 // NOTE: Try to maximize rec padding to avoid pixel bleeding on MSAA filtering
718 SetShapesTexture(GetFontDefault().texture, (Rectangle){ rec.x + 2, rec.y + 2, 1, 1 });
719 }
720 else
721 {
722 // NOTE: Set up a 1px padding on char rectangle to avoid pixel bleeding
723 SetShapesTexture(GetFontDefault().texture, (Rectangle){ rec.x + 1, rec.y + 1, rec.width - 2, rec.height - 2 });
724 }
725 #endif
726 #else
727 #if SUPPORT_MODULE_RSHAPES
728 // Set default texture and rectangle to be used for shapes drawing
729 // NOTE: rlgl default texture is a 1x1 pixel UNCOMPRESSED_R8G8B8A8
730 Texture2D texture = { rlGetTextureIdDefault(), 1, 1, 1, PIXELFORMAT_UNCOMPRESSED_R8G8B8A8 };
731 SetShapesTexture(texture, (Rectangle){ 0.0f, 0.0f, 1.0f, 1.0f }); // WARNING: Module required: rshapes
732 #endif
733 #endif
734
735 CORE.Time.frameCounter = 0;
736 CORE.Window.shouldClose = false;
737
738 // Initialize random seed
739 SetRandomSeed((unsigned int)time(NULL));
740
741 TRACELOG(LOG_INFO, "SYSTEM: Working Directory: %s", GetWorkingDirectory());
742 }
743
744 // Close window and unload OpenGL context
745 void CloseWindow(void)
746 {
747 #if SUPPORT_MODULE_RTEXT
748 UnloadFontDefault(); // WARNING: Module required: rtext
749 #endif
750
751 rlglClose(); // De-init rlgl
752
753 // De-initialize platform
754 //--------------------------------------------------------------
755 ClosePlatform();
756 //--------------------------------------------------------------
757
758 CORE.Window.ready = false;
759 TRACELOG(LOG_INFO, "Window closed successfully");
760 }
761
762 // Check if window has been initialized successfully
763 bool IsWindowReady(void)
764 {
765 return CORE.Window.ready;
766 }
767
768 // Check if window is currently fullscreen
769 bool IsWindowFullscreen(void)
770 {
771 return FLAG_IS_SET(CORE.Window.flags, FLAG_FULLSCREEN_MODE);
772 }
773
774 // Check if window is currently hidden
775 bool IsWindowHidden(void)
776 {
777 return FLAG_IS_SET(CORE.Window.flags, FLAG_WINDOW_HIDDEN);
778 }
779
780 // Check if window has been minimized
781 bool IsWindowMinimized(void)
782 {
783 return FLAG_IS_SET(CORE.Window.flags, FLAG_WINDOW_MINIMIZED);
784 }
785
786 // Check if window has been maximized
787 bool IsWindowMaximized(void)
788 {
789 return FLAG_IS_SET(CORE.Window.flags, FLAG_WINDOW_MAXIMIZED);
790 }
791
792 // Check if window has the focus
793 bool IsWindowFocused(void)
794 {
795 return !FLAG_IS_SET(CORE.Window.flags, FLAG_WINDOW_UNFOCUSED);
796 }
797
798 // Check if window has been resizedLastFrame
799 bool IsWindowResized(void)
800 {
801 return CORE.Window.resizedLastFrame;
802 }
803
804 // Check if one specific window flag is enabled
805 bool IsWindowState(unsigned int flag)
806 {
807 return FLAG_IS_SET(CORE.Window.flags, flag);
808 }
809
810 // Get current screen width
811 int GetScreenWidth(void)
812 {
813 return CORE.Window.screen.width;
814 }
815
816 // Get current screen height
817 int GetScreenHeight(void)
818 {
819 return CORE.Window.screen.height;
820 }
821
822 // Get current render width which is equal to screen width*dpi scale
823 int GetRenderWidth(void)
824 {
825 int width = 0;
826
827 if (CORE.Window.usingFbo) width = CORE.Window.currentFbo.width;
828 else width = CORE.Window.render.width;
829
830 return width;
831 }
832
833 // Get current screen height which is equal to screen height*dpi scale
834 int GetRenderHeight(void)
835 {
836 int height = 0;
837
838 if (CORE.Window.usingFbo) height = CORE.Window.currentFbo.height;
839 else height = CORE.Window.render.height;
840
841 return height;
842 }
843
844 // Enable waiting for events on EndDrawing(), no automatic event polling
845 void EnableEventWaiting(void)
846 {
847 CORE.Window.eventWaiting = true;
848 }
849
850 // Disable waiting for events on EndDrawing(), automatic events polling
851 void DisableEventWaiting(void)
852 {
853 CORE.Window.eventWaiting = false;
854 }
855
856 // Check if cursor is not visible
857 bool IsCursorHidden(void)
858 {
859 return CORE.Input.Mouse.cursorHidden;
860 }
861
862 // Check if cursor is on the current screen
863 bool IsCursorOnScreen(void)
864 {
865 return CORE.Input.Mouse.cursorOnScreen;
866 }
867
868 //----------------------------------------------------------------------------------
869 // Module Functions Definition: Screen Drawing
870 //----------------------------------------------------------------------------------
871
872 // Set background color (framebuffer clear color)
873 void ClearBackground(Color color)
874 {
875 rlClearColor(color.r, color.g, color.b, color.a); // Set clear color
876 rlClearScreenBuffers(); // Clear current framebuffers
877 }
878
879 // Setup canvas (framebuffer) to start drawing
880 void BeginDrawing(void)
881 {
882 // WARNING: Previously to BeginDrawing() other render textures drawing could happen,
883 // consequently the measure for update vs draw is not accurate (only the total frame time is accurate)
884
885 CORE.Time.current = GetTime(); // Number of elapsed seconds since InitTimer()
886 CORE.Time.update = CORE.Time.current - CORE.Time.previous;
887 CORE.Time.previous = CORE.Time.current;
888
889 rlLoadIdentity(); // Reset current matrix (modelview)
890 rlMultMatrixf(MatrixToFloat(CORE.Window.screenScale)); // Apply screen scaling
891
892 //rlTranslatef(0.375, 0.375, 0); // HACK to have 2D pixel-perfect drawing on OpenGL 1.1
893 // NOTE: Not required with OpenGL 3.3+
894 }
895
896 // End canvas drawing and swap buffers (double buffering)
897 void EndDrawing(void)
898 {
899 rlDrawRenderBatchActive(); // Update and draw internal render batch
900
901 #if SUPPORT_AUTOMATION_EVENTS
902 if (automationEventRecording) RecordAutomationEvent(); // Event recording
903 #endif
904
905 #if !SUPPORT_CUSTOM_FRAME_CONTROL
906 SwapScreenBuffer(); // Copy back buffer to front buffer (screen)
907
908 // Frame time control system
909 CORE.Time.current = GetTime();
910 CORE.Time.draw = CORE.Time.current - CORE.Time.previous;
911 CORE.Time.previous = CORE.Time.current;
912
913 CORE.Time.frame = CORE.Time.update + CORE.Time.draw;
914
915 // Wait for some milliseconds...
916 if (CORE.Time.frame < CORE.Time.target)
917 {
918 WaitTime(CORE.Time.target - CORE.Time.frame);
919
920 CORE.Time.current = GetTime();
921 double waitTime = CORE.Time.current - CORE.Time.previous;
922 CORE.Time.previous = CORE.Time.current;
923
924 CORE.Time.frame += waitTime; // Total frame time: update + draw + wait
925 }
926
927 PollInputEvents(); // Poll user events (before next frame update)
928 #endif
929
930 #if SUPPORT_SCREEN_CAPTURE
931 if (IsKeyPressed(KEY_F12))
932 {
933 TakeScreenshot(TextFormat("screenshot%03i.png", screenshotCounter));
934 screenshotCounter++;
935 }
936 #endif
937
938 CORE.Time.frameCounter++;
939 }
940
941 // Initialize 2D mode with custom camera (2D)
942 void BeginMode2D(Camera2D camera)
943 {
944 rlDrawRenderBatchActive(); // Update and draw internal render batch
945
946 rlLoadIdentity(); // Reset current matrix (modelview)
947
948 // Apply 2d camera transformation to modelview
949 rlMultMatrixf(MatrixToFloat(GetCameraMatrix2D(camera)));
950 }
951
952 // Ends 2D mode with custom camera
953 void EndMode2D(void)
954 {
955 rlDrawRenderBatchActive(); // Update and draw internal render batch
956
957 rlLoadIdentity(); // Reset current matrix (modelview)
958
959 if (rlGetActiveFramebuffer() == 0) rlMultMatrixf(MatrixToFloat(CORE.Window.screenScale)); // Apply screen scaling if required
960 }
961
962 // Initializes 3D mode with custom camera (3D)
963 void BeginMode3D(Camera camera)
964 {
965 rlDrawRenderBatchActive(); // Update and draw internal render batch
966
967 rlMatrixMode(RL_PROJECTION); // Switch to projection matrix
968 rlPushMatrix(); // Save previous matrix, which contains the settings for the 2d ortho projection
969 rlLoadIdentity(); // Reset current matrix (projection)
970
971 float aspect = (float)CORE.Window.currentFbo.width/(float)CORE.Window.currentFbo.height;
972
973 // NOTE: zNear and zFar values are important when computing depth buffer values
974 if (camera.projection == CAMERA_PERSPECTIVE)
975 {
976 // Setup perspective projection
977 double top = rlGetCullDistanceNear()*tan(camera.fovy*0.5*DEG2RAD);
978 double right = top*aspect;
979
980 rlFrustum(-right, right, -top, top, rlGetCullDistanceNear(), rlGetCullDistanceFar());
981 }
982 else if (camera.projection == CAMERA_ORTHOGRAPHIC)
983 {
984 // Setup orthographic projection
985 double top = camera.fovy/2.0;
986 double right = top*aspect;
987
988 rlOrtho(-right, right, -top,top, rlGetCullDistanceNear(), rlGetCullDistanceFar());
989 }
990
991 rlMatrixMode(RL_MODELVIEW); // Switch back to modelview matrix
992 rlLoadIdentity(); // Reset current matrix (modelview)
993
994 // Setup Camera view
995 Matrix matView = MatrixLookAt(camera.position, camera.target, camera.up);
996 rlMultMatrixf(MatrixToFloat(matView)); // Multiply modelview matrix by view matrix (camera)
997
998 rlEnableDepthTest(); // Enable DEPTH_TEST for 3D
999 }
1000
1001 // Ends 3D mode and returns to default 2D orthographic mode
1002 void EndMode3D(void)
1003 {
1004 rlDrawRenderBatchActive(); // Update and draw internal render batch
1005
1006 rlMatrixMode(RL_PROJECTION); // Switch to projection matrix
1007 rlPopMatrix(); // Restore previous matrix (projection) from matrix stack
1008
1009 rlMatrixMode(RL_MODELVIEW); // Switch back to modelview matrix
1010 rlLoadIdentity(); // Reset current matrix (modelview)
1011
1012 if (rlGetActiveFramebuffer() == 0) rlMultMatrixf(MatrixToFloat(CORE.Window.screenScale)); // Apply screen scaling if required
1013
1014 rlDisableDepthTest(); // Disable DEPTH_TEST for 2D
1015 }
1016
1017 // Initializes render texture for drawing
1018 void BeginTextureMode(RenderTexture2D target)
1019 {
1020 rlDrawRenderBatchActive(); // Update and draw internal render batch
1021
1022 rlEnableFramebuffer(target.id); // Enable render target
1023
1024 // Set viewport and RLGL internal framebuffer size
1025 rlViewport(0, 0, target.texture.width, target.texture.height);
1026 rlSetFramebufferWidth(target.texture.width);
1027 rlSetFramebufferHeight(target.texture.height);
1028
1029 rlMatrixMode(RL_PROJECTION); // Switch to projection matrix
1030 rlLoadIdentity(); // Reset current matrix (projection)
1031
1032 // Set orthographic projection to current framebuffer size
1033 // NOTE: Configured top-left corner as (0, 0)
1034 rlOrtho(0, target.texture.width, target.texture.height, 0, 0.0f, 1.0f);
1035
1036 rlMatrixMode(RL_MODELVIEW); // Switch back to modelview matrix
1037 rlLoadIdentity(); // Reset current matrix (modelview)
1038
1039 //rlScalef(0.0f, -1.0f, 0.0f); // Flip Y-drawing (?)
1040
1041 // Setup current width/height for proper aspect ratio
1042 // calculation when using BeginTextureMode()
1043 CORE.Window.currentFbo.width = target.texture.width;
1044 CORE.Window.currentFbo.height = target.texture.height;
1045 CORE.Window.usingFbo = true;
1046 }
1047
1048 // Ends drawing to render texture
1049 void EndTextureMode(void)
1050 {
1051 rlDrawRenderBatchActive(); // Update and draw internal render batch
1052
1053 rlDisableFramebuffer(); // Disable render target (fbo)
1054
1055 // Set viewport to default framebuffer size
1056 SetupViewport(CORE.Window.render.width, CORE.Window.render.height);
1057
1058 // Go back to the modelview state from BeginDrawing, back to the main framebuffer
1059 rlMatrixMode(RL_MODELVIEW); // Switch back to modelview matrix
1060 rlLoadIdentity(); // Reset current matrix (modelview)
1061 rlMultMatrixf(MatrixToFloat(CORE.Window.screenScale)); // Apply screen scaling if required
1062
1063 // Reset current fbo to screen size
1064 CORE.Window.currentFbo.width = CORE.Window.render.width;
1065 CORE.Window.currentFbo.height = CORE.Window.render.height;
1066 CORE.Window.usingFbo = false;
1067 }
1068
1069 // Begin custom shader mode
1070 void BeginShaderMode(Shader shader)
1071 {
1072 rlSetShader(shader.id, shader.locs);
1073 }
1074
1075 // End custom shader mode (returns to default shader)
1076 void EndShaderMode(void)
1077 {
1078 rlSetShader(rlGetShaderIdDefault(), rlGetShaderLocsDefault());
1079 }
1080
1081 // Begin blending mode (alpha, additive, multiplied, subtract, custom)
1082 // NOTE: Blend modes supported are enumerated in BlendMode enum
1083 void BeginBlendMode(int mode)
1084 {
1085 rlSetBlendMode(mode);
1086 }
1087
1088 // End blending mode (reset to default: alpha blending)
1089 void EndBlendMode(void)
1090 {
1091 rlSetBlendMode(BLEND_ALPHA);
1092 }
1093
1094 // Begin scissor mode (define screen area for following drawing)
1095 // NOTE: Scissor rec refers to bottom-left corner, changing it to upper-left
1096 void BeginScissorMode(int x, int y, int width, int height)
1097 {
1098 rlDrawRenderBatchActive(); // Update and draw internal render batch
1099
1100 rlEnableScissorTest();
1101
1102 #if defined(__APPLE__)
1103 if (!CORE.Window.usingFbo)
1104 {
1105 Vector2 scale = GetWindowScaleDPI();
1106 rlScissor((int)(x*scale.x), (int)(GetScreenHeight()*scale.y - (((y + height)*scale.y))), (int)(width*scale.x), (int)(height*scale.y));
1107 }
1108 #else
1109 if (!CORE.Window.usingFbo && FLAG_IS_SET(CORE.Window.flags, FLAG_WINDOW_HIGHDPI))
1110 {
1111 Vector2 scale = GetWindowScaleDPI();
1112 rlScissor((int)(x*scale.x), (int)(CORE.Window.currentFbo.height - (y + height)*scale.y), (int)(width*scale.x), (int)(height*scale.y));
1113 }
1114 #endif
1115 else
1116 {
1117 rlScissor(x, CORE.Window.currentFbo.height - (y + height), width, height);
1118 }
1119 }
1120
1121 // End scissor mode
1122 void EndScissorMode(void)
1123 {
1124 rlDrawRenderBatchActive(); // Update and draw internal render batch
1125 rlDisableScissorTest();
1126 }
1127
1128 //----------------------------------------------------------------------------------
1129 // Module Functions Definition: VR Stereo Rendering
1130 //----------------------------------------------------------------------------------
1131
1132 // Begin VR drawing configuration
1133 void BeginVrStereoMode(VrStereoConfig config)
1134 {
1135 rlEnableStereoRender();
1136
1137 // Set stereo render matrices
1138 rlSetMatrixProjectionStereo(config.projection[0], config.projection[1]);
1139 rlSetMatrixViewOffsetStereo(config.viewOffset[0], config.viewOffset[1]);
1140 }
1141
1142 // End VR drawing process (and desktop mirror)
1143 void EndVrStereoMode(void)
1144 {
1145 rlDisableStereoRender();
1146 }
1147
1148 // Load VR stereo config for VR simulator device parameters
1149 VrStereoConfig LoadVrStereoConfig(VrDeviceInfo device)
1150 {
1151 VrStereoConfig config = { 0 };
1152
1153 if (rlGetVersion() != RL_OPENGL_11)
1154 {
1155 // Compute aspect ratio
1156 float aspect = ((float)device.hResolution*0.5f)/(float)device.vResolution;
1157
1158 // Compute lens parameters
1159 float lensShift = (device.hScreenSize*0.25f - device.lensSeparationDistance*0.5f)/device.hScreenSize;
1160 config.leftLensCenter[0] = 0.25f + lensShift;
1161 config.leftLensCenter[1] = 0.5f;
1162 config.rightLensCenter[0] = 0.75f - lensShift;
1163 config.rightLensCenter[1] = 0.5f;
1164 config.leftScreenCenter[0] = 0.25f;
1165 config.leftScreenCenter[1] = 0.5f;
1166 config.rightScreenCenter[0] = 0.75f;
1167 config.rightScreenCenter[1] = 0.5f;
1168
1169 // Compute distortion scale parameters
1170 // NOTE: To get lens max radius, lensShift must be normalized to [-1..1]
1171 float lensRadius = fabsf(-1.0f - 4.0f*lensShift);
1172 float lensRadiusSq = lensRadius*lensRadius;
1173 float distortionScale = device.lensDistortionValues[0] +
1174 device.lensDistortionValues[1]*lensRadiusSq +
1175 device.lensDistortionValues[2]*lensRadiusSq*lensRadiusSq +
1176 device.lensDistortionValues[3]*lensRadiusSq*lensRadiusSq*lensRadiusSq;
1177
1178 float normScreenWidth = 0.5f;
1179 float normScreenHeight = 1.0f;
1180 config.scaleIn[0] = 2.0f/normScreenWidth;
1181 config.scaleIn[1] = 2.0f/normScreenHeight/aspect;
1182 config.scale[0] = normScreenWidth*0.5f/distortionScale;
1183 config.scale[1] = normScreenHeight*0.5f*aspect/distortionScale;
1184
1185 // Fovy is normally computed with: 2*atan2f(device.vScreenSize, 2*device.eyeToScreenDistance)
1186 // ...but with lens distortion it is increased (see Oculus SDK Documentation)
1187 float fovy = 2.0f*atan2f(device.vScreenSize*0.5f*distortionScale, device.eyeToScreenDistance); // Really need distortionScale?
1188 // float fovy = 2.0f*(float)atan2f(device.vScreenSize*0.5f, device.eyeToScreenDistance);
1189
1190 // Compute camera projection matrices
1191 float projOffset = 4.0f*lensShift; // Scaled to projection space coordinates [-1..1]
1192 Matrix proj = MatrixPerspective(fovy, aspect, rlGetCullDistanceNear(), rlGetCullDistanceFar());
1193
1194 config.projection[0] = MatrixMultiply(proj, MatrixTranslate(projOffset, 0.0f, 0.0f));
1195 config.projection[1] = MatrixMultiply(proj, MatrixTranslate(-projOffset, 0.0f, 0.0f));
1196
1197 // Compute camera transformation matrices
1198 // NOTE: Camera movement might seem more natural if modelling the head
1199 // Axis of rotation is the base of the head, so adding some y (base of head to eye level
1200 // and -z (center of head to eye protrusion) to the camera positions
1201 config.viewOffset[0] = MatrixTranslate(device.interpupillaryDistance*0.5f, 0.075f, 0.045f);
1202 config.viewOffset[1] = MatrixTranslate(-device.interpupillaryDistance*0.5f, 0.075f, 0.045f);
1203
1204 // Compute eyes Viewports
1205 /*
1206 config.eyeViewportRight[0] = 0;
1207 config.eyeViewportRight[1] = 0;
1208 config.eyeViewportRight[2] = device.hResolution/2;
1209 config.eyeViewportRight[3] = device.vResolution;
1210
1211 config.eyeViewportLeft[0] = device.hResolution/2;
1212 config.eyeViewportLeft[1] = 0;
1213 config.eyeViewportLeft[2] = device.hResolution/2;
1214 config.eyeViewportLeft[3] = device.vResolution;
1215 */
1216 }
1217 else TRACELOG(LOG_WARNING, "RLGL: VR Simulator not supported on OpenGL 1.1");
1218
1219 return config;
1220 }
1221
1222 // Unload VR stereo config properties
1223 void UnloadVrStereoConfig(VrStereoConfig config)
1224 {
1225 TRACELOG(LOG_INFO, "UnloadVrStereoConfig not implemented in rcore.c");
1226 }
1227
1228 //----------------------------------------------------------------------------------
1229 // Module Functions Definition: Shaders Management
1230 //----------------------------------------------------------------------------------
1231
1232 // Load shader from files and bind default locations
1233 // NOTE: If shader filename is NULL, using default vertex/fragment shaders
1234 Shader LoadShader(const char *vsFileName, const char *fsFileName)
1235 {
1236 Shader shader = { 0 };
1237
1238 char *vShaderStr = NULL;
1239 char *fShaderStr = NULL;
1240
1241 if (vsFileName != NULL) vShaderStr = LoadFileText(vsFileName);
1242 if (fsFileName != NULL) fShaderStr = LoadFileText(fsFileName);
1243
1244 if ((vShaderStr == NULL) && (fShaderStr == NULL)) TRACELOG(LOG_WARNING, "SHADER: Shader files provided are not valid, using default shader");
1245
1246 shader = LoadShaderFromMemory(vShaderStr, fShaderStr);
1247
1248 UnloadFileText(vShaderStr);
1249 UnloadFileText(fShaderStr);
1250
1251 return shader;
1252 }
1253
1254 // Load shader from code strings and bind default locations
1255 Shader LoadShaderFromMemory(const char *vsCode, const char *fsCode)
1256 {
1257 Shader shader = { 0 };
1258
1259 shader.id = rlLoadShaderProgram(vsCode, fsCode);
1260
1261 if (shader.id == 0)
1262 {
1263 // Shader could not be loaded but still loading the location points to avoid potential crashes
1264 // NOTE: All locations set to -1 (no location found)
1265 shader.locs = (int *)RL_CALLOC(RL_MAX_SHADER_LOCATIONS, sizeof(int));
1266 for (int i = 0; i < RL_MAX_SHADER_LOCATIONS; i++) shader.locs[i] = -1;
1267 }
1268 else if (shader.id == rlGetShaderIdDefault()) shader.locs = rlGetShaderLocsDefault();
1269 else if (shader.id > 0)
1270 {
1271 // After custom shader loading, trying to set default location names
1272 // Default shader attribute locations have been binded before linking:
1273 // - vertex position location = 0
1274 // - vertex texcoord location = 1
1275 // - vertex normal location = 2
1276 // - vertex color location = 3
1277 // - vertex tangent location = 4
1278 // - vertex texcoord2 location = 5
1279 // - vertex boneIndices location = 6
1280 // - vertex boneWeights location = 7
1281
1282 // NOTE: If any location is not found, loc point becomes -1
1283
1284 // Load shader locations array
1285 // NOTE: All locations set to -1 (no location)
1286 shader.locs = (int *)RL_CALLOC(RL_MAX_SHADER_LOCATIONS, sizeof(int));
1287 for (int i = 0; i < RL_MAX_SHADER_LOCATIONS; i++) shader.locs[i] = -1;
1288
1289 // Get handles to GLSL input attribute locations
1290 shader.locs[SHADER_LOC_VERTEX_POSITION] = rlGetLocationAttrib(shader.id, RL_DEFAULT_SHADER_ATTRIB_NAME_POSITION);
1291 shader.locs[SHADER_LOC_VERTEX_TEXCOORD01] = rlGetLocationAttrib(shader.id, RL_DEFAULT_SHADER_ATTRIB_NAME_TEXCOORD);
1292 shader.locs[SHADER_LOC_VERTEX_TEXCOORD02] = rlGetLocationAttrib(shader.id, RL_DEFAULT_SHADER_ATTRIB_NAME_TEXCOORD2);
1293 shader.locs[SHADER_LOC_VERTEX_NORMAL] = rlGetLocationAttrib(shader.id, RL_DEFAULT_SHADER_ATTRIB_NAME_NORMAL);
1294 shader.locs[SHADER_LOC_VERTEX_TANGENT] = rlGetLocationAttrib(shader.id, RL_DEFAULT_SHADER_ATTRIB_NAME_TANGENT);
1295 shader.locs[SHADER_LOC_VERTEX_COLOR] = rlGetLocationAttrib(shader.id, RL_DEFAULT_SHADER_ATTRIB_NAME_COLOR);
1296 shader.locs[SHADER_LOC_VERTEX_BONEIDS] = rlGetLocationAttrib(shader.id, RL_DEFAULT_SHADER_ATTRIB_NAME_BONEINDICES);
1297 shader.locs[SHADER_LOC_VERTEX_BONEWEIGHTS] = rlGetLocationAttrib(shader.id, RL_DEFAULT_SHADER_ATTRIB_NAME_BONEWEIGHTS);
1298 shader.locs[SHADER_LOC_VERTEX_INSTANCETRANSFORM] = rlGetLocationAttrib(shader.id, RL_DEFAULT_SHADER_ATTRIB_NAME_INSTANCETRANSFORM);
1299
1300 // Get handles to GLSL uniform locations (vertex shader)
1301 shader.locs[SHADER_LOC_MATRIX_MVP] = rlGetLocationUniform(shader.id, RL_DEFAULT_SHADER_UNIFORM_NAME_MVP);
1302 shader.locs[SHADER_LOC_MATRIX_VIEW] = rlGetLocationUniform(shader.id, RL_DEFAULT_SHADER_UNIFORM_NAME_VIEW);
1303 shader.locs[SHADER_LOC_MATRIX_PROJECTION] = rlGetLocationUniform(shader.id, RL_DEFAULT_SHADER_UNIFORM_NAME_PROJECTION);
1304 shader.locs[SHADER_LOC_MATRIX_MODEL] = rlGetLocationUniform(shader.id, RL_DEFAULT_SHADER_UNIFORM_NAME_MODEL);
1305 shader.locs[SHADER_LOC_MATRIX_NORMAL] = rlGetLocationUniform(shader.id, RL_DEFAULT_SHADER_UNIFORM_NAME_NORMAL);
1306 shader.locs[SHADER_LOC_MATRIX_BONETRANSFORMS] = rlGetLocationUniform(shader.id, RL_DEFAULT_SHADER_UNIFORM_NAME_BONEMATRICES);
1307
1308 // Get handles to GLSL uniform locations (fragment shader)
1309 shader.locs[SHADER_LOC_COLOR_DIFFUSE] = rlGetLocationUniform(shader.id, RL_DEFAULT_SHADER_UNIFORM_NAME_COLOR);
1310 shader.locs[SHADER_LOC_MAP_DIFFUSE] = rlGetLocationUniform(shader.id, RL_DEFAULT_SHADER_SAMPLER2D_NAME_TEXTURE0); // SHADER_LOC_MAP_ALBEDO
1311 shader.locs[SHADER_LOC_MAP_SPECULAR] = rlGetLocationUniform(shader.id, RL_DEFAULT_SHADER_SAMPLER2D_NAME_TEXTURE1); // SHADER_LOC_MAP_METALNESS
1312 shader.locs[SHADER_LOC_MAP_NORMAL] = rlGetLocationUniform(shader.id, RL_DEFAULT_SHADER_SAMPLER2D_NAME_TEXTURE2);
1313 }
1314
1315 return shader;
1316 }
1317
1318 // Check if a shader is valid (loaded on GPU)
1319 bool IsShaderValid(Shader shader)
1320 {
1321 return ((shader.id > 0) && // Validate shader id (GPU loaded successfully)
1322 (shader.locs != NULL)); // Validate memory has been allocated for default shader locations
1323
1324 // The following locations are tried to be set automatically (locs[i] >= 0),
1325 // any of them can be checked for validation but the only mandatory one is, afaik, SHADER_LOC_VERTEX_POSITION
1326 // NOTE: Users can also setup manually their own attributes/uniforms and do not used the default raylib ones
1327
1328 // Vertex shader attribute locations (default)
1329 // shader.locs[SHADER_LOC_VERTEX_POSITION] // Set by default internal shader
1330 // shader.locs[SHADER_LOC_VERTEX_TEXCOORD01] // Set by default internal shader
1331 // shader.locs[SHADER_LOC_VERTEX_TEXCOORD02]
1332 // shader.locs[SHADER_LOC_VERTEX_NORMAL]
1333 // shader.locs[SHADER_LOC_VERTEX_TANGENT]
1334 // shader.locs[SHADER_LOC_VERTEX_COLOR] // Set by default internal shader
1335
1336 // Vertex shader uniform locations (default)
1337 // shader.locs[SHADER_LOC_MATRIX_MVP] // Set by default internal shader
1338 // shader.locs[SHADER_LOC_MATRIX_VIEW]
1339 // shader.locs[SHADER_LOC_MATRIX_PROJECTION]
1340 // shader.locs[SHADER_LOC_MATRIX_MODEL]
1341 // shader.locs[SHADER_LOC_MATRIX_NORMAL]
1342
1343 // Fragment shader uniform locations (default)
1344 // shader.locs[SHADER_LOC_COLOR_DIFFUSE] // Set by default internal shader
1345 // shader.locs[SHADER_LOC_MAP_DIFFUSE] // Set by default internal shader
1346 // shader.locs[SHADER_LOC_MAP_SPECULAR]
1347 // shader.locs[SHADER_LOC_MAP_NORMAL]
1348 }
1349
1350 // Unload shader from GPU memory (VRAM)
1351 void UnloadShader(Shader shader)
1352 {
1353 if (shader.id != rlGetShaderIdDefault())
1354 {
1355 rlUnloadShaderProgram(shader.id);
1356
1357 // NOTE: If shader loading failed, it should be 0
1358 RL_FREE(shader.locs);
1359 }
1360 }
1361
1362 // Get shader uniform location
1363 int GetShaderLocation(Shader shader, const char *uniformName)
1364 {
1365 return rlGetLocationUniform(shader.id, uniformName);
1366 }
1367
1368 // Get shader attribute location
1369 int GetShaderLocationAttrib(Shader shader, const char *attribName)
1370 {
1371 return rlGetLocationAttrib(shader.id, attribName);
1372 }
1373
1374 // Set shader uniform value
1375 void SetShaderValue(Shader shader, int locIndex, const void *value, int uniformType)
1376 {
1377 SetShaderValueV(shader, locIndex, value, uniformType, 1);
1378 }
1379
1380 // Set shader uniform value vector
1381 void SetShaderValueV(Shader shader, int locIndex, const void *value, int uniformType, int count)
1382 {
1383 if (locIndex > -1)
1384 {
1385 rlEnableShader(shader.id);
1386 rlSetUniform(locIndex, value, uniformType, count);
1387 //rlDisableShader(); // Avoid resetting current shader program, in case other uniforms are set
1388 }
1389 }
1390
1391 // Set shader uniform value (matrix 4x4)
1392 void SetShaderValueMatrix(Shader shader, int locIndex, Matrix mat)
1393 {
1394 if (locIndex > -1)
1395 {
1396 rlEnableShader(shader.id);
1397 rlSetUniformMatrix(locIndex, mat);
1398 //rlDisableShader();
1399 }
1400 }
1401
1402 // Set shader uniform value for texture
1403 void SetShaderValueTexture(Shader shader, int locIndex, Texture2D texture)
1404 {
1405 if (locIndex > -1)
1406 {
1407 rlEnableShader(shader.id);
1408 rlSetUniformSampler(locIndex, texture.id);
1409 //rlDisableShader();
1410 }
1411 }
1412
1413 //----------------------------------------------------------------------------------
1414 // Module Functions Definition: Screen-space Queries
1415 //----------------------------------------------------------------------------------
1416
1417 // Get a ray trace from screen position (i.e mouse)
1418 Ray GetScreenToWorldRay(Vector2 position, Camera camera)
1419 {
1420 Ray ray = GetScreenToWorldRayEx(position, camera, GetScreenWidth(), GetScreenHeight());
1421
1422 return ray;
1423 }
1424
1425 // Get a ray trace from the screen position (i.e mouse) within a specific section of the screen
1426 Ray GetScreenToWorldRayEx(Vector2 position, Camera camera, int width, int height)
1427 {
1428 Ray ray = { 0 };
1429
1430 // Calculate normalized device coordinates
1431 // NOTE: y value is negative
1432 float x = (2.0f*position.x)/(float)width - 1.0f;
1433 float y = 1.0f - (2.0f*position.y)/(float)height;
1434 float z = 1.0f;
1435
1436 // Store values in a vector
1437 Vector3 deviceCoords = { x, y, z };
1438
1439 // Calculate view matrix from camera look at
1440 Matrix matView = MatrixLookAt(camera.position, camera.target, camera.up);
1441
1442 Matrix matProj = MatrixIdentity();
1443
1444 if (camera.projection == CAMERA_PERSPECTIVE)
1445 {
1446 // Calculate projection matrix from perspective
1447 matProj = MatrixPerspective(camera.fovy*DEG2RAD, ((double)width/(double)height), rlGetCullDistanceNear(), rlGetCullDistanceFar());
1448 }
1449 else if (camera.projection == CAMERA_ORTHOGRAPHIC)
1450 {
1451 double aspect = (double)width/(double)height;
1452 double top = camera.fovy/2.0;
1453 double right = top*aspect;
1454
1455 // Calculate projection matrix from orthographic
1456 matProj = MatrixOrtho(-right, right, -top, top, rlGetCullDistanceNear(), rlGetCullDistanceFar());
1457 }
1458
1459 // Unproject far/near points
1460 Vector3 nearPoint = Vector3Unproject((Vector3){ deviceCoords.x, deviceCoords.y, 0.0f }, matProj, matView);
1461 Vector3 farPoint = Vector3Unproject((Vector3){ deviceCoords.x, deviceCoords.y, 1.0f }, matProj, matView);
1462
1463 // Unproject the mouse cursor in the near plane
1464 // It is needed as the source position because orthographic projects,
1465 // compared to perspective doesn't have a convergence point,
1466 // meaning that the "eye" of the camera is more like a plane than a point
1467 Vector3 cameraPlanePointerPos = Vector3Unproject((Vector3){ deviceCoords.x, deviceCoords.y, -1.0f }, matProj, matView);
1468
1469 // Calculate normalized direction vector
1470 Vector3 direction = Vector3Normalize(Vector3Subtract(farPoint, nearPoint));
1471
1472 if (camera.projection == CAMERA_PERSPECTIVE) ray.position = camera.position;
1473 else if (camera.projection == CAMERA_ORTHOGRAPHIC) ray.position = cameraPlanePointerPos;
1474
1475 // Apply calculated vectors to ray
1476 ray.direction = direction;
1477
1478 return ray;
1479 }
1480
1481 // Get transform matrix for camera
1482 Matrix GetCameraMatrix(Camera camera)
1483 {
1484 Matrix mat = MatrixLookAt(camera.position, camera.target, camera.up);
1485
1486 return mat;
1487 }
1488
1489 // Get camera 2d transform matrix
1490 Matrix GetCameraMatrix2D(Camera2D camera)
1491 {
1492 Matrix matTransform = { 0 };
1493 // The camera in world-space is set by
1494 // 1. Move it to target
1495 // 2. Rotate by -rotation and scale by (1/zoom)
1496 // When setting higher scale, it's more intuitive for the world to become bigger (= camera become smaller),
1497 // not for the camera getting bigger, hence the invert. Same deal with rotation
1498 // 3. Move it by (-offset);
1499 // Offset defines target transform relative to screen, but since effectively "moving" screen (camera)
1500 // it needs to be moved into opposite direction (inverse transform)
1501
1502 // Having camera transform in world-space, inverse of it gives the modelview transform
1503 // Since (A*B*C)' = C'*B'*A', the modelview is
1504 // 1. Move to offset
1505 // 2. Rotate and Scale
1506 // 3. Move by -target
1507 Matrix matOrigin = MatrixTranslate(-camera.target.x, -camera.target.y, 0.0f);
1508 Matrix matRotation = MatrixRotate((Vector3){ 0.0f, 0.0f, 1.0f }, camera.rotation*DEG2RAD);
1509 Matrix matScale = MatrixScale(camera.zoom, camera.zoom, 1.0f);
1510 Matrix matTranslation = MatrixTranslate(camera.offset.x, camera.offset.y, 0.0f);
1511
1512 matTransform = MatrixMultiply(MatrixMultiply(matOrigin, MatrixMultiply(matScale, matRotation)), matTranslation);
1513
1514 return matTransform;
1515 }
1516
1517 // Get the screen space position from a 3d world space position
1518 Vector2 GetWorldToScreen(Vector3 position, Camera camera)
1519 {
1520 Vector2 screenPosition = GetWorldToScreenEx(position, camera, GetScreenWidth(), GetScreenHeight());
1521
1522 return screenPosition;
1523 }
1524
1525 // Get size position for a 3d world space position (useful for texture drawing)
1526 Vector2 GetWorldToScreenEx(Vector3 position, Camera camera, int width, int height)
1527 {
1528 // Calculate projection matrix (from perspective instead of frustum
1529 Matrix matProj = MatrixIdentity();
1530
1531 if (camera.projection == CAMERA_PERSPECTIVE)
1532 {
1533 // Calculate projection matrix from perspective
1534 matProj = MatrixPerspective(camera.fovy*DEG2RAD, ((double)width/(double)height), rlGetCullDistanceNear(), rlGetCullDistanceFar());
1535 }
1536 else if (camera.projection == CAMERA_ORTHOGRAPHIC)
1537 {
1538 double aspect = (double)width/(double)height;
1539 double top = camera.fovy/2.0;
1540 double right = top*aspect;
1541
1542 // Calculate projection matrix from orthographic
1543 matProj = MatrixOrtho(-right, right, -top, top, rlGetCullDistanceNear(), rlGetCullDistanceFar());
1544 }
1545
1546 // Calculate view matrix from camera look at (and transpose it)
1547 Matrix matView = MatrixLookAt(camera.position, camera.target, camera.up);
1548
1549 // Convert world position vector to quaternion
1550 Quaternion worldPos = { position.x, position.y, position.z, 1.0f };
1551
1552 // Transform world position to view
1553 worldPos = QuaternionTransform(worldPos, matView);
1554
1555 // Transform result to projection (clip space position)
1556 worldPos = QuaternionTransform(worldPos, matProj);
1557
1558 // Calculate normalized device coordinates (inverted y)
1559 Vector3 ndcPos = { worldPos.x/worldPos.w, -worldPos.y/worldPos.w, worldPos.z/worldPos.w };
1560
1561 // Calculate 2d screen position vector
1562 Vector2 screenPosition = { (ndcPos.x + 1.0f)/2.0f*(float)width, (ndcPos.y + 1.0f)/2.0f*(float)height };
1563
1564 return screenPosition;
1565 }
1566
1567 // Get the screen space position for a 2d camera world space position
1568 Vector2 GetWorldToScreen2D(Vector2 position, Camera2D camera)
1569 {
1570 Matrix matCamera = GetCameraMatrix2D(camera);
1571 Vector3 transform = Vector3Transform((Vector3){ position.x, position.y, 0 }, matCamera);
1572
1573 return (Vector2){ transform.x, transform.y };
1574 }
1575
1576 // Get the world space position for a 2d camera screen space position
1577 Vector2 GetScreenToWorld2D(Vector2 position, Camera2D camera)
1578 {
1579 Matrix invMatCamera = MatrixInvert(GetCameraMatrix2D(camera));
1580 Vector3 transform = Vector3Transform((Vector3){ position.x, position.y, 0 }, invMatCamera);
1581
1582 return (Vector2){ transform.x, transform.y };
1583 }
1584
1585 //----------------------------------------------------------------------------------
1586 // Module Functions Definition: Timing
1587 //----------------------------------------------------------------------------------
1588
1589 // NOTE: Functions with a platform-specific implementation on rcore_<platform>.c
1590 //double GetTime(void)
1591
1592 // Set target FPS (maximum)
1593 void SetTargetFPS(int fps)
1594 {
1595 if (fps < 1) CORE.Time.target = 0.0;
1596 else CORE.Time.target = 1.0/(double)fps;
1597
1598 TRACELOG(LOG_INFO, "TIMER: Target time per frame: %02.03f milliseconds", (float)CORE.Time.target*1000.0f);
1599 }
1600
1601 // Get current FPS
1602 // NOTE: Calculating an average framerate
1603 int GetFPS(void)
1604 {
1605 int fps = 0;
1606
1607 #if !SUPPORT_CUSTOM_FRAME_CONTROL
1608 #define FPS_CAPTURE_FRAMES_COUNT 30 // 30 captures
1609 #define FPS_AVERAGE_TIME_SECONDS 0.5f // 500 milliseconds
1610 #define FPS_STEP (FPS_AVERAGE_TIME_SECONDS/FPS_CAPTURE_FRAMES_COUNT)
1611
1612 static int index = 0;
1613 static float history[FPS_CAPTURE_FRAMES_COUNT] = { 0 };
1614 static float average = 0, last = 0;
1615 float fpsFrame = GetFrameTime();
1616
1617 // If reseting the window, reset the FPS info
1618 if (CORE.Time.frameCounter == 0)
1619 {
1620 average = 0;
1621 last = 0;
1622 index = 0;
1623
1624 for (int i = 0; i < FPS_CAPTURE_FRAMES_COUNT; i++) history[i] = 0;
1625 }
1626
1627 if (fpsFrame != 0)
1628 {
1629 if ((GetTime() - last) > FPS_STEP)
1630 {
1631 last = (float)GetTime();
1632 index = (index + 1)%FPS_CAPTURE_FRAMES_COUNT;
1633 average -= history[index];
1634 history[index] = fpsFrame/FPS_CAPTURE_FRAMES_COUNT;
1635 average += history[index];
1636 }
1637
1638 fps = (int)roundf(1.0f/average);
1639 }
1640 else fps = 0;
1641 #endif
1642
1643 return fps;
1644 }
1645
1646 // Get time in seconds for last frame drawn (delta time)
1647 float GetFrameTime(void)
1648 {
1649 return (float)CORE.Time.frame;
1650 }
1651
1652 //----------------------------------------------------------------------------------
1653 // Module Functions Definition: Custom frame control
1654 //----------------------------------------------------------------------------------
1655
1656 // NOTE: Functions with a platform-specific implementation on rcore_<platform>.c
1657 //void SwapScreenBuffer(void);
1658 //void PollInputEvents(void);
1659
1660 // Wait for some time (stop program execution)
1661 // NOTE: Sleep() granularity could be around 10 ms, it means, Sleep() could
1662 // take longer than expected... for that reason a busy wait loop is used
1663 // REF: http://stackoverflow.com/questions/43057578/c-programming-win32-games-sleep-taking-longer-than-expected
1664 // REF: http://www.geisswerks.com/ryan/FAQS/timing.html --> All about timing on Win32!
1665 void WaitTime(double seconds)
1666 {
1667 if (seconds < 0) return; // Security check
1668
1669 #if SUPPORT_BUSY_WAIT_LOOP || SUPPORT_PARTIALBUSY_WAIT_LOOP
1670 double destinationTime = GetTime() + seconds;
1671 #endif
1672
1673 #if SUPPORT_BUSY_WAIT_LOOP
1674 while (GetTime() < destinationTime) { }
1675 #else
1676 #if SUPPORT_PARTIALBUSY_WAIT_LOOP
1677 double sleepSeconds = seconds - seconds*0.05; // NOTE: Reserve a percentage of the time for busy waiting
1678 #else
1679 double sleepSeconds = seconds;
1680 #endif
1681
1682 // System halt functions
1683 #if defined(_WIN32)
1684 Sleep((unsigned long)(sleepSeconds*1000.0));
1685 #endif
1686 #if defined(__linux__) || defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__EMSCRIPTEN__)
1687 struct timespec req = { 0 };
1688 time_t sec = sleepSeconds;
1689 long nsec = (sleepSeconds - sec)*1000000000L;
1690 req.tv_sec = sec;
1691 req.tv_nsec = nsec;
1692
1693 // NOTE: Use nanosleep() on Unix platforms... usleep() it's deprecated
1694 while (nanosleep(&req, &req) == -1) continue;
1695 #endif
1696 #if defined(__APPLE__)
1697 usleep(sleepSeconds*1000000.0);
1698 #endif
1699
1700 #if SUPPORT_PARTIALBUSY_WAIT_LOOP
1701 while (GetTime() < destinationTime) { }
1702 #endif
1703 #endif
1704 }
1705
1706 //----------------------------------------------------------------------------------
1707 // Module Functions Definition: Misc
1708 //----------------------------------------------------------------------------------
1709
1710 // NOTE: Functions with a platform-specific implementation on rcore_<platform>.c
1711 //void OpenURL(const char *url)
1712
1713 // Set the seed for the random number generator
1714 void SetRandomSeed(unsigned int seed)
1715 {
1716 #if SUPPORT_RPRAND_GENERATOR
1717 rprand_set_seed(seed);
1718 #else
1719 srand(seed);
1720 #endif
1721 }
1722
1723 // Get a random value between min and max included
1724 int GetRandomValue(int min, int max)
1725 {
1726 int value = 0;
1727
1728 if (min > max)
1729 {
1730 int tmp = max;
1731 max = min;
1732 min = tmp;
1733 }
1734
1735 #if SUPPORT_RPRAND_GENERATOR
1736 value = rprand_get_value(min, max);
1737 #else
1738 // WARNING: Ranges higher than RAND_MAX will return invalid results
1739 // More specifically, if (max - min) > INT_MAX there will be an overflow,
1740 // and otherwise if (max - min) > RAND_MAX the random value will incorrectly never exceed a certain threshold
1741 // NOTE: Depending on the library it can be as low as 32767
1742 if ((unsigned int)(max - min) > (unsigned int)RAND_MAX)
1743 {
1744 TRACELOG(LOG_WARNING, "Invalid GetRandomValue() arguments, range should not be higher than %i", RAND_MAX);
1745 }
1746
1747 // NOTE: This one-line approach produces a non-uniform distribution,
1748 // as stated by Donald Knuth in the book The Art of Programming, so
1749 // using below approach for more uniform results
1750 //value = (rand()%(abs(max - min) + 1) + min);
1751
1752 // More uniform range solution
1753 int range = (max - min) + 1;
1754
1755 // Degenerate/overflow case: fall back to min (same behavior as "always min" instead of UB)
1756 if (range <= 0) value = min;
1757 else
1758 {
1759 // Rejection sampling to get a uniform integer in [min, max]
1760 unsigned long c = (unsigned long)RAND_MAX + 1UL; // number of possible rand() results
1761 unsigned long m = (unsigned long)range; // size of the target interval
1762 unsigned long t = c - (c%m); // largest multiple of m <= c
1763 unsigned long r = 0;
1764
1765 for (;;)
1766 {
1767 r = (unsigned long)rand();
1768 if (r < t) break; // Only accept values within the fair region
1769 }
1770
1771 value = min + (int)(r%m);
1772 }
1773 #endif
1774
1775 return value;
1776 }
1777
1778 // Load random values sequence, no values repeated, min and max included
1779 int *LoadRandomSequence(unsigned int count, int min, int max)
1780 {
1781 int *values = NULL;
1782
1783 #if SUPPORT_RPRAND_GENERATOR
1784 values = rprand_load_sequence(count, min, max);
1785 #else
1786 if (count > ((unsigned int)abs(max - min) + 1)) return values; // Security check
1787
1788 values = (int *)RL_CALLOC(count, sizeof(int));
1789
1790 int value = 0;
1791 bool dupValue = false;
1792
1793 for (int i = 0; i < (int)count;)
1794 {
1795 value = GetRandomValue(min, max);
1796 dupValue = false;
1797
1798 for (int j = 0; j < i; j++)
1799 {
1800 if (values[j] == value)
1801 {
1802 dupValue = true;
1803 break;
1804 }
1805 }
1806
1807 if (!dupValue)
1808 {
1809 values[i] = value;
1810 i++;
1811 }
1812 }
1813 #endif
1814
1815 return values;
1816 }
1817
1818 // Unload random values sequence
1819 void UnloadRandomSequence(int *sequence)
1820 {
1821 #if SUPPORT_RPRAND_GENERATOR
1822 rprand_unload_sequence(sequence);
1823 #else
1824 RL_FREE(sequence);
1825 #endif
1826 }
1827
1828 // Takes a screenshot of current screen
1829 // NOTE: Provided fileName should not contain paths, saving to working directory
1830 void TakeScreenshot(const char *fileName)
1831 {
1832 #if SUPPORT_MODULE_RTEXTURES
1833 // Security check to (partially) avoid malicious code
1834 if (strchr(fileName, '\'') != NULL) { TRACELOG(LOG_WARNING, "SYSTEM: Provided fileName could be potentially malicious, avoid [\'] character"); return; }
1835
1836 // Apply content scaling if required
1837 Vector2 scale = { 1.0f, 1.0f };
1838 if (FLAG_IS_SET(CORE.Window.flags, FLAG_WINDOW_HIGHDPI)) scale = GetWindowScaleDPI();
1839
1840 unsigned char *imgData = rlReadScreenPixels((int)((float)CORE.Window.render.width*scale.x), (int)((float)CORE.Window.render.height*scale.y));
1841 Image image = { imgData, (int)((float)CORE.Window.render.width*scale.x), (int)((float)CORE.Window.render.height*scale.y), 1, PIXELFORMAT_UNCOMPRESSED_R8G8B8A8 };
1842
1843 char path[MAX_FILEPATH_LENGTH] = { 0 };
1844 strncpy(path, TextFormat("%s/%s", CORE.Storage.basePath, fileName), MAX_FILEPATH_LENGTH - 1);
1845
1846 ExportImage(image, path); // WARNING: Module required: rtextures
1847 RL_FREE(imgData);
1848
1849 if (FileExists(path)) TRACELOG(LOG_INFO, "SYSTEM: [%s] Screenshot taken successfully", path);
1850 else TRACELOG(LOG_WARNING, "SYSTEM: [%s] Screenshot could not be saved", path);
1851 #else
1852 TRACELOG(LOG_WARNING,"IMAGE: ExportImage() requires module: rtextures");
1853 #endif
1854 }
1855
1856 // Setup window configuration flags (view FLAGS)
1857 // NOTE: This function is expected to be called before window creation,
1858 // because it sets up some flags for the window creation process
1859 // To configure window states after creation, use SetWindowState()
1860 void SetConfigFlags(unsigned int flags)
1861 {
1862 if (CORE.Window.ready) TRACELOG(LOG_WARNING, "WINDOW: SetConfigFlags called after window initialization, Use \"SetWindowState\" to set flags instead");
1863
1864 // Selected flags are set but not evaluated at this point,
1865 // flag evaluation happens at InitWindow() or SetWindowState()
1866 FLAG_SET(CORE.Window.flags, flags);
1867 }
1868
1869 // void OpenURL(const char *url); // Defined per platform
1870
1871 //----------------------------------------------------------------------------------
1872 // Module Functions Definition: Logging system
1873 //----------------------------------------------------------------------------------
1874 // Set the current threshold (minimum) log level
1875 void SetTraceLogLevel(int logType) { logTypeLevel = logType; }
1876
1877 // Show trace log messages (LOG_INFO, LOG_WARNING, LOG_ERROR, LOG_DEBUG)
1878 void TraceLog(int logType, const char *text, ...)
1879 {
1880 #if SUPPORT_TRACELOG
1881 // Message has level below current threshold, don't emit
1882 if ((logType < logTypeLevel) || (text == NULL)) return;
1883
1884 va_list args;
1885 va_start(args, text);
1886
1887 if (traceLog)
1888 {
1889 traceLog(logType, text, args);
1890 va_end(args);
1891 return;
1892 }
1893
1894 #if defined(PLATFORM_ANDROID)
1895 switch (logType)
1896 {
1897 case LOG_TRACE: __android_log_vprint(ANDROID_LOG_VERBOSE, "raylib", text, args); break;
1898 case LOG_DEBUG: __android_log_vprint(ANDROID_LOG_DEBUG, "raylib", text, args); break;
1899 case LOG_INFO: __android_log_vprint(ANDROID_LOG_INFO, "raylib", text, args); break;
1900 case LOG_WARNING: __android_log_vprint(ANDROID_LOG_WARN, "raylib", text, args); break;
1901 case LOG_ERROR: __android_log_vprint(ANDROID_LOG_ERROR, "raylib", text, args); break;
1902 case LOG_FATAL: __android_log_vprint(ANDROID_LOG_FATAL, "raylib", text, args); break;
1903 default: break;
1904 }
1905 #else
1906 char buffer[MAX_TRACELOG_MSG_LENGTH] = { 0 };
1907
1908 switch (logType)
1909 {
1910 case LOG_TRACE: strncpy(buffer, "TRACE: ", 8); break;
1911 case LOG_DEBUG: strncpy(buffer, "DEBUG: ", 8); break;
1912 case LOG_INFO: strncpy(buffer, "INFO: ", 7); break;
1913 case LOG_WARNING: strncpy(buffer, "WARNING: ", 10); break;
1914 case LOG_ERROR: strncpy(buffer, "ERROR: ", 8); break;
1915 case LOG_FATAL: strncpy(buffer, "FATAL: ", 8); break;
1916 default: break;
1917 }
1918
1919 unsigned int textLength = (unsigned int)strlen(text);
1920 memcpy(buffer + strlen(buffer), text, (textLength < (MAX_TRACELOG_MSG_LENGTH - 12))? textLength : (MAX_TRACELOG_MSG_LENGTH - 12));
1921 strcat(buffer, "\n");
1922 vprintf(buffer, args);
1923 fflush(stdout);
1924 #endif
1925
1926 va_end(args);
1927
1928 if (logType == LOG_FATAL) exit(EXIT_FAILURE); // If fatal logging, exit program
1929 #endif
1930 }
1931
1932 // Set custom trace log
1933 void SetTraceLogCallback(TraceLogCallback callback)
1934 {
1935 traceLog = callback;
1936 }
1937
1938 //----------------------------------------------------------------------------------
1939 // Module Functions Definition: Memory management
1940 //----------------------------------------------------------------------------------
1941 // Internal memory allocator
1942 // NOTE: Initializes to zero by default
1943 void *MemAlloc(unsigned int size)
1944 {
1945 void *ptr = RL_CALLOC(size, 1);
1946 return ptr;
1947 }
1948
1949 // Internal memory reallocator
1950 void *MemRealloc(void *ptr, unsigned int size)
1951 {
1952 void *ret = RL_REALLOC(ptr, size);
1953 return ret;
1954 }
1955
1956 // Internal memory free
1957 void MemFree(void *ptr)
1958 {
1959 RL_FREE(ptr);
1960 }
1961
1962 //----------------------------------------------------------------------------------
1963 // Module Functions Definition: File System management
1964 //----------------------------------------------------------------------------------
1965 // Load data from file into a buffer
1966 unsigned char *LoadFileData(const char *fileName, int *dataSize)
1967 {
1968 unsigned char *data = NULL;
1969 *dataSize = 0;
1970
1971 if (fileName != NULL)
1972 {
1973 if (loadFileData) return loadFileData(fileName, dataSize);
1974
1975 FILE *file = fopen(fileName, "rb");
1976
1977 if (file != NULL)
1978 {
1979 // WARNING: On binary streams SEEK_END could not be found,
1980 // using fseek() and ftell() could not work in some (rare) cases
1981 fseek(file, 0, SEEK_END);
1982 int size = ftell(file); // WARNING: ftell() returns 'long int', maximum size returned is INT_MAX (2147483647 bytes)
1983 fseek(file, 0, SEEK_SET);
1984
1985 if (size > 0)
1986 {
1987 data = (unsigned char *)RL_CALLOC(size, sizeof(unsigned char));
1988
1989 if (data != NULL)
1990 {
1991 // NOTE: fread() returns number of read elements instead of bytes, so reading [1 byte, size elements]
1992 size_t count = fread(data, sizeof(unsigned char), size, file);
1993
1994 // WARNING: fread() returns a size_t value, usually 'unsigned int' (32bit compilation) and 'unsigned long long' (64bit compilation)
1995 // dataSize is unified along raylib as a 'int' type, so, for file-sizes > INT_MAX (2147483647 bytes) there is a limitation
1996 if (count > 2147483647)
1997 {
1998 TRACELOG(LOG_WARNING, "FILEIO: [%s] File is bigger than 2147483647 bytes, avoid using LoadFileData()", fileName);
1999
2000 RL_FREE(data);
2001 data = NULL;
2002 }
2003 else
2004 {
2005 *dataSize = (int)count;
2006
2007 if ((*dataSize) != size) TRACELOG(LOG_WARNING, "FILEIO: [%s] File partially loaded (%i bytes out of %i)", fileName, dataSize, count);
2008 else TRACELOG(LOG_INFO, "FILEIO: [%s] File loaded successfully", fileName);
2009 }
2010 }
2011 else TRACELOG(LOG_WARNING, "FILEIO: [%s] Failed to allocated memory for file reading", fileName);
2012 }
2013 else TRACELOG(LOG_WARNING, "FILEIO: [%s] Failed to read file", fileName);
2014
2015 fclose(file);
2016 }
2017 else TRACELOG(LOG_WARNING, "FILEIO: [%s] Failed to open file", fileName);
2018 }
2019 else TRACELOG(LOG_WARNING, "FILEIO: File name provided is not valid");
2020
2021 return data;
2022 }
2023
2024 // Unload file data allocated by LoadFileData()
2025 void UnloadFileData(unsigned char *data)
2026 {
2027 RL_FREE(data);
2028 }
2029
2030 // Save data to file from buffer
2031 bool SaveFileData(const char *fileName, void *data, int dataSize)
2032 {
2033 bool result = false;
2034
2035 if (fileName != NULL)
2036 {
2037 if (saveFileData) return saveFileData(fileName, data, dataSize);
2038
2039 FILE *file = fopen(fileName, "wb");
2040
2041 if (file != NULL)
2042 {
2043 // WARNING: fwrite() returns a size_t value, usually 'unsigned int' (32bit compilation) and 'unsigned long long' (64bit compilation)
2044 // and expects a size_t input value but as dataSize is limited to INT_MAX (2147483647 bytes), there shouldn't be a problem
2045 int count = (int)fwrite(data, sizeof(unsigned char), dataSize, file);
2046
2047 if (count == 0) TRACELOG(LOG_WARNING, "FILEIO: [%s] Failed to write file", fileName);
2048 else if (count != dataSize) TRACELOG(LOG_WARNING, "FILEIO: [%s] File partially written", fileName);
2049 else TRACELOG(LOG_INFO, "FILEIO: [%s] File saved successfully", fileName);
2050
2051 int closed = fclose(file);
2052 if (closed == 0) result = true;
2053 }
2054 else TRACELOG(LOG_WARNING, "FILEIO: [%s] Failed to open file", fileName);
2055 }
2056 else TRACELOG(LOG_WARNING, "FILEIO: File name provided is not valid");
2057
2058 return result;
2059 }
2060
2061 // Export data to code (.h), returns true on success
2062 bool ExportDataAsCode(const unsigned char *data, int dataSize, const char *fileName)
2063 {
2064 bool result = false;
2065
2066 #ifndef TEXT_BYTES_PER_LINE
2067 #define TEXT_BYTES_PER_LINE 20
2068 #endif
2069
2070 // NOTE: Text data buffer size is estimated considering raw data size in bytes
2071 // and requiring 6 char bytes for every byte: "0x00, "
2072 char *txtData = (char *)RL_CALLOC(dataSize*6 + 2000, sizeof(char));
2073
2074 int byteCount = 0;
2075 byteCount += sprintf(txtData + byteCount, "////////////////////////////////////////////////////////////////////////////////////////\n");
2076 byteCount += sprintf(txtData + byteCount, "// //\n");
2077 byteCount += sprintf(txtData + byteCount, "// DataAsCode exporter v1.0 - Raw data exported as an array of bytes //\n");
2078 byteCount += sprintf(txtData + byteCount, "// //\n");
2079 byteCount += sprintf(txtData + byteCount, "// more info and bugs-report: github.com/raysan5/raylib //\n");
2080 byteCount += sprintf(txtData + byteCount, "// feedback and support: ray[at]raylib.com //\n");
2081 byteCount += sprintf(txtData + byteCount, "// //\n");
2082 byteCount += sprintf(txtData + byteCount, "// Copyright (c) 2022-2026 Ramon Santamaria (@raysan5) //\n");
2083 byteCount += sprintf(txtData + byteCount, "// //\n");
2084 byteCount += sprintf(txtData + byteCount, "////////////////////////////////////////////////////////////////////////////////////////\n\n");
2085
2086 // Get file name from path
2087 char varFileName[256] = { 0 };
2088 strncpy(varFileName, GetFileNameWithoutExt(fileName), 256 - 1);
2089 for (int i = 0; varFileName[i] != '\0'; i++)
2090 {
2091 // Convert variable name to uppercase
2092 if ((varFileName[i] >= 'a') && (varFileName[i] <= 'z')) { varFileName[i] = varFileName[i] - 32; }
2093 // Replace non valid character for C identifier with '_'
2094 else if (varFileName[i] == '.' || varFileName[i] == '-' || varFileName[i] == '?' || varFileName[i] == '!' || varFileName[i] == '+') { varFileName[i] = '_'; }
2095 }
2096
2097 byteCount += sprintf(txtData + byteCount, "#define %s_DATA_SIZE %i\n\n", varFileName, dataSize);
2098
2099 byteCount += sprintf(txtData + byteCount, "static unsigned char %s_DATA[%s_DATA_SIZE] = { ", varFileName, varFileName);
2100 for (int i = 0; i < (dataSize - 1); i++) byteCount += sprintf(txtData + byteCount, ((i%TEXT_BYTES_PER_LINE == 0)? "0x%x,\n" : "0x%x, "), data[i]);
2101 byteCount += sprintf(txtData + byteCount, "0x%x };\n", data[dataSize - 1]);
2102
2103 // NOTE: Text data size exported is determined by '\0' (NULL) character
2104 result = SaveFileText(fileName, txtData);
2105
2106 RL_FREE(txtData);
2107
2108 if (result != 0) TRACELOG(LOG_INFO, "FILEIO: [%s] Data as code exported successfully", fileName);
2109 else TRACELOG(LOG_WARNING, "FILEIO: [%s] Failed to export data as code", fileName);
2110
2111 return result;
2112 }
2113
2114 // Load text data from file, returns a '\0' terminated string
2115 // NOTE: text chars array should be freed manually
2116 char *LoadFileText(const char *fileName)
2117 {
2118 char *text = NULL;
2119
2120 if (fileName != NULL)
2121 {
2122 if (loadFileText) return loadFileText(fileName);
2123
2124 FILE *file = fopen(fileName, "rt");
2125
2126 if (file != NULL)
2127 {
2128 // WARNING: When reading a file as 'text' file,
2129 // text mode causes carriage return-linefeed translation...
2130 // ...but using fseek() should return correct byte-offset
2131 fseek(file, 0, SEEK_END);
2132 unsigned int size = (unsigned int)ftell(file);
2133 fseek(file, 0, SEEK_SET);
2134
2135 if (size > 0)
2136 {
2137 text = (char *)RL_CALLOC(size + 1, sizeof(char));
2138
2139 if (text != NULL)
2140 {
2141 unsigned int count = (unsigned int)fread(text, sizeof(char), size, file);
2142
2143 // WARNING: \r\n is converted to \n on reading, so,
2144 // read bytes count gets reduced by the number of lines
2145 if (count < size) text = (char *)RL_REALLOC(text, count + 1);
2146
2147 // Zero-terminate the string
2148 text[count] = '\0';
2149
2150 TRACELOG(LOG_INFO, "FILEIO: [%s] Text file loaded successfully", fileName);
2151 }
2152 else TRACELOG(LOG_WARNING, "FILEIO: [%s] Failed to allocated memory for file reading", fileName);
2153 }
2154 else TRACELOG(LOG_WARNING, "FILEIO: [%s] Failed to read text file", fileName);
2155
2156 fclose(file);
2157 }
2158 else TRACELOG(LOG_WARNING, "FILEIO: [%s] Failed to open text file", fileName);
2159 }
2160 else TRACELOG(LOG_WARNING, "FILEIO: File name provided is not valid");
2161
2162 return text;
2163 }
2164
2165 // Unload file text data allocated by LoadFileText()
2166 void UnloadFileText(char *text)
2167 {
2168 RL_FREE(text);
2169 }
2170
2171 // Save text data to file (write), string must be '\0' terminated
2172 bool SaveFileText(const char *fileName, const char *text)
2173 {
2174 bool result = false;
2175
2176 if (fileName != NULL)
2177 {
2178 if (saveFileText) return saveFileText(fileName, text);
2179
2180 FILE *file = fopen(fileName, "wt");
2181
2182 if (file != NULL)
2183 {
2184 int count = fprintf(file, "%s", text);
2185
2186 if (count < 0) TRACELOG(LOG_WARNING, "FILEIO: [%s] Failed to write text file", fileName);
2187 else TRACELOG(LOG_INFO, "FILEIO: [%s] Text file saved successfully", fileName);
2188
2189 int closed = fclose(file);
2190 if (closed == 0) result = true;
2191 }
2192 else TRACELOG(LOG_WARNING, "FILEIO: [%s] Failed to open text file", fileName);
2193 }
2194 else TRACELOG(LOG_WARNING, "FILEIO: File name provided is not valid");
2195
2196 return result;
2197 }
2198
2199 // File access custom callbacks
2200 // WARNING: Callbacks setup is intended for advanced users
2201
2202 // Set custom file binary data loader
2203 void SetLoadFileDataCallback(LoadFileDataCallback callback)
2204 {
2205 loadFileData = callback;
2206 }
2207
2208 // Set custom file binary data saver
2209 void SetSaveFileDataCallback(SaveFileDataCallback callback)
2210 {
2211 saveFileData = callback;
2212 }
2213
2214 // Set custom file text data loader
2215 void SetLoadFileTextCallback(LoadFileTextCallback callback)
2216 {
2217 loadFileText = callback;
2218 }
2219
2220 // Set custom file text data saver
2221 void SetSaveFileTextCallback(SaveFileTextCallback callback)
2222 {
2223 saveFileText = callback;
2224 }
2225
2226 // Rename file (if exists)
2227 // NOTE: Only rename file name required, not full path
2228 int FileRename(const char *fileName, const char *fileRename)
2229 {
2230 int result = 0;
2231
2232 if (FileExists(fileName))
2233 {
2234 result = rename(fileName, fileRename);
2235 }
2236 else result = -1;
2237
2238 return result;
2239 }
2240
2241 // Remove file (if exists)
2242 int FileRemove(const char *fileName)
2243 {
2244 int result = 0;
2245
2246 if (FileExists(fileName))
2247 {
2248 result = remove(fileName);
2249 }
2250 else result = -1;
2251
2252 return result;
2253 }
2254
2255 // Copy file from one path to another
2256 // NOTE: If destination path does not exist, it is created!
2257 int FileCopy(const char *srcPath, const char *dstPath)
2258 {
2259 int result = 0;
2260 int srcDataSize = 0;
2261 unsigned char *srcFileData = LoadFileData(srcPath, &srcDataSize);
2262
2263 // Create required paths if they do not exist
2264 if (!DirectoryExists(GetDirectoryPath(dstPath)))
2265 result = MakeDirectory(GetDirectoryPath(dstPath));
2266
2267 if (result == 0) // Directory created successfully (or already exists)
2268 {
2269 if ((srcFileData != NULL) && (srcDataSize > 0))
2270 result = SaveFileData(dstPath, srcFileData, srcDataSize);
2271 }
2272
2273 UnloadFileData(srcFileData);
2274
2275 return result;
2276 }
2277
2278 // Move file from one directory to another
2279 // NOTE: If dst directories do not exists they are created
2280 int FileMove(const char *srcPath, const char *dstPath)
2281 {
2282 int result = -1;
2283
2284 if (FileExists(srcPath))
2285 {
2286 if (FileCopy(srcPath, dstPath) == 0) result = FileRemove(srcPath);
2287 else TRACELOG(LOG_WARNING, "FILEIO: [%s] Failed to copy file to [%s]", srcPath, dstPath);
2288 }
2289 else TRACELOG(LOG_WARNING, "FILEIO: [%s] Source file does not exist", srcPath);
2290
2291 return result;
2292 }
2293
2294 // Replace text in an existing file
2295 // WARNING: DEPENDENCY: [rtext] module
2296 int FileTextReplace(const char *fileName, const char *search, const char *replacement)
2297 {
2298 int result = 0;
2299 char *fileText = NULL;
2300 char *fileTextUpdated = { 0 };
2301
2302 #if SUPPORT_MODULE_RTEXT
2303 if (FileExists(fileName))
2304 {
2305 fileText = LoadFileText(fileName);
2306 fileTextUpdated = TextReplaceAlloc(fileText, search, replacement);
2307 result = SaveFileText(fileName, fileTextUpdated);
2308 MemFree(fileTextUpdated);
2309 UnloadFileText(fileText);
2310 }
2311 #else
2312 TRACELOG(LOG_WARNING, "FILE: File text replace requires [rtext] module");
2313 #endif
2314
2315 return result;
2316 }
2317
2318 // Find text index position in existing file
2319 // WARNING: DEPENDENCY: [rtext] module
2320 int FileTextFindIndex(const char *fileName, const char *search)
2321 {
2322 int result = -1;
2323
2324 if (FileExists(fileName))
2325 {
2326 char *fileText = LoadFileText(fileName);
2327 char *ptr = strstr(fileText, search);
2328 if (ptr != NULL) result = (int)(ptr - fileText);
2329 UnloadFileText(fileText);
2330 }
2331
2332 return result;
2333 }
2334
2335 // Check if the file exists
2336 bool FileExists(const char *fileName)
2337 {
2338 bool result = false;
2339
2340 if (ACCESS(fileName) != -1) result = true;
2341
2342 // NOTE: Alternatively, stat() can be used instead of access()
2343 //#include <sys/stat.h>
2344 //struct stat statbuf;
2345 //if (stat(filename, &statbuf) == 0) result = true;
2346
2347 return result;
2348 }
2349
2350 // Check file extension
2351 bool IsFileExtension(const char *fileName, const char *ext)
2352 {
2353 #define MAX_FILE_EXTENSIONS 32
2354
2355 bool result = false;
2356 const char *fileExt = GetFileExtension(fileName);
2357
2358 // WARNING: fileExt points to last '.' on fileName string but it could happen
2359 // that fileName is not correct: "myfile.png more text following\n"
2360
2361 if (fileExt != NULL)
2362 {
2363 int fileExtLength = (int)strlen(fileExt);
2364 char fileExtLower[16] = { 0 };
2365 char *fileExtLowerPtr = fileExtLower;
2366 for (int i = 0; (i < fileExtLength) && (i < 16); i++)
2367 {
2368 // Copy and convert to lower-case
2369 if ((fileExt[i] >= 'A') && (fileExt[i] <= 'Z')) fileExtLower[i] = fileExt[i] + 32;
2370 else fileExtLower[i] = fileExt[i];
2371 }
2372
2373 int extCount = 1;
2374 int extLength = (int)strlen(ext);
2375 char *extList = (char *)RL_CALLOC(extLength + 1, 1);
2376 char *extListPtrs[MAX_FILE_EXTENSIONS] = { 0 };
2377 strncpy(extList, ext, extLength);
2378 extListPtrs[0] = extList;
2379
2380 for (int i = 0; i < extLength; i++)
2381 {
2382 // Convert to lower-case if extension is upper-case
2383 if ((extList[i] >= 'A') && (extList[i] <= 'Z')) extList[i] += 32;
2384
2385 // Get pointer to next extension and add null-terminator
2386 if ((extList[i] == ';') && (extCount < (MAX_FILE_EXTENSIONS - 1)))
2387 {
2388 extList[i] = '\0';
2389 extListPtrs[extCount] = extList + i + 1;
2390 extCount++;
2391 }
2392 }
2393
2394 for (int i = 0; i < extCount; i++)
2395 {
2396 // Consider the case where extension provided
2397 // does not start with the '.'
2398 fileExtLowerPtr = fileExtLower;
2399 if (extListPtrs[i][0] != '.') fileExtLowerPtr++;
2400
2401 if (strcmp(fileExtLowerPtr, extListPtrs[i]) == 0)
2402 {
2403 result = true;
2404 break;
2405 }
2406 }
2407
2408 RL_FREE(extList);
2409 }
2410
2411 return result;
2412 }
2413
2414 // Check if a directory path exists
2415 bool DirectoryExists(const char *dirPath)
2416 {
2417 bool result = false;
2418 DIR *dir = opendir(dirPath);
2419
2420 if (dir != NULL)
2421 {
2422 result = true;
2423 closedir(dir);
2424 }
2425
2426 return result;
2427 }
2428
2429 // Get file length in bytes
2430 // NOTE: GetFileSize() conflicts with windows.h
2431 int GetFileLength(const char *fileName)
2432 {
2433 int size = 0;
2434
2435 // NOTE: On Unix-like systems, it can by used the POSIX system call: stat(),
2436 // but depending on the platform that call could not be available
2437 //struct stat result = { 0 };
2438 //stat(fileName, &result);
2439 //return result.st_size;
2440
2441 FILE *file = fopen(fileName, "rb");
2442
2443 if (file != NULL)
2444 {
2445 fseek(file, 0L, SEEK_END);
2446 long int fileSize = ftell(file);
2447
2448 // Check for size overflow (INT_MAX)
2449 if (fileSize > 2147483647) TRACELOG(LOG_WARNING, "[%s] File size overflows expected limit, do not use GetFileLength()", fileName);
2450 else size = (int)fileSize;
2451
2452 fclose(file);
2453 }
2454
2455 return size;
2456 }
2457
2458 // Get file modification time (last write time)
2459 long GetFileModTime(const char *fileName)
2460 {
2461 struct stat result = { 0 };
2462 long modTime = 0;
2463
2464 if (stat(fileName, &result) == 0)
2465 {
2466 time_t mod = result.st_mtime;
2467 modTime = (long)mod;
2468 }
2469
2470 return modTime;
2471 }
2472
2473 // Get pointer to extension for a filename string (includes the dot: .png)
2474 // WARNING: Getting the pointer to the input string extension position (not a string copy)
2475 const char *GetFileExtension(const char *fileName)
2476 {
2477 const char *dot = strrchr(fileName, '.');
2478
2479 if (!dot || (dot == fileName)) return NULL;
2480
2481 return dot;
2482 }
2483
2484 // String pointer reverse break: returns right-most occurrence of charset in s
2485 static const char *strprbrk(const char *text, const char *charset)
2486 {
2487 const char *latestMatch = NULL;
2488
2489 for (; (text != NULL) && (text = strpbrk(text, charset)); latestMatch = text++) { }
2490
2491 return latestMatch;
2492 }
2493
2494 // Get pointer to filename for a path string
2495 const char *GetFileName(const char *filePath)
2496 {
2497 const char *fileName = NULL;
2498
2499 if (filePath != NULL) fileName = strprbrk(filePath, "\\/");
2500
2501 if (fileName == NULL) return filePath;
2502
2503 return fileName + 1;
2504 }
2505
2506 // Get filename string without extension (uses static string)
2507 const char *GetFileNameWithoutExt(const char *filePath)
2508 {
2509 #define MAX_FILENAME_LENGTH 256
2510
2511 static char fileName[MAX_FILENAME_LENGTH] = { 0 };
2512 memset(fileName, 0, MAX_FILENAME_LENGTH);
2513
2514 if (filePath != NULL)
2515 {
2516 strncpy(fileName, GetFileName(filePath), MAX_FILENAME_LENGTH - 1); // Get filename.ext without path
2517 int fileNameLength = (int)strlen(fileName); // Get size in bytes
2518
2519 for (int i = fileNameLength; i > 0; i--) // Reverse search '.'
2520 {
2521 if (fileName[i] == '.')
2522 {
2523 // NOTE: Break on first '.' found
2524 fileName[i] = '\0';
2525 break;
2526 }
2527 }
2528 }
2529
2530 return fileName;
2531 }
2532
2533 // Get directory for a given filePath
2534 const char *GetDirectoryPath(const char *filePath)
2535 {
2536 /*
2537 // NOTE: Directory separator is different in Windows and other platforms,
2538 // fortunately, Windows also support the '/' separator, that's the one should be used
2539 #if defined(_WIN32)
2540 char separator = '\\';
2541 #else
2542 char separator = '/';
2543 #endif
2544 */
2545 const char *lastSlash = NULL;
2546 static char dirPath[MAX_FILEPATH_LENGTH] = { 0 };
2547 memset(dirPath, 0, MAX_FILEPATH_LENGTH);
2548
2549 // In case provided path does not contain a root drive letter (C:\, D:\)
2550 // nor leading path separator (\, /), add the current directory path to dirPath
2551 if ((filePath[1] != ':') && (filePath[0] != '\\') && (filePath[0] != '/'))
2552 {
2553 // For security, set starting path to current directory,
2554 // obtained path will be concatenated to this
2555 dirPath[0] = '.';
2556 dirPath[1] = '/';
2557 }
2558
2559 lastSlash = strprbrk(filePath, "\\/");
2560 if (lastSlash)
2561 {
2562 if (lastSlash == filePath)
2563 {
2564 // The last and only slash is the leading one: path is in a root directory
2565 dirPath[0] = filePath[0];
2566 dirPath[1] = '\0';
2567 }
2568 else
2569 {
2570 // NOTE: Be careful, strncpy() is not safe, it does not care about '\0'
2571 char *dirPathPtr = dirPath;
2572 if ((filePath[1] != ':') && (filePath[0] != '\\') && (filePath[0] != '/')) dirPathPtr += 2; // Skip drive letter, "C:"
2573 memcpy(dirPathPtr, filePath, strlen(filePath) - (strlen(lastSlash) - 1));
2574 dirPath[strlen(filePath) - strlen(lastSlash) + (((filePath[1] != ':') && (filePath[0] != '\\') && (filePath[0] != '/'))? 2 : 0)] = '\0'; // Add '\0' manually
2575 }
2576 }
2577
2578 return dirPath;
2579 }
2580
2581 // Get previous directory path for a given path
2582 const char *GetPrevDirectoryPath(const char *dirPath)
2583 {
2584 static char prevDirPath[MAX_FILEPATH_LENGTH] = { 0 };
2585 memset(prevDirPath, 0, MAX_FILEPATH_LENGTH);
2586 int dirPathLength = (int)strlen(dirPath);
2587
2588 if (dirPathLength <= 3) strncpy(prevDirPath, dirPath, MAX_FILEPATH_LENGTH - 1);
2589
2590 for (int i = (dirPathLength - 1); (i >= 0) && (dirPathLength > 3); i--)
2591 {
2592 if ((dirPath[i] == '\\') || (dirPath[i] == '/'))
2593 {
2594 // Check for root: "C:\" or "/"
2595 if (((i == 2) && (dirPath[1] ==':')) || (i == 0)) i++;
2596
2597 strncpy(prevDirPath, dirPath, i);
2598 break;
2599 }
2600 }
2601
2602 return prevDirPath;
2603 }
2604
2605 // Get current working directory
2606 const char *GetWorkingDirectory(void)
2607 {
2608 static char currentDir[MAX_FILEPATH_LENGTH] = { 0 };
2609 memset(currentDir, 0, MAX_FILEPATH_LENGTH);
2610
2611 char *path = GETCWD(currentDir, MAX_FILEPATH_LENGTH - 1);
2612
2613 return path;
2614 }
2615
2616 const char *GetApplicationDirectory(void)
2617 {
2618 static char appDir[MAX_FILEPATH_LENGTH] = { 0 };
2619 memset(appDir, 0, MAX_FILEPATH_LENGTH);
2620
2621 #if defined(_WIN32)
2622 int len = 0;
2623
2624 #if defined(UNICODE)
2625 unsigned short widePath[MAX_PATH];
2626 len = GetModuleFileNameW(NULL, (wchar_t *)widePath, MAX_PATH);
2627 len = WideCharToMultiByte(0, 0, (wchar_t *)widePath, len, appDir, MAX_PATH, NULL, NULL);
2628 #else
2629 len = GetModuleFileNameA(NULL, appDir, MAX_PATH);
2630 #endif
2631
2632 if (len > 0)
2633 {
2634 for (int i = len; i >= 0; i--)
2635 {
2636 if (appDir[i] == '\\')
2637 {
2638 appDir[i + 1] = '\0';
2639 break;
2640 }
2641 }
2642 }
2643 else
2644 {
2645 appDir[0] = '.';
2646 appDir[1] = '\\';
2647 }
2648
2649 #elif defined(__linux__)
2650
2651 unsigned int size = sizeof(appDir);
2652 ssize_t len = readlink("/proc/self/exe", appDir, size);
2653
2654 if (len > 0)
2655 {
2656 for (int i = len; i >= 0; i--)
2657 {
2658 if (appDir[i] == '/')
2659 {
2660 appDir[i + 1] = '\0';
2661 break;
2662 }
2663 }
2664 }
2665 else
2666 {
2667 appDir[0] = '.';
2668 appDir[1] = '/';
2669 }
2670
2671 #elif defined(__APPLE__)
2672
2673 uint32_t size = sizeof(appDir);
2674
2675 if (_NSGetExecutablePath(appDir, &size) == 0)
2676 {
2677 int appDirLength = (int)strlen(appDir);
2678 for (int i = appDirLength; i >= 0; i--)
2679 {
2680 if (appDir[i] == '/')
2681 {
2682 appDir[i + 1] = '\0';
2683 break;
2684 }
2685 }
2686 }
2687 else
2688 {
2689 appDir[0] = '.';
2690 appDir[1] = '/';
2691 }
2692
2693 #elif defined(__FreeBSD__)
2694
2695 size_t size = sizeof(appDir);
2696 int mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_PATHNAME, -1};
2697
2698 if (sysctl(mib, 4, appDir, &size, NULL, 0) == 0)
2699 {
2700 int appDirLength = (int)strlen(appDir);
2701 for (int i = appDirLength; i >= 0; i--)
2702 {
2703 if (appDir[i] == '/')
2704 {
2705 appDir[i + 1] = '\0';
2706 break;
2707 }
2708 }
2709 }
2710 else
2711 {
2712 appDir[0] = '.';
2713 appDir[1] = '/';
2714 }
2715
2716 #elif defined(__wasm__)
2717
2718 appDir[0] = '/';
2719 #endif
2720
2721 return appDir;
2722 }
2723
2724 // Load directory filepaths
2725 // NOTE: Base path is prepended to the scanned filepaths
2726 // WARNING: Directory is scanned twice, first time to get paths count
2727 // Scanneed files and directories, no recursive/subdirs scanning
2728 FilePathList LoadDirectoryFiles(const char *dirPath)
2729 {
2730 return LoadDirectoryFilesEx(dirPath, FILE_FILTER_TAG_ALL, false);
2731 }
2732
2733 // Load directory filepaths with extension filtering and recursive directory scan
2734 // Use "*.*" to include all files and directories on scan
2735 // Use "FILES*" to include only files on scan
2736 // Use "DIRS*" to include only directories on scan
2737 // WARNING: Directory is scanned twice, first time to get paths count
2738 FilePathList LoadDirectoryFilesEx(const char *basePath, const char *filter, bool scanSubdirs)
2739 {
2740 FilePathList files = { 0 };
2741
2742 if (DirectoryExists(basePath)) // It's a directory
2743 {
2744 if ((filter != NULL) && (filter[0] == '\0')) filter = NULL;
2745
2746 // SCAN 1: Count files
2747 unsigned int fileCounter = GetDirectoryFileCountEx(basePath, filter, scanSubdirs);
2748
2749 // Memory allocation for dirFileCount
2750 files.paths = (char **)RL_CALLOC(fileCounter, sizeof(char *));
2751 for (unsigned int i = 0; i < fileCounter; i++) files.paths[i] = (char *)RL_CALLOC(MAX_FILEPATH_LENGTH, sizeof(char));
2752
2753 // SCAN 2: Read filepaths
2754 // WARNING: basePath is always prepended to scanned paths
2755 ScanDirectoryFiles(basePath, &files, filter, fileCounter, scanSubdirs);
2756
2757 // Security check: read files.count should match fileCounter
2758 if (files.count != fileCounter)
2759 {
2760 TRACELOG(LOG_WARNING, "FILEIO: Read files count (%u) does not match capacity allocated (%u)", files.count, fileCounter);
2761 files.count = fileCounter; // Avoid memory leak when unloading this FilePathList
2762 }
2763 }
2764 else TRACELOG(LOG_WARNING, "FILEIO: Directory cannot be opened (%s)", basePath); // Maybe it's a file...
2765
2766 return files;
2767 }
2768
2769 // Unload directory filepaths
2770 // WARNING: files.count is not reseted to 0 after unloading
2771 void UnloadDirectoryFiles(FilePathList files)
2772 {
2773 if (files.paths != NULL)
2774 {
2775 for (unsigned int i = 0; i < files.count; i++) RL_FREE(files.paths[i]);
2776
2777 RL_FREE(files.paths);
2778 }
2779 }
2780
2781 // Create directories (including full path requested), returns 0 on success
2782 int MakeDirectory(const char *dirPath)
2783 {
2784 if ((dirPath == NULL) || (dirPath[0] == '\0')) return -1; // Path is not valid
2785 if (DirectoryExists(dirPath)) return 0; // Path already exists (is valid)
2786
2787 // Copy path string to avoid modifying original
2788 int dirPathLength = (int)strlen(dirPath) + 1;
2789 char *pathcpy = (char *)RL_CALLOC(dirPathLength, 1);
2790 memcpy(pathcpy, dirPath, dirPathLength);
2791
2792 // Iterate over pathcpy, create each subdirectory as needed
2793 for (int i = 0; (i < dirPathLength) && (pathcpy[i] != '\0'); i++)
2794 {
2795 if (pathcpy[i] == ':') i++;
2796 else
2797 {
2798 if ((pathcpy[i] == '\\') || (pathcpy[i] == '/'))
2799 {
2800 pathcpy[i] = '\0';
2801 if (!DirectoryExists(pathcpy)) MKDIR(pathcpy);
2802 pathcpy[i] = '/';
2803 }
2804 }
2805 }
2806
2807 // Create final directory
2808 if (!DirectoryExists(pathcpy)) MKDIR(pathcpy);
2809 RL_FREE(pathcpy);
2810
2811 // In case something failed and requested directory
2812 // was not successfully created, return -1
2813 if (!DirectoryExists(dirPath)) return -1;
2814
2815 return 0;
2816 }
2817
2818 // Change working directory, returns true on success
2819 bool ChangeDirectory(const char *dirPath)
2820 {
2821 bool result = CHDIR(dirPath);
2822
2823 if (result != 0) TRACELOG(LOG_WARNING, "SYSTEM: Failed to change to directory: %s", dirPath);
2824 else TRACELOG(LOG_INFO, "SYSTEM: Working Directory: %s", dirPath);
2825
2826 return (result == 0);
2827 }
2828
2829 // Check if a given path point to a file
2830 bool IsPathFile(const char *path)
2831 {
2832 struct stat result = { 0 };
2833 stat(path, &result);
2834
2835 return S_ISREG(result.st_mode);
2836 }
2837
2838 // Check if fileName is valid for the platform/OS
2839 bool IsFileNameValid(const char *fileName)
2840 {
2841 bool valid = true;
2842
2843 if ((fileName != NULL) && (fileName[0] != '\0'))
2844 {
2845 int fileNameLength = (int)strlen(fileName);
2846 bool allPeriods = true;
2847
2848 for (int i = 0; i < fileNameLength; i++)
2849 {
2850 // Check invalid characters
2851 if ((fileName[i] == '<') ||
2852 (fileName[i] == '>') ||
2853 (fileName[i] == ':') ||
2854 (fileName[i] == '\"') ||
2855 (fileName[i] == '/') ||
2856 (fileName[i] == '\\') ||
2857 (fileName[i] == '|') ||
2858 (fileName[i] == '?') ||
2859 (fileName[i] == '*')) { valid = false; break; }
2860
2861 // Check non-glyph characters
2862 if ((unsigned char)fileName[i] < 32) { valid = false; break; }
2863
2864 // Check if filename is not all periods
2865 if (fileName[i] != '.') allPeriods = false;
2866 }
2867
2868 if (allPeriods) valid = false;
2869
2870 /*
2871 if (valid)
2872 {
2873 // Check invalid DOS names
2874 if (fileNameLength >= 3)
2875 {
2876 if (((fileName[0] == 'C') && (fileName[1] == 'O') && (fileName[2] == 'N')) || // CON
2877 ((fileName[0] == 'P') && (fileName[1] == 'R') && (fileName[2] == 'N')) || // PRN
2878 ((fileName[0] == 'A') && (fileName[1] == 'U') && (fileName[2] == 'X')) || // AUX
2879 ((fileName[0] == 'N') && (fileName[1] == 'U') && (fileName[2] == 'L'))) valid = false; // NUL
2880 }
2881
2882 if (fileNameLength >= 4)
2883 {
2884 if (((fileName[0] == 'C') && (fileName[1] == 'O') && (fileName[2] == 'M') && ((fileName[3] >= '0') && (fileName[3] <= '9'))) || // COM0-9
2885 ((fileName[0] == 'L') && (fileName[1] == 'P') && (fileName[2] == 'T') && ((fileName[3] >= '0') && (fileName[3] <= '9')))) valid = false; // LPT0-9
2886 }
2887 }
2888 */
2889 }
2890
2891 return valid;
2892 }
2893
2894 // Check if a file has been dropped into window
2895 bool IsFileDropped(void)
2896 {
2897 bool result = false;
2898
2899 if (CORE.Window.dropFileCount > 0) result = true;
2900
2901 return result;
2902 }
2903
2904 // Load dropped filepaths
2905 FilePathList LoadDroppedFiles(void)
2906 {
2907 FilePathList files = { 0 };
2908
2909 files.count = CORE.Window.dropFileCount;
2910 files.paths = CORE.Window.dropFilepaths;
2911
2912 return files;
2913 }
2914
2915 // Unload dropped filepaths
2916 void UnloadDroppedFiles(FilePathList files)
2917 {
2918 // WARNING: files pointers are the same as internal ones
2919
2920 if (files.count > 0)
2921 {
2922 for (unsigned int i = 0; i < files.count; i++) RL_FREE(files.paths[i]);
2923
2924 RL_FREE(files.paths);
2925
2926 CORE.Window.dropFileCount = 0;
2927 CORE.Window.dropFilepaths = NULL;
2928 }
2929 }
2930
2931 // Get the file count in a directory
2932 unsigned int GetDirectoryFileCount(const char *dirPath)
2933 {
2934 return GetDirectoryFileCountEx(dirPath, FILE_FILTER_TAG_ALL, false);
2935 }
2936
2937 // Get the file count in a directory with extension filtering and recursive directory scan. Use 'FILE_FILTER_TAG_DIR_ONLY' in the filter string to include directories in the result
2938 unsigned int GetDirectoryFileCountEx(const char *basePath, const char *filter, bool scanSubdirs)
2939 {
2940 unsigned int fileCounter = 0;
2941
2942 // WARNING: Path can not be static or it will be reused between recursive function calls!
2943 char path[MAX_FILEPATH_LENGTH] = { 0 };
2944 memset(path, 0, MAX_FILEPATH_LENGTH);
2945
2946 struct dirent *entity;
2947 DIR *dir = opendir(basePath);
2948
2949 if (dir != NULL) // It's a directory
2950 {
2951 while ((entity = readdir(dir)) != NULL)
2952 {
2953 // NOTE: Skipping '.' (current dir) and '..' (parent dir) filepaths
2954 if ((strcmp(entity->d_name, ".") != 0) && (strcmp(entity->d_name, "..") != 0))
2955 {
2956 // Construct new path from our base path
2957 #if defined(_WIN32)
2958 int pathLength = snprintf(path, MAX_FILEPATH_LENGTH - 1, "%s\\%s", basePath, entity->d_name);
2959 #else
2960 int pathLength = snprintf(path, MAX_FILEPATH_LENGTH - 1, "%s/%s", basePath, entity->d_name);
2961 #endif
2962 // Don't add to count if path too long
2963 if ((pathLength < 0) || (pathLength >= MAX_FILEPATH_LENGTH))
2964 {
2965 TRACELOG(LOG_WARNING, "FILEIO: Path longer than %d characters (%s...)", MAX_FILEPATH_LENGTH, basePath);
2966 }
2967 else if (IsPathFile(path))
2968 {
2969 if ((filter == NULL) || (strstr(filter, FILE_FILTER_TAG_ALL) != NULL) ||
2970 (strstr(filter, FILE_FILTER_TAG_FILE_ONLY) != NULL) || IsFileExtension(path, filter)) fileCounter++;
2971 }
2972 else
2973 {
2974 if ((filter != NULL) && ((strstr(filter, FILE_FILTER_TAG_ALL) != NULL) || (strstr(filter, FILE_FILTER_TAG_DIR_ONLY) != NULL))) fileCounter++;
2975 if (scanSubdirs) fileCounter += GetDirectoryFileCountEx(path, filter, scanSubdirs);
2976 }
2977 }
2978 }
2979 closedir(dir);
2980 }
2981 else TRACELOG(LOG_WARNING, "FILEIO: Directory cannot be opened (%s)", basePath); // Maybe it's a file...
2982 return fileCounter;
2983 }
2984
2985 //----------------------------------------------------------------------------------
2986 // Module Functions Definition: Compression and Encoding
2987 //----------------------------------------------------------------------------------
2988
2989 // Compress data (DEFLATE algorithm)
2990 unsigned char *CompressData(const unsigned char *data, int dataSize, int *compDataSize)
2991 {
2992 #define COMPRESSION_QUALITY_DEFLATE 8
2993
2994 unsigned char *compData = NULL;
2995
2996 #if SUPPORT_COMPRESSION_API
2997 // Compress data and generate a valid DEFLATE stream
2998 struct sdefl *sdefl = (struct sdefl *)RL_CALLOC(1, sizeof(struct sdefl)); // WARNING: Possible stack overflow, struct sdefl is almost 1MB
2999 int bounds = sdefl_bound(dataSize);
3000 compData = (unsigned char *)RL_CALLOC(bounds, 1);
3001
3002 *compDataSize = sdeflate(sdefl, compData, data, dataSize, COMPRESSION_QUALITY_DEFLATE); // Compression level 8, same as stbiw
3003 RL_FREE(sdefl);
3004
3005 TRACELOG(LOG_INFO, "SYSTEM: Compress data: Original size: %i -> Comp. size: %i", dataSize, *compDataSize);
3006 #endif
3007
3008 return compData;
3009 }
3010
3011 // Decompress data (DEFLATE algorithm)
3012 unsigned char *DecompressData(const unsigned char *compData, int compDataSize, int *dataSize)
3013 {
3014 unsigned char *data = NULL;
3015
3016 #if SUPPORT_COMPRESSION_API
3017 // Decompress data from a valid DEFLATE stream
3018 unsigned char *data0 = (unsigned char *)RL_CALLOC(MAX_DECOMPRESSION_SIZE*1024*1024, 1);
3019 int size = sinflate(data0, MAX_DECOMPRESSION_SIZE*1024*1024, compData, compDataSize);
3020
3021 // WARNING: RL_REALLOC can make (and leave) data copies in memory,
3022 // that can be a security concern in case of compression of sensitive data
3023 // So, using a second buffer to copy data manually, wiping original buffer memory
3024 data = (unsigned char *)RL_CALLOC(size, 1);
3025 memcpy(data, data0, size);
3026 memset(data0, 0, MAX_DECOMPRESSION_SIZE*1024*1024); // Wipe memory, is memset() safe?
3027 RL_FREE(data0);
3028
3029 TRACELOG(LOG_INFO, "SYSTEM: Decompress data: Comp. size: %i -> Original size: %i", compDataSize, size);
3030
3031 *dataSize = size;
3032 #endif
3033
3034 return data;
3035 }
3036
3037 // Encode data to Base64 string
3038 // NOTE: Returned string includes NULL terminator, considered on outputSize
3039 char *EncodeDataBase64(const unsigned char *data, int dataSize, int *outputSize)
3040 {
3041 // Base64 conversion table from RFC 4648 [0..63]
3042 // NOTE: They represent 64 values (6 bits), to encode 3 bytes of data into 4 "sextets" (6bit characters)
3043 static const char base64EncodeTable[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
3044
3045 // Compute expected size and padding
3046 int paddedSize = dataSize;
3047 while (paddedSize%3 != 0) paddedSize++; // Padding bytes to round 4*(dataSize/3) to 4 bytes
3048 int estimatedOutputSize = 4*(paddedSize/3);
3049 int padding = paddedSize - dataSize;
3050
3051 // Adding null terminator to string
3052 estimatedOutputSize += 1;
3053
3054 // Load some memory to store encoded string
3055 char *encodedData = (char *)RL_CALLOC(estimatedOutputSize, 1);
3056 if (encodedData == NULL) return NULL;
3057
3058 int outputCount = 0;
3059 for (int i = 0; i < dataSize;)
3060 {
3061 unsigned int octetA = 0;
3062 unsigned int octetB = 0;
3063 unsigned int octetC = 0;
3064 unsigned int octetPack = 0;
3065
3066 octetA = data[i]; // Generates 2 sextets
3067 octetB = ((i + 1) < dataSize)? data[i + 1] : 0; // Generates 3 sextets
3068 octetC = ((i + 2) < dataSize)? data[i + 2] : 0; // Generates 4 sextets
3069
3070 octetPack = (octetA << 16) | (octetB << 8) | octetC;
3071
3072 encodedData[outputCount + 0] = (unsigned char)(base64EncodeTable[(octetPack >> 18) & 0x3f]);
3073 encodedData[outputCount + 1] = (unsigned char)(base64EncodeTable[(octetPack >> 12) & 0x3f]);
3074 encodedData[outputCount + 2] = (unsigned char)(base64EncodeTable[(octetPack >> 6) & 0x3f]);
3075 encodedData[outputCount + 3] = (unsigned char)(base64EncodeTable[octetPack & 0x3f]);
3076 outputCount += 4;
3077 i += 3;
3078 }
3079
3080 // Add required padding bytes
3081 for (int p = 0; p < padding; p++) encodedData[outputCount - p - 1] = '=';
3082
3083 // Add null terminator to string
3084 encodedData[outputCount] = '\0';
3085 outputCount++;
3086
3087 if (outputCount != estimatedOutputSize) TRACELOG(LOG_WARNING, "BASE64: Output size differs from estimation");
3088
3089 *outputSize = estimatedOutputSize;
3090 return encodedData;
3091 }
3092
3093 // Decode Base64 string (expected NULL terminated)
3094 unsigned char *DecodeDataBase64(const char *text, int *outputSize)
3095 {
3096 // Base64 decode table
3097 // NOTE: Following ASCII order [0..255] assigning the expected sixtet value to
3098 // every character in the corresponding ASCII position
3099 static const unsigned char base64DecodeTable[256] = {
3100 ['A'] = 0, ['B'] = 1, ['C'] = 2, ['D'] = 3, ['E'] = 4, ['F'] = 5, ['G'] = 6, ['H'] = 7,
3101 ['I'] = 8, ['J'] = 9, ['K'] = 10, ['L'] = 11, ['M'] = 12, ['N'] = 13, ['O'] = 14, ['P'] = 15,
3102 ['Q'] = 16, ['R'] = 17, ['S'] = 18, ['T'] = 19, ['U'] = 20, ['V'] = 21, ['W'] = 22, ['X'] = 23, ['Y'] = 24, ['Z'] = 25,
3103 ['a'] = 26, ['b'] = 27, ['c'] = 28, ['d'] = 29, ['e'] = 30, ['f'] = 31, ['g'] = 32, ['h'] = 33,
3104 ['i'] = 34, ['j'] = 35, ['k'] = 36, ['l'] = 37, ['m'] = 38, ['n'] = 39, ['o'] = 40, ['p'] = 41,
3105 ['q'] = 42, ['r'] = 43, ['s'] = 44, ['t'] = 45, ['u'] = 46, ['v'] = 47, ['w'] = 48, ['x'] = 49, ['y'] = 50, ['z'] = 51,
3106 ['0'] = 52, ['1'] = 53, ['2'] = 54, ['3'] = 55, ['4'] = 56, ['5'] = 57, ['6'] = 58, ['7'] = 59,
3107 ['8'] = 60, ['9'] = 61, ['+'] = 62, ['/'] = 63
3108 };
3109
3110 *outputSize = 0;
3111 if (text == NULL) return NULL;
3112
3113 // Compute expected size and padding
3114 int dataSize = (int)strlen(text); // WARNING: Expecting NULL terminated strings!
3115 int ending = dataSize - 1;
3116 int padding = 0;
3117 while (text[ending] == '=') { padding++; ending--; }
3118 int estimatedOutputSize = 3*(dataSize/4) - padding;
3119 int maxOutputSize = 3*(dataSize/4);
3120
3121 // Load some memory to store decoded data
3122 // NOTE: Allocated enough size to include padding
3123 unsigned char *decodedData = (unsigned char *)RL_CALLOC(maxOutputSize, 1);
3124 if (decodedData == NULL) return NULL;
3125
3126 int outputCount = 0;
3127 for (int i = 0; i < dataSize;)
3128 {
3129 // Every 4 sextets must generate 3 octets
3130 if ((i + 2) >= dataSize)
3131 {
3132 TRACELOG(LOG_WARNING, "BASE64: Decoding error: Input data size is not valid");
3133 break;
3134 }
3135
3136 unsigned int sixtetA = base64DecodeTable[(unsigned char)text[i]];
3137 unsigned int sixtetB = base64DecodeTable[(unsigned char)text[i + 1]];
3138 unsigned int sixtetC = (((i + 2) < dataSize) && (unsigned char)text[i + 2] != '=')? base64DecodeTable[(unsigned char)text[i + 2]] : 0;
3139 unsigned int sixtetD = (((i + 3) < dataSize) && (unsigned char)text[i + 3] != '=')? base64DecodeTable[(unsigned char)text[i + 3]] : 0;
3140
3141 unsigned int octetPack = (sixtetA << 18) | (sixtetB << 12) | (sixtetC << 6) | sixtetD;
3142
3143 if ((outputCount + 3) > maxOutputSize)
3144 {
3145 TRACELOG(LOG_WARNING, "BASE64: Decoding error: Output data size is too small");
3146 break;
3147 }
3148
3149 decodedData[outputCount + 0] = (octetPack >> 16) & 0xff;
3150 decodedData[outputCount + 1] = (octetPack >> 8) & 0xff;
3151 decodedData[outputCount + 2] = octetPack & 0xff;
3152 outputCount += 3;
3153 i += 4;
3154 }
3155
3156 if (estimatedOutputSize != (outputCount - padding)) TRACELOG(LOG_WARNING, "BASE64: Decoded size differs from estimation");
3157
3158 *outputSize = estimatedOutputSize;
3159 return decodedData;
3160 }
3161
3162 // Compute CRC32 hash code
3163 unsigned int ComputeCRC32(unsigned char *data, int dataSize)
3164 {
3165 static unsigned int crcTable[256] = {
3166 0x00000000, 0x77073096, 0xee0e612c, 0x990951ba, 0x076dc419, 0x706af48f, 0xe963a535, 0x9e6495a3,
3167 0x0edb8832, 0x79dcb8a4, 0xe0d5e91e, 0x97d2d988, 0x09b64c2b, 0x7eb17cbd, 0xe7b82d07, 0x90bf1d91,
3168 0x1db71064, 0x6ab020f2, 0xf3b97148, 0x84be41de, 0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7,
3169 0x136c9856, 0x646ba8c0, 0xfd62f97a, 0x8a65c9ec, 0x14015c4f, 0x63066cd9, 0xfa0f3d63, 0x8d080df5,
3170 0x3b6e20c8, 0x4c69105e, 0xd56041e4, 0xa2677172, 0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b,
3171 0x35b5a8fa, 0x42b2986c, 0xdbbbc9d6, 0xacbcf940, 0x32d86ce3, 0x45df5c75, 0xdcd60dcf, 0xabd13d59,
3172 0x26d930ac, 0x51de003a, 0xc8d75180, 0xbfd06116, 0x21b4f4b5, 0x56b3c423, 0xcfba9599, 0xb8bda50f,
3173 0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924, 0x2f6f7c87, 0x58684c11, 0xc1611dab, 0xb6662d3d,
3174 0x76dc4190, 0x01db7106, 0x98d220bc, 0xefd5102a, 0x71b18589, 0x06b6b51f, 0x9fbfe4a5, 0xe8b8d433,
3175 0x7807c9a2, 0x0f00f934, 0x9609a88e, 0xe10e9818, 0x7f6a0dbb, 0x086d3d2d, 0x91646c97, 0xe6635c01,
3176 0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e, 0x6c0695ed, 0x1b01a57b, 0x8208f4c1, 0xf50fc457,
3177 0x65b0d9c6, 0x12b7e950, 0x8bbeb8ea, 0xfcb9887c, 0x62dd1ddf, 0x15da2d49, 0x8cd37cf3, 0xfbd44c65,
3178 0x4db26158, 0x3ab551ce, 0xa3bc0074, 0xd4bb30e2, 0x4adfa541, 0x3dd895d7, 0xa4d1c46d, 0xd3d6f4fb,
3179 0x4369e96a, 0x346ed9fc, 0xad678846, 0xda60b8d0, 0x44042d73, 0x33031de5, 0xaa0a4c5f, 0xdd0d7cc9,
3180 0x5005713c, 0x270241aa, 0xbe0b1010, 0xc90c2086, 0x5768b525, 0x206f85b3, 0xb966d409, 0xce61e49f,
3181 0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4, 0x59b33d17, 0x2eb40d81, 0xb7bd5c3b, 0xc0ba6cad,
3182 0xedb88320, 0x9abfb3b6, 0x03b6e20c, 0x74b1d29a, 0xead54739, 0x9dd277af, 0x04db2615, 0x73dc1683,
3183 0xe3630b12, 0x94643b84, 0x0d6d6a3e, 0x7a6a5aa8, 0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1,
3184 0xf00f9344, 0x8708a3d2, 0x1e01f268, 0x6906c2fe, 0xf762575d, 0x806567cb, 0x196c3671, 0x6e6b06e7,
3185 0xfed41b76, 0x89d32be0, 0x10da7a5a, 0x67dd4acc, 0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5,
3186 0xd6d6a3e8, 0xa1d1937e, 0x38d8c2c4, 0x4fdff252, 0xd1bb67f1, 0xa6bc5767, 0x3fb506dd, 0x48b2364b,
3187 0xd80d2bda, 0xaf0a1b4c, 0x36034af6, 0x41047a60, 0xdf60efc3, 0xa867df55, 0x316e8eef, 0x4669be79,
3188 0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236, 0xcc0c7795, 0xbb0b4703, 0x220216b9, 0x5505262f,
3189 0xc5ba3bbe, 0xb2bd0b28, 0x2bb45a92, 0x5cb36a04, 0xc2d7ffa7, 0xb5d0cf31, 0x2cd99e8b, 0x5bdeae1d,
3190 0x9b64c2b0, 0xec63f226, 0x756aa39c, 0x026d930a, 0x9c0906a9, 0xeb0e363f, 0x72076785, 0x05005713,
3191 0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0x0cb61b38, 0x92d28e9b, 0xe5d5be0d, 0x7cdcefb7, 0x0bdbdf21,
3192 0x86d3d2d4, 0xf1d4e242, 0x68ddb3f8, 0x1fda836e, 0x81be16cd, 0xf6b9265b, 0x6fb077e1, 0x18b74777,
3193 0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c, 0x8f659eff, 0xf862ae69, 0x616bffd3, 0x166ccf45,
3194 0xa00ae278, 0xd70dd2ee, 0x4e048354, 0x3903b3c2, 0xa7672661, 0xd06016f7, 0x4969474d, 0x3e6e77db,
3195 0xaed16a4a, 0xd9d65adc, 0x40df0b66, 0x37d83bf0, 0xa9bcae53, 0xdebb9ec5, 0x47b2cf7f, 0x30b5ffe9,
3196 0xbdbdf21c, 0xcabac28a, 0x53b39330, 0x24b4a3a6, 0xbad03605, 0xcdd70693, 0x54de5729, 0x23d967bf,
3197 0xb3667a2e, 0xc4614ab8, 0x5d681b02, 0x2a6f2b94, 0xb40bbe37, 0xc30c8ea1, 0x5a05df1b, 0x2d02ef8d
3198 };
3199
3200 unsigned int crc = ~0u;
3201
3202 for (int i = 0; i < dataSize; i++) crc = (crc >> 8) ^ crcTable[data[i] ^ (crc & 0xff)];
3203
3204 return ~crc;
3205 }
3206
3207 // Compute MD5 hash code
3208 // NOTE: Returns a static int[4] array (16 bytes)
3209 unsigned int *ComputeMD5(unsigned char *data, int dataSize)
3210 {
3211 #define ROTATE_LEFT(x, c) (((x) << (c)) | ((x) >> (32 - (c))))
3212
3213 static unsigned int hash[4] = { 0 }; // Hash to be returned
3214
3215 // WARNING: All variables are unsigned 32 bit and wrap modulo 2^32 when calculating
3216
3217 // NOTE: r specifies the per-round shift amounts
3218 unsigned int r[] = {
3219 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22,
3220 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20,
3221 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23,
3222 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21
3223 };
3224
3225 // Using binary integer part of the sines of integers (in radians) as constants
3226 unsigned int k[] = {
3227 0xd76aa478, 0xe8c7b756, 0x242070db, 0xc1bdceee,
3228 0xf57c0faf, 0x4787c62a, 0xa8304613, 0xfd469501,
3229 0x698098d8, 0x8b44f7af, 0xffff5bb1, 0x895cd7be,
3230 0x6b901122, 0xfd987193, 0xa679438e, 0x49b40821,
3231 0xf61e2562, 0xc040b340, 0x265e5a51, 0xe9b6c7aa,
3232 0xd62f105d, 0x02441453, 0xd8a1e681, 0xe7d3fbc8,
3233 0x21e1cde6, 0xc33707d6, 0xf4d50d87, 0x455a14ed,
3234 0xa9e3e905, 0xfcefa3f8, 0x676f02d9, 0x8d2a4c8a,
3235 0xfffa3942, 0x8771f681, 0x6d9d6122, 0xfde5380c,
3236 0xa4beea44, 0x4bdecfa9, 0xf6bb4b60, 0xbebfbc70,
3237 0x289b7ec6, 0xeaa127fa, 0xd4ef3085, 0x04881d05,
3238 0xd9d4d039, 0xe6db99e5, 0x1fa27cf8, 0xc4ac5665,
3239 0xf4292244, 0x432aff97, 0xab9423a7, 0xfc93a039,
3240 0x655b59c3, 0x8f0ccc92, 0xffeff47d, 0x85845dd1,
3241 0x6fa87e4f, 0xfe2ce6e0, 0xa3014314, 0x4e0811a1,
3242 0xf7537e82, 0xbd3af235, 0x2ad7d2bb, 0xeb86d391
3243 };
3244
3245 hash[0] = 0x67452301;
3246 hash[1] = 0xefcdab89;
3247 hash[2] = 0x98badcfe;
3248 hash[3] = 0x10325476;
3249
3250 // Pre-processing: adding a single 1 bit
3251 // Append '1' bit to message
3252 // NOTE: The input bytes are considered as bits strings,
3253 // where the first bit is the most significant bit of the byte
3254
3255 // Pre-processing: padding with zeros
3256 // Append '0' bit until message length in bit 448 (mod 512)
3257 // Append length mod (2 pow 64) to message
3258
3259 int newDataSize = ((((dataSize + 8)/64) + 1)*64) - 8;
3260
3261 unsigned char *msg = (unsigned char *)RL_CALLOC(newDataSize + 64, 1); // Initialize with '0' bits, allocating 64 extra bytes
3262 memcpy(msg, data, dataSize);
3263 msg[dataSize] = 128; // Write the '1' bit
3264
3265 unsigned int bitsLen = 8*dataSize;
3266 memcpy(msg + newDataSize, &bitsLen, 4); // Append the len in bits at the end of the buffer
3267
3268 // Process the message in successive 512-bit chunks for each 512-bit chunk of message
3269 for (int offset = 0; offset < newDataSize; offset += (512/8))
3270 {
3271 // Break chunk into sixteen 32-bit words w[j], 0 <= j <= 15
3272 unsigned int *w = (unsigned int *)(msg + offset);
3273
3274 // Initialize hash value for this chunk
3275 unsigned int a = hash[0];
3276 unsigned int b = hash[1];
3277 unsigned int c = hash[2];
3278 unsigned int d = hash[3];
3279
3280 for (int i = 0; i < 64; i++)
3281 {
3282 unsigned int f = 0;
3283 unsigned int g = 0;
3284
3285 if (i < 16)
3286 {
3287 f = (b & c) | ((~b) & d);
3288 g = i;
3289 }
3290 else if (i < 32)
3291 {
3292 f = (d & b) | ((~d) & c);
3293 g = (5*i + 1)%16;
3294 }
3295 else if (i < 48)
3296 {
3297 f = b ^ c ^ d;
3298 g = (3*i + 5)%16;
3299 }
3300 else
3301 {
3302 f = c ^ (b | (~d));
3303 g = (7*i)%16;
3304 }
3305
3306 unsigned int temp = d;
3307 d = c;
3308 c = b;
3309 b = b + ROTATE_LEFT((a + f + k[i] + w[g]), r[i]);
3310 a = temp;
3311 }
3312
3313 // Add chunk's hash to result so far
3314 hash[0] += a;
3315 hash[1] += b;
3316 hash[2] += c;
3317 hash[3] += d;
3318 }
3319
3320 RL_FREE(msg);
3321
3322 return hash;
3323 }
3324
3325 // Compute SHA-1 hash code
3326 // NOTE: Returns a static int[5] array (20 bytes)
3327 unsigned int *ComputeSHA1(unsigned char *data, int dataSize)
3328 {
3329 #define SHA1_ROTATE_LEFT(x, c) (((x) << (c)) | ((x) >> (32 - (c))))
3330
3331 static unsigned int hash[5] = { 0 }; // Hash to be returned
3332
3333 // Initialize hash values
3334 hash[0] = 0x67452301;
3335 hash[1] = 0xEFCDAB89;
3336 hash[2] = 0x98BADCFE;
3337 hash[3] = 0x10325476;
3338 hash[4] = 0xC3D2E1F0;
3339
3340 // Pre-processing: adding a single 1 bit
3341 // Append '1' bit to message
3342 // NOTE: The input bytes are considered as bits strings,
3343 // where the first bit is the most significant bit of the byte
3344
3345 // Pre-processing: padding with zeros
3346 // Append '0' bit until message length in bit 448 (mod 512)
3347 // Append length mod (2 pow 64) to message
3348
3349 int newDataSize = ((((dataSize + 8)/64) + 1)*64);
3350
3351 unsigned char *msg = (unsigned char *)RL_CALLOC(newDataSize, 1); // Initialize with '0' bits
3352 memcpy(msg, data, dataSize);
3353 msg[dataSize] = 128; // Write the '1' bit
3354
3355 unsigned long long bitsLen = 8ULL * dataSize;
3356 msg[newDataSize-1] = (unsigned char)(bitsLen);
3357 msg[newDataSize-2] = (unsigned char)(bitsLen >> 8);
3358 msg[newDataSize-3] = (unsigned char)(bitsLen >> 16);
3359 msg[newDataSize-4] = (unsigned char)(bitsLen >> 24);
3360 msg[newDataSize-5] = (unsigned char)(bitsLen >> 32);
3361 msg[newDataSize-6] = (unsigned char)(bitsLen >> 40);
3362 msg[newDataSize-7] = (unsigned char)(bitsLen >> 48);
3363 msg[newDataSize-8] = (unsigned char)(bitsLen >> 56);
3364
3365 // Process the message in successive 512-bit chunks
3366 for (int offset = 0; offset < newDataSize; offset += (512/8))
3367 {
3368 // Break chunk into sixteen 32-bit words w[j], 0 <= j <= 15
3369 unsigned int w[80] = { 0 };
3370 for (int i = 0; i < 16; i++)
3371 {
3372 w[i] = (msg[offset + (i*4) + 0] << 24) |
3373 (msg[offset + (i*4) + 1] << 16) |
3374 (msg[offset + (i*4) + 2] << 8) |
3375 (msg[offset + (i*4) + 3]);
3376 }
3377
3378 // Message schedule: extend the sixteen 32-bit words into eighty 32-bit words:
3379 for (int i = 16; i < 80; i++) w[i] = SHA1_ROTATE_LEFT(w[i-3] ^ w[i-8] ^ w[i-14] ^ w[i-16], 1);
3380
3381 // Initialize hash value for this chunk
3382 unsigned int a = hash[0];
3383 unsigned int b = hash[1];
3384 unsigned int c = hash[2];
3385 unsigned int d = hash[3];
3386 unsigned int e = hash[4];
3387
3388 for (int i = 0; i < 80; i++)
3389 {
3390 unsigned int f = 0;
3391 unsigned int k = 0;
3392
3393 if (i < 20)
3394 {
3395 f = (b & c) | ((~b) & d);
3396 k = 0x5A827999;
3397 }
3398 else if (i < 40)
3399 {
3400 f = b ^ c ^ d;
3401 k = 0x6ED9EBA1;
3402 }
3403 else if (i < 60)
3404 {
3405 f = (b & c) | (b & d) | (c & d);
3406 k = 0x8F1BBCDC;
3407 }
3408 else
3409 {
3410 f = b ^ c ^ d;
3411 k = 0xCA62C1D6;
3412 }
3413
3414 unsigned int temp = SHA1_ROTATE_LEFT(a, 5) + f + e + k + w[i];
3415 e = d;
3416 d = c;
3417 c = SHA1_ROTATE_LEFT(b, 30);
3418 b = a;
3419 a = temp;
3420 }
3421
3422 // Add this chunk's hash to result so far
3423 hash[0] += a;
3424 hash[1] += b;
3425 hash[2] += c;
3426 hash[3] += d;
3427 hash[4] += e;
3428 }
3429
3430 RL_FREE(msg);
3431
3432 return hash;
3433 }
3434
3435 // Compute SHA-256 hash code
3436 // NOTE: Returns a static int[8] array (32 bytes)
3437 unsigned int *ComputeSHA256(unsigned char *data, int dataSize)
3438 {
3439 #define SHA256_ROTATE_RIGHT(x, c) ((x >> c) | (x << ((sizeof(unsigned int)*8) - c)))
3440 #define SHA256_A0(x) (SHA256_ROTATE_RIGHT(x, 7) ^ SHA256_ROTATE_RIGHT(x, 18) ^ (x >> 3))
3441 #define SHA256_A1(x) (SHA256_ROTATE_RIGHT(x, 17) ^ SHA256_ROTATE_RIGHT(x, 19) ^ (x >> 10))
3442
3443 static const unsigned int k[64] = {
3444 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5,
3445 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
3446 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3,
3447 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
3448 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc,
3449 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
3450 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7,
3451 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
3452 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13,
3453 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
3454 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3,
3455 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
3456 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5,
3457 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
3458 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208,
3459 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2
3460 };
3461
3462 static unsigned int hash[8] = { 0 };
3463 hash[0] = 0x6A09e667;
3464 hash[1] = 0xbb67ae85;
3465 hash[2] = 0x3c6ef372;
3466 hash[3] = 0xa54ff53a;
3467 hash[4] = 0x510e527f;
3468 hash[5] = 0x9b05688c;
3469 hash[6] = 0x1f83d9ab;
3470 hash[7] = 0x5be0cd19;
3471
3472 const unsigned long long int bitLen = ((unsigned long long int)dataSize)*8;
3473 unsigned long long int paddedSize = dataSize + sizeof(dataSize);
3474 paddedSize += (64 - (paddedSize%64));
3475 unsigned char *buffer = (unsigned char *)RL_CALLOC(paddedSize, sizeof(unsigned char));
3476
3477 memcpy(buffer, data, dataSize);
3478 buffer[dataSize] = 0x80;
3479 for (int i = 1; i <= sizeof(bitLen); i++)
3480 {
3481 buffer[(paddedSize - sizeof(bitLen)) + (i - 1)] = (bitLen >> (8*(sizeof(bitLen) - i))) & 0xFF;
3482 }
3483
3484 for (unsigned long long int blockN = 0; blockN < paddedSize/64; blockN++)
3485 {
3486 unsigned int a = hash[0];
3487 unsigned int b = hash[1];
3488 unsigned int c = hash[2];
3489 unsigned int d = hash[3];
3490 unsigned int e = hash[4];
3491 unsigned int f = hash[5];
3492 unsigned int g = hash[6];
3493 unsigned int h = hash[7];
3494
3495 unsigned char *block = buffer + (blockN*64);
3496 unsigned int w[64] = { 0 };
3497 for (int i = 0; i < 16; i++)
3498 {
3499 w[i] = ((unsigned int)block[i*4 + 0] << 24) |
3500 ((unsigned int)block[i*4 + 1] << 16) |
3501 ((unsigned int)block[i*4 + 2] << 8) |
3502 ((unsigned int)block[i*4 + 3]);
3503 }
3504 for (int t = 16; t < 64; t++) w[t] = SHA256_A1(w[t - 2]) + w[t - 7] + SHA256_A0(w[t - 15]) + w[t - 16];
3505
3506 for (unsigned long long int t = 0; t < 64; t++)
3507 {
3508 unsigned int e1 = (SHA256_ROTATE_RIGHT(e, 6) ^ SHA256_ROTATE_RIGHT(e, 11) ^ SHA256_ROTATE_RIGHT(e, 25));
3509 unsigned int ch = ((e & f) ^ (~e & g));
3510 unsigned int t1 = (h + e1 + ch + k[t] + w[t]);
3511 unsigned int e0 = (SHA256_ROTATE_RIGHT(a, 2) ^ SHA256_ROTATE_RIGHT(a, 13) ^ SHA256_ROTATE_RIGHT(a, 22));
3512 unsigned int maj = ((a & b) ^ (a & c) ^ (b & c));
3513 unsigned int t2 = e0 + maj;
3514
3515 h = g;
3516 g = f;
3517 f = e;
3518 e = d + t1;
3519 d = c;
3520 c = b;
3521 b = a;
3522 a = t1 + t2;
3523 }
3524
3525 hash[0] += a;
3526 hash[1] += b;
3527 hash[2] += c;
3528 hash[3] += d;
3529 hash[4] += e;
3530 hash[5] += f;
3531 hash[6] += g;
3532 hash[7] += h;
3533 }
3534
3535 RL_FREE(buffer);
3536
3537 return hash;
3538 }
3539
3540 //----------------------------------------------------------------------------------
3541 // Module Functions Definition: Automation Events Recording and Playing
3542 //----------------------------------------------------------------------------------
3543
3544 // Load automation events list from file, NULL for empty list, capacity = MAX_AUTOMATION_EVENTS
3545 AutomationEventList LoadAutomationEventList(const char *fileName)
3546 {
3547 AutomationEventList list = { 0 };
3548
3549 #if SUPPORT_AUTOMATION_EVENTS
3550 // Allocate and empty automation event list, ready to record new events
3551 list.events = (AutomationEvent *)RL_CALLOC(MAX_AUTOMATION_EVENTS, sizeof(AutomationEvent));
3552 list.capacity = MAX_AUTOMATION_EVENTS;
3553
3554 if (fileName == NULL) TRACELOG(LOG_INFO, "AUTOMATION: New empty events list loaded successfully");
3555 else
3556 {
3557 // Load automation events file (binary)
3558 /*
3559 //int dataSize = 0;
3560 //unsigned char *data = LoadFileData(fileName, &dataSize);
3561
3562 FILE *raeFile = fopen(fileName, "rb");
3563 unsigned char fileId[4] = { 0 };
3564
3565 fread(fileId, 1, 4, raeFile);
3566
3567 if ((fileId[0] == 'r') && (fileId[1] == 'A') && (fileId[2] == 'E') && (fileId[1] == ' '))
3568 {
3569 fread(&eventCount, sizeof(int), 1, raeFile);
3570 TRACELOG(LOG_WARNING, "Events loaded: %i\n", eventCount);
3571 fread(events, sizeof(AutomationEvent), eventCount, raeFile);
3572 }
3573
3574 fclose(raeFile);
3575 */
3576
3577 // Load events file (text)
3578 //unsigned char *buffer = LoadFileText(fileName);
3579 FILE *raeFile = fopen(fileName, "rt");
3580
3581 if (raeFile != NULL)
3582 {
3583 unsigned int counter = 0;
3584 char buffer[256] = { 0 };
3585 char eventDesc[64] = { 0 };
3586
3587 char *result = fgets(buffer, 256, raeFile);
3588 if (result != buffer) TRACELOG(LOG_WARNING, "AUTOMATION: [%s] Issue reading line to buffer", fileName);
3589
3590 while (!feof(raeFile))
3591 {
3592 switch (buffer[0])
3593 {
3594 case 'c': sscanf(buffer, "c %i", &list.count); break;
3595 case 'e':
3596 {
3597 sscanf(buffer, "e %d %d %d %d %d %d %[^\n]s", &list.events[counter].frame, &list.events[counter].type,
3598 &list.events[counter].params[0], &list.events[counter].params[1], &list.events[counter].params[2], &list.events[counter].params[3], eventDesc);
3599
3600 counter++;
3601 } break;
3602 default: break;
3603 }
3604
3605 result = fgets(buffer, 256, raeFile);
3606 if (result != buffer) TRACELOG(LOG_WARNING, "AUTOMATION: [%s] Issue reading line to buffer", fileName);
3607 }
3608
3609 if (counter != list.count)
3610 {
3611 TRACELOG(LOG_WARNING, "AUTOMATION: Events read from file [%i] do not mach event count specified [%i]", counter, list.count);
3612 list.count = counter;
3613 }
3614
3615 fclose(raeFile);
3616
3617 TRACELOG(LOG_INFO, "AUTOMATION: Events file loaded successfully");
3618 }
3619
3620 TRACELOG(LOG_INFO, "AUTOMATION: Events loaded from file: %i", list.count);
3621 }
3622 #endif
3623 return list;
3624 }
3625
3626 // Unload automation events list from file
3627 void UnloadAutomationEventList(AutomationEventList list)
3628 {
3629 #if SUPPORT_AUTOMATION_EVENTS
3630 RL_FREE(list.events);
3631 #endif
3632 }
3633
3634 // Export automation events list as text file
3635 bool ExportAutomationEventList(AutomationEventList list, const char *fileName)
3636 {
3637 bool result = false;
3638
3639 #if SUPPORT_AUTOMATION_EVENTS
3640 // Export events as binary file
3641 // NOTE: Code not used, only for reference if required in the future
3642 /*
3643 if (list.count > 0)
3644 {
3645 int binarySize = 4 + sizeof(int) + sizeof(AutomationEvent)*list.count;
3646 unsigned char *binBuffer = (unsigned char *)RL_CALLOC(binarySize, 1);
3647 int offset = 0;
3648 memcpy(binBuffer + offset, "rAE ", 4);
3649 offset += 4;
3650 memcpy(binBuffer + offset, &list.count, sizeof(int));
3651 offset += sizeof(int);
3652 memcpy(binBuffer + offset, list.events, sizeof(AutomationEvent)*list.count);
3653 offset += sizeof(AutomationEvent)*list.count;
3654
3655 result = SaveFileData(TextFormat("%s.rae",fileName), binBuffer, binarySize);
3656 RL_FREE(binBuffer);
3657 }
3658 */
3659
3660 // Export events as text
3661 // NOTE: Save to memory buffer and SaveFileText()
3662 char *txtData = (char *)RL_CALLOC(256*list.count + 2048, sizeof(char)); // 256 characters per line plus some header
3663
3664 int byteCount = 0;
3665 byteCount += sprintf(txtData + byteCount, "#\n");
3666 byteCount += sprintf(txtData + byteCount, "# Automation events exporter v1.0 - raylib automation events list\n");
3667 byteCount += sprintf(txtData + byteCount, "#\n");
3668 byteCount += sprintf(txtData + byteCount, "# c <events_count>\n");
3669 byteCount += sprintf(txtData + byteCount, "# e <frame> <event_type> <param0> <param1> <param2> <param3> // <event_type_name>\n");
3670 byteCount += sprintf(txtData + byteCount, "#\n");
3671 byteCount += sprintf(txtData + byteCount, "# more info and bugs-report: github.com/raysan5/raylib\n");
3672 byteCount += sprintf(txtData + byteCount, "# feedback and support: ray[at]raylib.com\n");
3673 byteCount += sprintf(txtData + byteCount, "#\n");
3674 byteCount += sprintf(txtData + byteCount, "# Copyright (c) 2023-2026 Ramon Santamaria (@raysan5)\n");
3675 byteCount += sprintf(txtData + byteCount, "#\n\n");
3676
3677 // Add events data
3678 byteCount += sprintf(txtData + byteCount, "c %i\n", list.count);
3679 for (unsigned int i = 0; i < list.count; i++)
3680 {
3681 byteCount += snprintf(txtData + byteCount, 256, "e %i %i %i %i %i %i // Event: %s\n", list.events[i].frame, list.events[i].type,
3682 list.events[i].params[0], list.events[i].params[1], list.events[i].params[2], list.events[i].params[3], autoEventTypeName[list.events[i].type]);
3683 }
3684
3685 // NOTE: Text data size exported is determined by '\0' (NULL) character
3686 result = SaveFileText(fileName, txtData);
3687
3688 RL_FREE(txtData);
3689 #endif
3690
3691 return result;
3692 }
3693
3694 // Setup automation event list to record to
3695 void SetAutomationEventList(AutomationEventList *list)
3696 {
3697 #if SUPPORT_AUTOMATION_EVENTS
3698 currentEventList = list;
3699 #endif
3700 }
3701
3702 // Set automation event internal base frame to start recording
3703 void SetAutomationEventBaseFrame(int frame)
3704 {
3705 CORE.Time.frameCounter = frame;
3706 }
3707
3708 // Start recording automation events (AutomationEventList must be set)
3709 void StartAutomationEventRecording(void)
3710 {
3711 #if SUPPORT_AUTOMATION_EVENTS
3712 automationEventRecording = true;
3713 #endif
3714 }
3715
3716 // Stop recording automation events
3717 void StopAutomationEventRecording(void)
3718 {
3719 #if SUPPORT_AUTOMATION_EVENTS
3720 automationEventRecording = false;
3721 #endif
3722 }
3723
3724 // Play a recorded automation event
3725 void PlayAutomationEvent(AutomationEvent event)
3726 {
3727 #if SUPPORT_AUTOMATION_EVENTS
3728 // WARNING: When should event be played? After/before/replace PollInputEvents()? -> Up to the user!
3729
3730 if (!automationEventRecording)
3731 {
3732 switch (event.type)
3733 {
3734 // Input event
3735 case INPUT_KEY_UP: CORE.Input.Keyboard.currentKeyState[event.params[0]] = false; break; // param[0]: key
3736 case INPUT_KEY_DOWN: { // param[0]: key
3737 CORE.Input.Keyboard.currentKeyState[event.params[0]] = true;
3738
3739 if (CORE.Input.Keyboard.previousKeyState[event.params[0]] == false)
3740 {
3741 if (CORE.Input.Keyboard.keyPressedQueueCount < MAX_KEY_PRESSED_QUEUE)
3742 {
3743 // Add character to the queue
3744 CORE.Input.Keyboard.keyPressedQueue[CORE.Input.Keyboard.keyPressedQueueCount] = event.params[0];
3745 CORE.Input.Keyboard.keyPressedQueueCount++;
3746 }
3747 }
3748 } break;
3749 case INPUT_MOUSE_BUTTON_UP: CORE.Input.Mouse.currentButtonState[event.params[0]] = false; break; // param[0]: key
3750 case INPUT_MOUSE_BUTTON_DOWN: CORE.Input.Mouse.currentButtonState[event.params[0]] = true; break; // param[0]: key
3751 case INPUT_MOUSE_POSITION: // param[0]: x, param[1]: y
3752 {
3753 CORE.Input.Mouse.currentPosition.x = (float)event.params[0];
3754 CORE.Input.Mouse.currentPosition.y = (float)event.params[1];
3755 } break;
3756 case INPUT_MOUSE_WHEEL_MOTION: // param[0]: x delta, param[1]: y delta
3757 {
3758 CORE.Input.Mouse.currentWheelMove.x = (float)event.params[0];
3759 CORE.Input.Mouse.currentWheelMove.y = (float)event.params[1];
3760 } break;
3761 case INPUT_TOUCH_UP: CORE.Input.Touch.currentTouchState[event.params[0]] = false; break; // param[0]: id
3762 case INPUT_TOUCH_DOWN: CORE.Input.Touch.currentTouchState[event.params[0]] = true; break; // param[0]: id
3763 case INPUT_TOUCH_POSITION: // param[0]: id, param[1]: x, param[2]: y
3764 {
3765 CORE.Input.Touch.position[event.params[0]].x = (float)event.params[1];
3766 CORE.Input.Touch.position[event.params[0]].y = (float)event.params[2];
3767 } break;
3768 case INPUT_GAMEPAD_CONNECT: CORE.Input.Gamepad.ready[event.params[0]] = true; break; // param[0]: gamepad
3769 case INPUT_GAMEPAD_DISCONNECT: CORE.Input.Gamepad.ready[event.params[0]] = false; break; // param[0]: gamepad
3770 case INPUT_GAMEPAD_BUTTON_UP: CORE.Input.Gamepad.currentButtonState[event.params[0]][event.params[1]] = false; break; // param[0]: gamepad, param[1]: button
3771 case INPUT_GAMEPAD_BUTTON_DOWN: CORE.Input.Gamepad.currentButtonState[event.params[0]][event.params[1]] = true; break; // param[0]: gamepad, param[1]: button
3772 case INPUT_GAMEPAD_AXIS_MOTION: // param[0]: gamepad, param[1]: axis, param[2]: delta
3773 {
3774 CORE.Input.Gamepad.axisState[event.params[0]][event.params[1]] = ((float)event.params[2]/32768.0f);
3775 } break;
3776 #if SUPPORT_GESTURES_SYSTEM
3777 case INPUT_GESTURE: GESTURES.current = event.params[0]; break; // param[0]: gesture (enum Gesture) -> rgestures.h: GESTURES.current
3778 #endif
3779 // Window event
3780 case WINDOW_CLOSE: CORE.Window.shouldClose = true; break;
3781 case WINDOW_MAXIMIZE: MaximizeWindow(); break;
3782 case WINDOW_MINIMIZE: MinimizeWindow(); break;
3783 case WINDOW_RESIZE: SetWindowSize(event.params[0], event.params[1]); break;
3784 // Custom event
3785 #if SUPPORT_SCREEN_CAPTURE
3786 case ACTION_TAKE_SCREENSHOT:
3787 {
3788 TakeScreenshot(TextFormat("screenshot%03i.png", screenshotCounter));
3789 screenshotCounter++;
3790 } break;
3791 #endif
3792 case ACTION_SETTARGETFPS: SetTargetFPS(event.params[0]); break;
3793 default: break;
3794 }
3795
3796 TRACELOG(LOG_INFO, "AUTOMATION PLAY: Frame: %i | Event type: %i | Event parameters: %i, %i, %i", event.frame, event.type, event.params[0], event.params[1], event.params[2]);
3797 }
3798 #endif
3799 }
3800
3801 //----------------------------------------------------------------------------------
3802 // Module Functions Definition: Input Handling: Keyboard
3803 //----------------------------------------------------------------------------------
3804
3805 // Check if a key has been pressed once
3806 bool IsKeyPressed(int key)
3807 {
3808 bool pressed = false;
3809
3810 if ((key > 0) && (key < MAX_KEYBOARD_KEYS))
3811 {
3812 if ((CORE.Input.Keyboard.previousKeyState[key] == 0) && (CORE.Input.Keyboard.currentKeyState[key] == 1)) pressed = true;
3813 }
3814
3815 return pressed;
3816 }
3817
3818 // Check if a key has been pressed again
3819 bool IsKeyPressedRepeat(int key)
3820 {
3821 bool repeat = false;
3822
3823 if ((key > 0) && (key < MAX_KEYBOARD_KEYS))
3824 {
3825 if (CORE.Input.Keyboard.keyRepeatInFrame[key] == 1) repeat = true;
3826 }
3827
3828 return repeat;
3829 }
3830
3831 // Check if a key is being pressed (key held down)
3832 bool IsKeyDown(int key)
3833 {
3834 bool down = false;
3835
3836 if ((key > 0) && (key < MAX_KEYBOARD_KEYS))
3837 {
3838 if (CORE.Input.Keyboard.currentKeyState[key] == 1) down = true;
3839 }
3840
3841 return down;
3842 }
3843
3844 // Check if a key has been released once
3845 bool IsKeyReleased(int key)
3846 {
3847 bool released = false;
3848
3849 if ((key > 0) && (key < MAX_KEYBOARD_KEYS))
3850 {
3851 if ((CORE.Input.Keyboard.previousKeyState[key] == 1) && (CORE.Input.Keyboard.currentKeyState[key] == 0)) released = true;
3852 }
3853
3854 return released;
3855 }
3856
3857 // Check if a key is NOT being pressed (key not held down)
3858 bool IsKeyUp(int key)
3859 {
3860 bool up = false;
3861
3862 if ((key > 0) && (key < MAX_KEYBOARD_KEYS))
3863 {
3864 if (CORE.Input.Keyboard.currentKeyState[key] == 0) up = true;
3865 }
3866
3867 return up;
3868 }
3869
3870 // Get the last key pressed
3871 int GetKeyPressed(void)
3872 {
3873 int value = 0;
3874
3875 if (CORE.Input.Keyboard.keyPressedQueueCount > 0)
3876 {
3877 // Get character from the queue head
3878 value = CORE.Input.Keyboard.keyPressedQueue[0];
3879
3880 // Shift elements 1 step toward the head
3881 for (int i = 0; i < (CORE.Input.Keyboard.keyPressedQueueCount - 1); i++)
3882 CORE.Input.Keyboard.keyPressedQueue[i] = CORE.Input.Keyboard.keyPressedQueue[i + 1];
3883
3884 // Reset last character in the queue
3885 CORE.Input.Keyboard.keyPressedQueue[CORE.Input.Keyboard.keyPressedQueueCount - 1] = 0;
3886 CORE.Input.Keyboard.keyPressedQueueCount--;
3887 }
3888
3889 return value;
3890 }
3891
3892 // Get the last char pressed
3893 int GetCharPressed(void)
3894 {
3895 int value = 0;
3896
3897 if (CORE.Input.Keyboard.charPressedQueueCount > 0)
3898 {
3899 // Get character from the queue head
3900 value = CORE.Input.Keyboard.charPressedQueue[0];
3901
3902 // Shift elements 1 step toward the head
3903 for (int i = 0; i < (CORE.Input.Keyboard.charPressedQueueCount - 1); i++)
3904 CORE.Input.Keyboard.charPressedQueue[i] = CORE.Input.Keyboard.charPressedQueue[i + 1];
3905
3906 // Reset last character in the queue
3907 CORE.Input.Keyboard.charPressedQueue[CORE.Input.Keyboard.charPressedQueueCount - 1] = 0;
3908 CORE.Input.Keyboard.charPressedQueueCount--;
3909 }
3910
3911 return value;
3912 }
3913
3914 // Set a custom key to exit program
3915 // NOTE: default exitKey is set to ESCAPE
3916 void SetExitKey(int key)
3917 {
3918 CORE.Input.Keyboard.exitKey = key;
3919 }
3920
3921 //----------------------------------------------------------------------------------
3922 // Module Functions Definition: Input Handling: Gamepad
3923 //----------------------------------------------------------------------------------
3924
3925 // NOTE: Functions with a platform-specific implementation on rcore_<platform>.c
3926 //int SetGamepadMappings(const char *mappings)
3927
3928 // Check if a gamepad is available
3929 bool IsGamepadAvailable(int gamepad)
3930 {
3931 bool result = false;
3932
3933 if ((gamepad < MAX_GAMEPADS) && CORE.Input.Gamepad.ready[gamepad]) result = true;
3934
3935 return result;
3936 }
3937
3938 // Get gamepad internal name id
3939 const char *GetGamepadName(int gamepad)
3940 {
3941 return CORE.Input.Gamepad.name[gamepad];
3942 }
3943
3944 // Check if a gamepad button has been pressed once
3945 bool IsGamepadButtonPressed(int gamepad, int button)
3946 {
3947 bool pressed = false;
3948
3949 if ((gamepad < MAX_GAMEPADS) && CORE.Input.Gamepad.ready[gamepad] && (button < MAX_GAMEPAD_BUTTONS))
3950 {
3951 if ((CORE.Input.Gamepad.previousButtonState[gamepad][button] == 0) && (CORE.Input.Gamepad.currentButtonState[gamepad][button] == 1)) pressed = true;
3952 }
3953
3954 return pressed;
3955 }
3956
3957 // Check if a gamepad button is being pressed
3958 bool IsGamepadButtonDown(int gamepad, int button)
3959 {
3960 bool down = false;
3961
3962 if ((gamepad < MAX_GAMEPADS) && CORE.Input.Gamepad.ready[gamepad] && (button < MAX_GAMEPAD_BUTTONS))
3963 {
3964 if (CORE.Input.Gamepad.currentButtonState[gamepad][button] == 1) down = true;
3965 }
3966
3967 return down;
3968 }
3969
3970 // Check if a gamepad button has NOT been pressed once
3971 bool IsGamepadButtonReleased(int gamepad, int button)
3972 {
3973 bool released = false;
3974
3975 if ((gamepad < MAX_GAMEPADS) && CORE.Input.Gamepad.ready[gamepad] && (button < MAX_GAMEPAD_BUTTONS))
3976 {
3977 if ((CORE.Input.Gamepad.previousButtonState[gamepad][button] == 1) && (CORE.Input.Gamepad.currentButtonState[gamepad][button] == 0)) released = true;
3978 }
3979
3980 return released;
3981 }
3982
3983 // Check if a gamepad button is NOT being pressed
3984 bool IsGamepadButtonUp(int gamepad, int button)
3985 {
3986 bool up = false;
3987
3988 if ((gamepad < MAX_GAMEPADS) && CORE.Input.Gamepad.ready[gamepad] && (button < MAX_GAMEPAD_BUTTONS))
3989 {
3990 if (CORE.Input.Gamepad.currentButtonState[gamepad][button] == 0) up = true;
3991 }
3992
3993 return up;
3994 }
3995
3996 // Get the last gamepad button pressed
3997 // NOTE: Returns last gamepad button down, down->up change not considered
3998 int GetGamepadButtonPressed(void)
3999 {
4000 return CORE.Input.Gamepad.lastButtonPressed;
4001 }
4002
4003 // Get gamepad axis count
4004 int GetGamepadAxisCount(int gamepad)
4005 {
4006 return CORE.Input.Gamepad.axisCount[gamepad];
4007 }
4008
4009 // Get axis movement vector for a gamepad
4010 float GetGamepadAxisMovement(int gamepad, int axis)
4011 {
4012 float value = ((axis == GAMEPAD_AXIS_LEFT_TRIGGER) || (axis == GAMEPAD_AXIS_RIGHT_TRIGGER))? -1.0f : 0.0f;
4013
4014 if ((gamepad < MAX_GAMEPADS) && CORE.Input.Gamepad.ready[gamepad] && (axis < MAX_GAMEPAD_AXES))
4015 {
4016 float movement = (value < 0.0f)? CORE.Input.Gamepad.axisState[gamepad][axis] : fabsf(CORE.Input.Gamepad.axisState[gamepad][axis]);
4017
4018 if (movement > value) value = CORE.Input.Gamepad.axisState[gamepad][axis];
4019 }
4020
4021 return value;
4022 }
4023
4024 //----------------------------------------------------------------------------------
4025 // Module Functions Definition: Input Handling: Mouse
4026 //----------------------------------------------------------------------------------
4027
4028 // NOTE: Functions with a platform-specific implementation on rcore_<platform>.c
4029 //void SetMousePosition(int x, int y)
4030 //void SetMouseCursor(int cursor)
4031
4032 // Check if a mouse button has been pressed once
4033 bool IsMouseButtonPressed(int button)
4034 {
4035 bool pressed = false;
4036
4037 if ((button >= 0) && (button <= MOUSE_BUTTON_BACK))
4038 {
4039 if ((CORE.Input.Mouse.currentButtonState[button] == 1) && (CORE.Input.Mouse.previousButtonState[button] == 0)) pressed = true;
4040
4041 // Map touches to mouse buttons checking
4042 if ((CORE.Input.Touch.currentTouchState[button] == 1) && (CORE.Input.Touch.previousTouchState[button] == 0)) pressed = true;
4043 }
4044
4045 return pressed;
4046 }
4047
4048 // Check if a mouse button is being pressed
4049 bool IsMouseButtonDown(int button)
4050 {
4051 bool down = false;
4052
4053 if ((button >= 0) && (button <= MOUSE_BUTTON_BACK))
4054 {
4055 if (CORE.Input.Mouse.currentButtonState[button] == 1) down = true;
4056
4057 // NOTE: Touches are considered like mouse buttons
4058 if (CORE.Input.Touch.currentTouchState[button] == 1) down = true;
4059 }
4060
4061 return down;
4062 }
4063
4064 // Check if a mouse button has been released once
4065 bool IsMouseButtonReleased(int button)
4066 {
4067 bool released = false;
4068
4069 if ((button >= 0) && (button <= MOUSE_BUTTON_BACK))
4070 {
4071 if ((CORE.Input.Mouse.currentButtonState[button] == 0) && (CORE.Input.Mouse.previousButtonState[button] == 1)) released = true;
4072
4073 // Map touches to mouse buttons checking
4074 if ((CORE.Input.Touch.currentTouchState[button] == 0) && (CORE.Input.Touch.previousTouchState[button] == 1)) released = true;
4075 }
4076
4077 return released;
4078 }
4079
4080 // Check if a mouse button is NOT being pressed
4081 bool IsMouseButtonUp(int button)
4082 {
4083 bool up = false;
4084
4085 if ((button >= 0) && (button <= MOUSE_BUTTON_BACK))
4086 {
4087 if (CORE.Input.Mouse.currentButtonState[button] == 0) up = true;
4088
4089 // NOTE: Touches are considered like mouse buttons
4090 if (CORE.Input.Touch.currentTouchState[button] == 0) up = true;
4091 }
4092
4093 return up;
4094 }
4095
4096 // Get mouse position X
4097 int GetMouseX(void)
4098 {
4099 int mouseX = (int)((CORE.Input.Mouse.currentPosition.x + CORE.Input.Mouse.offset.x)*CORE.Input.Mouse.scale.x);
4100
4101 return mouseX;
4102 }
4103
4104 // Get mouse position Y
4105 int GetMouseY(void)
4106 {
4107 int mouseY = (int)((CORE.Input.Mouse.currentPosition.y + CORE.Input.Mouse.offset.y)*CORE.Input.Mouse.scale.y);
4108
4109 return mouseY;
4110 }
4111
4112 // Get mouse position XY
4113 Vector2 GetMousePosition(void)
4114 {
4115 Vector2 position = { 0 };
4116
4117 position.x = (CORE.Input.Mouse.currentPosition.x + CORE.Input.Mouse.offset.x)*CORE.Input.Mouse.scale.x;
4118 position.y = (CORE.Input.Mouse.currentPosition.y + CORE.Input.Mouse.offset.y)*CORE.Input.Mouse.scale.y;
4119
4120 return position;
4121 }
4122
4123 // Get mouse delta between frames
4124 Vector2 GetMouseDelta(void)
4125 {
4126 Vector2 delta = { 0 };
4127
4128 delta.x = (CORE.Input.Mouse.currentPosition.x - CORE.Input.Mouse.previousPosition.x)*CORE.Input.Mouse.scale.x;
4129 delta.y = (CORE.Input.Mouse.currentPosition.y - CORE.Input.Mouse.previousPosition.y)*CORE.Input.Mouse.scale.y;
4130
4131 return delta;
4132 }
4133
4134 // Set mouse offset
4135 // NOTE: Useful when rendering to different size targets
4136 void SetMouseOffset(int offsetX, int offsetY)
4137 {
4138 CORE.Input.Mouse.offset = (Vector2){ (float)offsetX, (float)offsetY };
4139 }
4140
4141 // Set mouse scaling
4142 // NOTE: Useful when rendering to different size targets
4143 void SetMouseScale(float scaleX, float scaleY)
4144 {
4145 CORE.Input.Mouse.scale = (Vector2){ scaleX, scaleY };
4146 }
4147
4148 // Get mouse wheel movement Y
4149 float GetMouseWheelMove(void)
4150 {
4151 float result = 0.0f;
4152
4153 if (fabsf(CORE.Input.Mouse.currentWheelMove.x) > fabsf(CORE.Input.Mouse.currentWheelMove.y)) result = (float)CORE.Input.Mouse.currentWheelMove.x;
4154 else result = (float)CORE.Input.Mouse.currentWheelMove.y;
4155
4156 return result;
4157 }
4158
4159 // Get mouse wheel movement X/Y as a vector
4160 Vector2 GetMouseWheelMoveV(void)
4161 {
4162 Vector2 result = { 0 };
4163
4164 result = CORE.Input.Mouse.currentWheelMove;
4165
4166 return result;
4167 }
4168
4169 //----------------------------------------------------------------------------------
4170 // Module Functions Definition: Input Handling: Touch
4171 //----------------------------------------------------------------------------------
4172
4173 // Get touch position X for touch point 0 (relative to screen size)
4174 int GetTouchX(void)
4175 {
4176 int touchX = (int)CORE.Input.Touch.position[0].x;
4177 return touchX;
4178 }
4179
4180 // Get touch position Y for touch point 0 (relative to screen size)
4181 int GetTouchY(void)
4182 {
4183 int touchY = (int)CORE.Input.Touch.position[0].y;
4184 return touchY;
4185 }
4186
4187 // Get touch position XY for a touch point index (relative to screen size)
4188 Vector2 GetTouchPosition(int index)
4189 {
4190 Vector2 position = { -1.0f, -1.0f };
4191
4192 if (index < MAX_TOUCH_POINTS) position = CORE.Input.Touch.position[index];
4193 else TRACELOG(LOG_WARNING, "INPUT: Required touch point out of range (Max touch points: %i)", MAX_TOUCH_POINTS);
4194
4195 return position;
4196 }
4197
4198 // Get touch point identifier for given index
4199 int GetTouchPointId(int index)
4200 {
4201 int id = -1;
4202
4203 if (index < MAX_TOUCH_POINTS) id = CORE.Input.Touch.pointId[index];
4204
4205 return id;
4206 }
4207
4208 // Get number of touch points
4209 int GetTouchPointCount(void)
4210 {
4211 return CORE.Input.Touch.pointCount;
4212 }
4213
4214 //----------------------------------------------------------------------------------
4215 // Module Internal Functions Definition
4216 //----------------------------------------------------------------------------------
4217
4218 // NOTE: Functions with a platform-specific implementation on rcore_<platform>.c
4219 //int InitPlatform(void)
4220 //void ClosePlatform(void)
4221
4222 // Initialize hi-resolution timer
4223 void InitTimer(void)
4224 {
4225 // Setting a higher resolution can improve the accuracy of time-out intervals in wait functions
4226 // However, it can also reduce overall system performance, because the thread scheduler switches tasks more often
4227 // High resolutions can also prevent the CPU power management system from entering power-saving modes
4228 // Setting a higher resolution does not improve the accuracy of the high-resolution performance counter
4229 #if defined(_WIN32) && SUPPORT_WINMM_HIGHRES_TIMER && !SUPPORT_BUSY_WAIT_LOOP && !defined(PLATFORM_DESKTOP_SDL)
4230 timeBeginPeriod(1); // Setup high-resolution timer to 1ms (granularity of 1-2 ms)
4231 #endif
4232
4233 #if defined(__linux__) || defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__EMSCRIPTEN__)
4234 struct timespec now = { 0 };
4235
4236 if (clock_gettime(CLOCK_MONOTONIC, &now) == 0) // Success
4237 {
4238 CORE.Time.base = (unsigned long long int)now.tv_sec*1000000000LLU + (unsigned long long int)now.tv_nsec;
4239 }
4240 else TRACELOG(LOG_WARNING, "TIMER: Hi-resolution timer not available");
4241 #endif
4242
4243 CORE.Time.previous = GetTime(); // Get time as double
4244 }
4245
4246 // Set viewport for a provided width and height
4247 void SetupViewport(int width, int height)
4248 {
4249 CORE.Window.render.width = width;
4250 CORE.Window.render.height = height;
4251
4252 // Set viewport width and height
4253 rlViewport(CORE.Window.renderOffset.x/2, CORE.Window.renderOffset.y/2, CORE.Window.render.width, CORE.Window.render.height);
4254
4255 rlMatrixMode(RL_PROJECTION); // Switch to projection matrix
4256 rlLoadIdentity(); // Reset current matrix (projection)
4257
4258 // Set orthographic projection to current framebuffer size
4259 // NOTE: Configured top-left corner as (0, 0)
4260 rlOrtho(0, CORE.Window.render.width, CORE.Window.render.height, 0, 0.0f, 1.0f);
4261
4262 rlMatrixMode(RL_MODELVIEW); // Switch back to modelview matrix
4263 rlLoadIdentity(); // Reset current matrix (modelview)
4264 }
4265
4266 // Scan all files and directories in a base path
4267 // WARNING: files.paths[] must be previously allocated and
4268 // contain enough space to store all required paths
4269 static void ScanDirectoryFiles(const char *basePath, FilePathList *files, const char *filter, unsigned int expectedFileCount, bool scanSubdirs)
4270 {
4271 // WARNING: Path can not be static or it will be reused between recursive function calls!
4272 char path[MAX_FILEPATH_LENGTH] = { 0 };
4273 memset(path, 0, MAX_FILEPATH_LENGTH);
4274
4275 struct dirent *dp = NULL;
4276 DIR *dir = opendir(basePath);
4277
4278 if (dir != NULL)
4279 {
4280 while (((dp = readdir(dir)) != NULL) && (files->count < expectedFileCount))
4281 {
4282 if ((strcmp(dp->d_name, ".") != 0) && (strcmp(dp->d_name, "..") != 0))
4283 {
4284 // Construct new path from our base path
4285 #if defined(_WIN32)
4286 int pathLength = snprintf(path, MAX_FILEPATH_LENGTH - 1, "%s\\%s", basePath, dp->d_name);
4287 #else
4288 int pathLength = snprintf(path, MAX_FILEPATH_LENGTH - 1, "%s/%s", basePath, dp->d_name);
4289 #endif
4290
4291 if ((pathLength < 0) || (pathLength >= MAX_FILEPATH_LENGTH))
4292 {
4293 TRACELOG(LOG_WARNING, "FILEIO: Path longer than %d characters (%s...)", MAX_FILEPATH_LENGTH, basePath);
4294 }
4295 else if (IsPathFile(path))
4296 {
4297 if ((filter == NULL) || (strstr(filter, FILE_FILTER_TAG_ALL) != NULL) ||
4298 (strstr(filter, FILE_FILTER_TAG_FILE_ONLY) != NULL) || IsFileExtension(path, filter))
4299 {
4300 strncpy(files->paths[files->count], path, MAX_FILEPATH_LENGTH - 1);
4301 files->count++;
4302 }
4303 }
4304 else
4305 {
4306 if ((filter != NULL) && ((strstr(filter, FILE_FILTER_TAG_DIR_ONLY) != NULL) || (strstr(filter, FILE_FILTER_TAG_ALL) != NULL)))
4307 {
4308 strncpy(files->paths[files->count], path, MAX_FILEPATH_LENGTH - 1);
4309 files->count++;
4310 }
4311
4312 if (scanSubdirs) ScanDirectoryFiles(path, files, filter, expectedFileCount, scanSubdirs);
4313 }
4314 }
4315 }
4316
4317 closedir(dir);
4318 }
4319 else TRACELOG(LOG_WARNING, "FILEIO: Directory cannot be opened (%s)", basePath); // Maybe it's a file...
4320 }
4321
4322 #if SUPPORT_AUTOMATION_EVENTS
4323 // Automation event recording
4324 // Checking events in current frame and save them into currentEventList
4325 // NOTE: Recording is by default done at EndDrawing(), before PollInputEvents()
4326 static void RecordAutomationEvent(void)
4327 {
4328 if (currentEventList->count == currentEventList->capacity) return;
4329
4330 // Keyboard input events recording
4331 //-------------------------------------------------------------------------------------
4332 for (int key = 0; key < MAX_KEYBOARD_KEYS; key++)
4333 {
4334 // Event type: INPUT_KEY_UP (only saved once)
4335 if (CORE.Input.Keyboard.previousKeyState[key] && !CORE.Input.Keyboard.currentKeyState[key])
4336 {
4337 currentEventList->events[currentEventList->count].frame = CORE.Time.frameCounter;
4338 currentEventList->events[currentEventList->count].type = INPUT_KEY_UP;
4339 currentEventList->events[currentEventList->count].params[0] = key;
4340 currentEventList->events[currentEventList->count].params[1] = 0;
4341 currentEventList->events[currentEventList->count].params[2] = 0;
4342
4343 TRACELOG(LOG_INFO, "AUTOMATION: Frame: %i | Event type: INPUT_KEY_UP | Event parameters: %i, %i, %i", currentEventList->events[currentEventList->count].frame, currentEventList->events[currentEventList->count].params[0], currentEventList->events[currentEventList->count].params[1], currentEventList->events[currentEventList->count].params[2]);
4344 currentEventList->count++;
4345 }
4346
4347 if (currentEventList->count == currentEventList->capacity) return; // Security check
4348
4349 // Event type: INPUT_KEY_DOWN
4350 if (CORE.Input.Keyboard.currentKeyState[key])
4351 {
4352 currentEventList->events[currentEventList->count].frame = CORE.Time.frameCounter;
4353 currentEventList->events[currentEventList->count].type = INPUT_KEY_DOWN;
4354 currentEventList->events[currentEventList->count].params[0] = key;
4355 currentEventList->events[currentEventList->count].params[1] = 0;
4356 currentEventList->events[currentEventList->count].params[2] = 0;
4357
4358 TRACELOG(LOG_INFO, "AUTOMATION: Frame: %i | Event type: INPUT_KEY_DOWN | Event parameters: %i, %i, %i", currentEventList->events[currentEventList->count].frame, currentEventList->events[currentEventList->count].params[0], currentEventList->events[currentEventList->count].params[1], currentEventList->events[currentEventList->count].params[2]);
4359 currentEventList->count++;
4360 }
4361
4362 if (currentEventList->count == currentEventList->capacity) return; // Security check
4363 }
4364 //-------------------------------------------------------------------------------------
4365
4366 // Mouse input currentEventList->events recording
4367 //-------------------------------------------------------------------------------------
4368 for (int button = 0; button < MAX_MOUSE_BUTTONS; button++)
4369 {
4370 // Event type: INPUT_MOUSE_BUTTON_UP
4371 if (CORE.Input.Mouse.previousButtonState[button] && !CORE.Input.Mouse.currentButtonState[button])
4372 {
4373 currentEventList->events[currentEventList->count].frame = CORE.Time.frameCounter;
4374 currentEventList->events[currentEventList->count].type = INPUT_MOUSE_BUTTON_UP;
4375 currentEventList->events[currentEventList->count].params[0] = button;
4376 currentEventList->events[currentEventList->count].params[1] = 0;
4377 currentEventList->events[currentEventList->count].params[2] = 0;
4378
4379 TRACELOG(LOG_INFO, "AUTOMATION: Frame: %i | Event type: INPUT_MOUSE_BUTTON_UP | Event parameters: %i, %i, %i", currentEventList->events[currentEventList->count].frame, currentEventList->events[currentEventList->count].params[0], currentEventList->events[currentEventList->count].params[1], currentEventList->events[currentEventList->count].params[2]);
4380 currentEventList->count++;
4381 }
4382
4383 if (currentEventList->count == currentEventList->capacity) return; // Security check
4384
4385 // Event type: INPUT_MOUSE_BUTTON_DOWN
4386 if (CORE.Input.Mouse.currentButtonState[button])
4387 {
4388 currentEventList->events[currentEventList->count].frame = CORE.Time.frameCounter;
4389 currentEventList->events[currentEventList->count].type = INPUT_MOUSE_BUTTON_DOWN;
4390 currentEventList->events[currentEventList->count].params[0] = button;
4391 currentEventList->events[currentEventList->count].params[1] = 0;
4392 currentEventList->events[currentEventList->count].params[2] = 0;
4393
4394 TRACELOG(LOG_INFO, "AUTOMATION: Frame: %i | Event type: INPUT_MOUSE_BUTTON_DOWN | Event parameters: %i, %i, %i", currentEventList->events[currentEventList->count].frame, currentEventList->events[currentEventList->count].params[0], currentEventList->events[currentEventList->count].params[1], currentEventList->events[currentEventList->count].params[2]);
4395 currentEventList->count++;
4396 }
4397
4398 if (currentEventList->count == currentEventList->capacity) return; // Security check
4399 }
4400
4401 // Event type: INPUT_MOUSE_POSITION (only saved if changed)
4402 if (((int)CORE.Input.Mouse.currentPosition.x != (int)CORE.Input.Mouse.previousPosition.x) ||
4403 ((int)CORE.Input.Mouse.currentPosition.y != (int)CORE.Input.Mouse.previousPosition.y))
4404 {
4405 currentEventList->events[currentEventList->count].frame = CORE.Time.frameCounter;
4406 currentEventList->events[currentEventList->count].type = INPUT_MOUSE_POSITION;
4407 currentEventList->events[currentEventList->count].params[0] = (int)CORE.Input.Mouse.currentPosition.x;
4408 currentEventList->events[currentEventList->count].params[1] = (int)CORE.Input.Mouse.currentPosition.y;
4409 currentEventList->events[currentEventList->count].params[2] = 0;
4410
4411 TRACELOG(LOG_INFO, "AUTOMATION: Frame: %i | Event type: INPUT_MOUSE_POSITION | Event parameters: %i, %i, %i", currentEventList->events[currentEventList->count].frame, currentEventList->events[currentEventList->count].params[0], currentEventList->events[currentEventList->count].params[1], currentEventList->events[currentEventList->count].params[2]);
4412 currentEventList->count++;
4413
4414 if (currentEventList->count == currentEventList->capacity) return; // Security check
4415 }
4416
4417 // Event type: INPUT_MOUSE_WHEEL_MOTION
4418 if (((int)CORE.Input.Mouse.currentWheelMove.x != (int)CORE.Input.Mouse.previousWheelMove.x) ||
4419 ((int)CORE.Input.Mouse.currentWheelMove.y != (int)CORE.Input.Mouse.previousWheelMove.y))
4420 {
4421 currentEventList->events[currentEventList->count].frame = CORE.Time.frameCounter;
4422 currentEventList->events[currentEventList->count].type = INPUT_MOUSE_WHEEL_MOTION;
4423 currentEventList->events[currentEventList->count].params[0] = (int)CORE.Input.Mouse.currentWheelMove.x;
4424 currentEventList->events[currentEventList->count].params[1] = (int)CORE.Input.Mouse.currentWheelMove.y;
4425 currentEventList->events[currentEventList->count].params[2] = 0;
4426
4427 TRACELOG(LOG_INFO, "AUTOMATION: Frame: %i | Event type: INPUT_MOUSE_WHEEL_MOTION | Event parameters: %i, %i, %i", currentEventList->events[currentEventList->count].frame, currentEventList->events[currentEventList->count].params[0], currentEventList->events[currentEventList->count].params[1], currentEventList->events[currentEventList->count].params[2]);
4428 currentEventList->count++;
4429
4430 if (currentEventList->count == currentEventList->capacity) return; // Security check
4431 }
4432 //-------------------------------------------------------------------------------------
4433
4434 // Touch input currentEventList->events recording
4435 //-------------------------------------------------------------------------------------
4436 for (int id = 0; id < MAX_TOUCH_POINTS; id++)
4437 {
4438 // Event type: INPUT_TOUCH_UP
4439 if (CORE.Input.Touch.previousTouchState[id] && !CORE.Input.Touch.currentTouchState[id])
4440 {
4441 currentEventList->events[currentEventList->count].frame = CORE.Time.frameCounter;
4442 currentEventList->events[currentEventList->count].type = INPUT_TOUCH_UP;
4443 currentEventList->events[currentEventList->count].params[0] = id;
4444 currentEventList->events[currentEventList->count].params[1] = 0;
4445 currentEventList->events[currentEventList->count].params[2] = 0;
4446
4447 TRACELOG(LOG_INFO, "AUTOMATION: Frame: %i | Event type: INPUT_TOUCH_UP | Event parameters: %i, %i, %i", currentEventList->events[currentEventList->count].frame, currentEventList->events[currentEventList->count].params[0], currentEventList->events[currentEventList->count].params[1], currentEventList->events[currentEventList->count].params[2]);
4448 currentEventList->count++;
4449 }
4450
4451 if (currentEventList->count == currentEventList->capacity) return; // Security check
4452
4453 // Event type: INPUT_TOUCH_DOWN
4454 if (CORE.Input.Touch.currentTouchState[id])
4455 {
4456 currentEventList->events[currentEventList->count].frame = CORE.Time.frameCounter;
4457 currentEventList->events[currentEventList->count].type = INPUT_TOUCH_DOWN;
4458 currentEventList->events[currentEventList->count].params[0] = id;
4459 currentEventList->events[currentEventList->count].params[1] = 0;
4460 currentEventList->events[currentEventList->count].params[2] = 0;
4461
4462 TRACELOG(LOG_INFO, "AUTOMATION: Frame: %i | Event type: INPUT_TOUCH_DOWN | Event parameters: %i, %i, %i", currentEventList->events[currentEventList->count].frame, currentEventList->events[currentEventList->count].params[0], currentEventList->events[currentEventList->count].params[1], currentEventList->events[currentEventList->count].params[2]);
4463 currentEventList->count++;
4464 }
4465
4466 if (currentEventList->count == currentEventList->capacity) return; // Security check
4467
4468 // Event type: INPUT_TOUCH_POSITION
4469 if (((int)CORE.Input.Touch.position[id].x != (int)CORE.Input.Touch.previousPosition[id].x) ||
4470 ((int)CORE.Input.Touch.position[id].y != (int)CORE.Input.Touch.previousPosition[id].y))
4471 {
4472 currentEventList->events[currentEventList->count].frame = CORE.Time.frameCounter;
4473 currentEventList->events[currentEventList->count].type = INPUT_TOUCH_POSITION;
4474 currentEventList->events[currentEventList->count].params[0] = id;
4475 currentEventList->events[currentEventList->count].params[1] = (int)CORE.Input.Touch.position[id].x;
4476 currentEventList->events[currentEventList->count].params[2] = (int)CORE.Input.Touch.position[id].y;
4477
4478 TRACELOG(LOG_INFO, "AUTOMATION: Frame: %i | Event type: INPUT_TOUCH_POSITION | Event parameters: %i, %i, %i", currentEventList->events[currentEventList->count].frame, currentEventList->events[currentEventList->count].params[0], currentEventList->events[currentEventList->count].params[1], currentEventList->events[currentEventList->count].params[2]);
4479 currentEventList->count++;
4480 }
4481
4482
4483 if (currentEventList->count == currentEventList->capacity) return; // Security check
4484 }
4485 //-------------------------------------------------------------------------------------
4486
4487 // Gamepad input currentEventList->events recording
4488 //-------------------------------------------------------------------------------------
4489 for (int gamepad = 0; gamepad < MAX_GAMEPADS; gamepad++)
4490 {
4491 // Event type: INPUT_GAMEPAD_CONNECT
4492 /*
4493 if ((CORE.Input.Gamepad.currentState[gamepad] != CORE.Input.Gamepad.previousState[gamepad]) &&
4494 (CORE.Input.Gamepad.currentState[gamepad])) // Check if changed to ready
4495 {
4496 // TODO: Save gamepad connect event
4497 }
4498 */
4499
4500 // Event type: INPUT_GAMEPAD_DISCONNECT
4501 /*
4502 if ((CORE.Input.Gamepad.currentState[gamepad] != CORE.Input.Gamepad.previousState[gamepad]) &&
4503 (!CORE.Input.Gamepad.currentState[gamepad])) // Check if changed to not-ready
4504 {
4505 // TODO: Save gamepad disconnect event
4506 }
4507 */
4508
4509 for (int button = 0; button < MAX_GAMEPAD_BUTTONS; button++)
4510 {
4511 // Event type: INPUT_GAMEPAD_BUTTON_UP
4512 if (CORE.Input.Gamepad.previousButtonState[gamepad][button] && !CORE.Input.Gamepad.currentButtonState[gamepad][button])
4513 {
4514 currentEventList->events[currentEventList->count].frame = CORE.Time.frameCounter;
4515 currentEventList->events[currentEventList->count].type = INPUT_GAMEPAD_BUTTON_UP;
4516 currentEventList->events[currentEventList->count].params[0] = gamepad;
4517 currentEventList->events[currentEventList->count].params[1] = button;
4518 currentEventList->events[currentEventList->count].params[2] = 0;
4519
4520 TRACELOG(LOG_INFO, "AUTOMATION: Frame: %i | Event type: INPUT_GAMEPAD_BUTTON_UP | Event parameters: %i, %i, %i", currentEventList->events[currentEventList->count].frame, currentEventList->events[currentEventList->count].params[0], currentEventList->events[currentEventList->count].params[1], currentEventList->events[currentEventList->count].params[2]);
4521 currentEventList->count++;
4522 }
4523
4524 if (currentEventList->count == currentEventList->capacity) return; // Security check
4525
4526 // Event type: INPUT_GAMEPAD_BUTTON_DOWN
4527 if (CORE.Input.Gamepad.currentButtonState[gamepad][button])
4528 {
4529 currentEventList->events[currentEventList->count].frame = CORE.Time.frameCounter;
4530 currentEventList->events[currentEventList->count].type = INPUT_GAMEPAD_BUTTON_DOWN;
4531 currentEventList->events[currentEventList->count].params[0] = gamepad;
4532 currentEventList->events[currentEventList->count].params[1] = button;
4533 currentEventList->events[currentEventList->count].params[2] = 0;
4534
4535 TRACELOG(LOG_INFO, "AUTOMATION: Frame: %i | Event type: INPUT_GAMEPAD_BUTTON_DOWN | Event parameters: %i, %i, %i", currentEventList->events[currentEventList->count].frame, currentEventList->events[currentEventList->count].params[0], currentEventList->events[currentEventList->count].params[1], currentEventList->events[currentEventList->count].params[2]);
4536 currentEventList->count++;
4537 }
4538
4539 if (currentEventList->count == currentEventList->capacity) return; // Security check
4540 }
4541
4542 for (int axis = 0; axis < MAX_GAMEPAD_AXES; axis++)
4543 {
4544 // Event type: INPUT_GAMEPAD_AXIS_MOTION
4545 float defaultMovement = ((axis == GAMEPAD_AXIS_LEFT_TRIGGER) || (axis == GAMEPAD_AXIS_RIGHT_TRIGGER))? -1.0f : 0.0f;
4546 if (GetGamepadAxisMovement(gamepad, axis) != defaultMovement)
4547 {
4548 currentEventList->events[currentEventList->count].frame = CORE.Time.frameCounter;
4549 currentEventList->events[currentEventList->count].type = INPUT_GAMEPAD_AXIS_MOTION;
4550 currentEventList->events[currentEventList->count].params[0] = gamepad;
4551 currentEventList->events[currentEventList->count].params[1] = axis;
4552 currentEventList->events[currentEventList->count].params[2] = (int)(CORE.Input.Gamepad.axisState[gamepad][axis]*32768.0f);
4553
4554 TRACELOG(LOG_INFO, "AUTOMATION: Frame: %i | Event type: INPUT_GAMEPAD_AXIS_MOTION | Event parameters: %i, %i, %i", currentEventList->events[currentEventList->count].frame, currentEventList->events[currentEventList->count].params[0], currentEventList->events[currentEventList->count].params[1], currentEventList->events[currentEventList->count].params[2]);
4555 currentEventList->count++;
4556 }
4557
4558 if (currentEventList->count == currentEventList->capacity) return; // Security check
4559 }
4560 }
4561 //-------------------------------------------------------------------------------------
4562
4563 #if SUPPORT_GESTURES_SYSTEM
4564 // Gestures input currentEventList->events recording
4565 //-------------------------------------------------------------------------------------
4566 if (GESTURES.current != GESTURE_NONE)
4567 {
4568 // Event type: INPUT_GESTURE
4569 currentEventList->events[currentEventList->count].frame = CORE.Time.frameCounter;
4570 currentEventList->events[currentEventList->count].type = INPUT_GESTURE;
4571 currentEventList->events[currentEventList->count].params[0] = GESTURES.current;
4572 currentEventList->events[currentEventList->count].params[1] = 0;
4573 currentEventList->events[currentEventList->count].params[2] = 0;
4574
4575 TRACELOG(LOG_INFO, "AUTOMATION: Frame: %i | Event type: INPUT_GESTURE | Event parameters: %i, %i, %i", currentEventList->events[currentEventList->count].frame, currentEventList->events[currentEventList->count].params[0], currentEventList->events[currentEventList->count].params[1], currentEventList->events[currentEventList->count].params[2]);
4576 currentEventList->count++;
4577
4578 if (currentEventList->count == currentEventList->capacity) return; // Security check
4579 }
4580 //-------------------------------------------------------------------------------------
4581 #endif
4582 }
4583 #endif
4584
4585 #if !SUPPORT_MODULE_RTEXT
4586 // Formatting of text with variables to 'embed'
4587 // WARNING: String returned will expire after this function is called MAX_TEXTFORMAT_BUFFERS times
4588 const char *TextFormat(const char *text, ...)
4589 {
4590 #ifndef MAX_TEXTFORMAT_BUFFERS
4591 #define MAX_TEXTFORMAT_BUFFERS 4 // Maximum number of static buffers for text formatting
4592 #endif
4593 #ifndef MAX_TEXT_BUFFER_LENGTH
4594 #define MAX_TEXT_BUFFER_LENGTH 1024 // Maximum size of static text buffer
4595 #endif
4596
4597 // Define an array of buffers, so strings don't expire until MAX_TEXTFORMAT_BUFFERS invocations
4598 static char buffers[MAX_TEXTFORMAT_BUFFERS][MAX_TEXT_BUFFER_LENGTH] = { 0 };
4599 static int index = 0;
4600
4601 char *currentBuffer = buffers[index];
4602 memset(currentBuffer, 0, MAX_TEXT_BUFFER_LENGTH); // Clear buffer before using
4603
4604 if (text != NULL)
4605 {
4606 va_list args;
4607 va_start(args, text);
4608 int requiredByteCount = vsnprintf(currentBuffer, MAX_TEXT_BUFFER_LENGTH, text, args);
4609 va_end(args);
4610
4611 // If requiredByteCount is larger than the MAX_TEXT_BUFFER_LENGTH, then overflow occurred
4612 if (requiredByteCount >= MAX_TEXT_BUFFER_LENGTH)
4613 {
4614 // Inserting "..." at the end of the string to mark as truncated
4615 char *truncBuffer = buffers[index] + MAX_TEXT_BUFFER_LENGTH - 4; // Adding 4 bytes = "...\0"
4616 snprintf(truncBuffer, 4, "...");
4617 }
4618
4619 index += 1; // Move to next buffer for next function call
4620 if (index >= MAX_TEXTFORMAT_BUFFERS) index = 0;
4621 }
4622
4623 return currentBuffer;
4624 }
4625 #endif