#if (defined(__linux__) || defined(PLATFORM_WEB) || defined(PLATFORM_WEB_RGFW)) && (_XOPEN_SOURCE < 500)
#undef _XOPEN_SOURCE
#define _XOPEN_SOURCE 500
#endif
#if (defined(__linux__) || defined(PLATFORM_WEB) || defined(PLATFORM_WEB_RGFW)) && (_POSIX_C_SOURCE < 199309L)
#undef _POSIX_C_SOURCE
#define _POSIX_C_SOURCE 199309L
#endif
#include "raylib.h"
#include "config.h"
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <stdarg.h>
#include <time.h>
#include <math.h>
#if defined(PLATFORM_MEMORY) || defined(PLATFORM_WEB)
#define SW_GL_FRAMEBUFFER_COPY_BGRA false
#endif
#define RLGL_IMPLEMENTATION
#include "rlgl.h"
#define RAYMATH_IMPLEMENTATION
#include "raymath.h"
#if SUPPORT_GESTURES_SYSTEM
#define RGESTURES_IMPLEMENTATION
#include "rgestures.h"
#endif
#if SUPPORT_CAMERA_SYSTEM
#define RCAMERA_IMPLEMENTATION
#include "rcamera.h"
#endif
#if SUPPORT_COMPRESSION_API
#define SINFL_IMPLEMENTATION
#define SINFL_NO_SIMD
#include "external/sinfl.h"
#define SDEFL_IMPLEMENTATION
#include "external/sdefl.h"
#endif
#if SUPPORT_RPRAND_GENERATOR
#define RPRAND_IMPLEMENTATION
#include "external/rprand.h"
#endif
#if defined(__linux__) && !defined(_GNU_SOURCE)
#define _GNU_SOURCE
#endif
#if defined(_WIN32)
#if !defined(MAX_PATH)
#define MAX_PATH 260
#endif
struct HINSTANCE__;
#if defined(__cplusplus)
extern "C" {
#endif
__declspec(dllimport) unsigned long __stdcall GetModuleFileNameA(struct HINSTANCE__ *hModule, char *lpFilename, unsigned long nSize);
__declspec(dllimport) unsigned long __stdcall GetModuleFileNameW(struct HINSTANCE__ *hModule, wchar_t *lpFilename, unsigned long nSize);
__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);
__declspec(dllimport) unsigned int __stdcall timeBeginPeriod(unsigned int uPeriod);
__declspec(dllimport) unsigned int __stdcall timeEndPeriod(unsigned int uPeriod);
#if defined(__cplusplus)
}
#endif
#elif defined(__linux__)
#include <unistd.h>
#elif defined(__FreeBSD__)
#include <sys/types.h>
#include <sys/sysctl.h>
#include <unistd.h>
#elif defined(__APPLE__)
#include <sys/syslimits.h>
#include <mach-o/dyld.h>
#endif
#define _CRT_INTERNAL_NONSTDC_NAMES 1
#include <sys/stat.h>
#if !defined(S_ISREG) && defined(S_IFMT) && defined(S_IFREG)
#define S_ISREG(m) (((m) & S_IFMT) == S_IFREG)
#endif
#if defined(_WIN32) && (defined(_MSC_VER) || defined(__TINYC__))
#define DIRENT_MALLOC RL_MALLOC
#define DIRENT_FREE RL_FREE
#include "external/dirent.h"
#else
#include <dirent.h>
#endif
#if defined(_WIN32)
#include <io.h>
#include <direct.h>
#define GETCWD _getcwd
#define CHDIR _chdir
#define MKDIR(dir) _mkdir(dir)
#define ACCESS(fn) _access(fn, 0)
#else
#include <unistd.h>
#define GETCWD getcwd
#define CHDIR chdir
#define MKDIR(dir) mkdir(dir, 0777)
#define ACCESS(fn) access(fn, F_OK)
#endif
#ifndef MAX_TRACELOG_MSG_LENGTH
#define MAX_TRACELOG_MSG_LENGTH 256
#endif
#ifndef MAX_FILEPATH_CAPACITY
#define MAX_FILEPATH_CAPACITY 8192
#endif
#ifndef MAX_FILEPATH_LENGTH
#if defined(_WIN32)
#define MAX_FILEPATH_LENGTH 256
#else
#define MAX_FILEPATH_LENGTH 4096
#endif
#endif
#ifndef MAX_KEYBOARD_KEYS
#define MAX_KEYBOARD_KEYS 512
#endif
#ifndef MAX_MOUSE_BUTTONS
#define MAX_MOUSE_BUTTONS 8
#endif
#ifndef MAX_GAMEPADS
#define MAX_GAMEPADS 4
#endif
#ifndef MAX_GAMEPAD_NAME_LENGTH
#define MAX_GAMEPAD_NAME_LENGTH 128
#endif
#ifndef MAX_GAMEPAD_AXES
#define MAX_GAMEPAD_AXES 8
#endif
#ifndef MAX_GAMEPAD_BUTTONS
#define MAX_GAMEPAD_BUTTONS 32
#endif
#ifndef MAX_GAMEPAD_VIBRATION_TIME
#define MAX_GAMEPAD_VIBRATION_TIME 2.0f
#endif
#ifndef MAX_TOUCH_POINTS
#define MAX_TOUCH_POINTS 8
#endif
#ifndef MAX_KEY_PRESSED_QUEUE
#define MAX_KEY_PRESSED_QUEUE 16
#endif
#ifndef MAX_CHAR_PRESSED_QUEUE
#define MAX_CHAR_PRESSED_QUEUE 16
#endif
#ifndef MAX_DECOMPRESSION_SIZE
#define MAX_DECOMPRESSION_SIZE 64
#endif
#ifndef MAX_AUTOMATION_EVENTS
#define MAX_AUTOMATION_EVENTS 16384
#endif
#ifndef FILE_FILTER_TAG_ALL
#define FILE_FILTER_TAG_ALL "*.*"
#endif
#ifndef FILE_FILTER_TAG_FILE_ONLY
#define FILE_FILTER_TAG_FILE_ONLY "FILES*"
#endif
#ifndef FILE_FILTER_TAG_DIR_ONLY
#define FILE_FILTER_TAG_DIR_ONLY "DIRS*"
#endif
#define FLAG_SET(n, f) ((n) |= (f))
#define FLAG_CLEAR(n, f) ((n) &= ~(f))
#define FLAG_TOGGLE(n, f) ((n) ^= (f))
#define FLAG_IS_SET(n, f) (((n) & (f)) == (f))
typedef struct { int x; int y; } Point;
typedef struct { unsigned int width; unsigned int height; } Size;
typedef struct CoreData {
struct {
const char *title; unsigned int flags; bool ready; bool shouldClose; bool resizedLastFrame; bool eventWaiting; bool usingFbo;
Size display; Size screen; Point position; Size previousScreen; Point previousPosition; Size render; Point renderOffset; Size currentFbo; Size screenMin; Size screenMax; Matrix screenScale;
char **dropFilepaths; unsigned int dropFileCount;
} Window;
struct {
const char *basePath;
} Storage;
struct {
struct {
int exitKey; char currentKeyState[MAX_KEYBOARD_KEYS]; char previousKeyState[MAX_KEYBOARD_KEYS];
char keyRepeatInFrame[MAX_KEYBOARD_KEYS];
int keyPressedQueue[MAX_KEY_PRESSED_QUEUE]; int keyPressedQueueCount;
int charPressedQueue[MAX_CHAR_PRESSED_QUEUE]; int charPressedQueueCount;
} Keyboard;
struct {
Vector2 offset; Vector2 scale; Vector2 currentPosition; Vector2 previousPosition; Vector2 lockedPosition;
int cursor; bool cursorHidden; bool cursorLocked; bool cursorOnScreen;
char currentButtonState[MAX_MOUSE_BUTTONS]; char previousButtonState[MAX_MOUSE_BUTTONS]; Vector2 currentWheelMove; Vector2 previousWheelMove;
} Mouse;
struct {
int pointCount; int pointId[MAX_TOUCH_POINTS]; Vector2 position[MAX_TOUCH_POINTS]; Vector2 previousPosition[MAX_TOUCH_POINTS]; char currentTouchState[MAX_TOUCH_POINTS]; char previousTouchState[MAX_TOUCH_POINTS];
} Touch;
struct {
int lastButtonPressed; int axisCount[MAX_GAMEPADS]; bool ready[MAX_GAMEPADS]; char name[MAX_GAMEPADS][MAX_GAMEPAD_NAME_LENGTH]; char currentButtonState[MAX_GAMEPADS][MAX_GAMEPAD_BUTTONS]; char previousButtonState[MAX_GAMEPADS][MAX_GAMEPAD_BUTTONS]; float axisState[MAX_GAMEPADS][MAX_GAMEPAD_AXES];
} Gamepad;
} Input;
struct {
double current; double previous; double update; double draw; double frame; double target; unsigned long long int base; unsigned int frameCounter;
} Time;
} CoreData;
RLAPI const char *raylib_version = RAYLIB_VERSION;
CoreData CORE = { 0 };
static int logTypeLevel = LOG_INFO;
static TraceLogCallback traceLog = NULL; static LoadFileDataCallback loadFileData = NULL; static SaveFileDataCallback saveFileData = NULL; static LoadFileTextCallback loadFileText = NULL; static SaveFileTextCallback saveFileText = NULL;
#if SUPPORT_SCREEN_CAPTURE
static int screenshotCounter = 0; #endif
#if SUPPORT_AUTOMATION_EVENTS
typedef enum AutomationEventType {
EVENT_NONE = 0,
INPUT_KEY_UP, INPUT_KEY_DOWN, INPUT_KEY_PRESSED, INPUT_KEY_RELEASED, INPUT_MOUSE_BUTTON_UP, INPUT_MOUSE_BUTTON_DOWN, INPUT_MOUSE_POSITION, INPUT_MOUSE_WHEEL_MOTION, INPUT_GAMEPAD_CONNECT, INPUT_GAMEPAD_DISCONNECT, INPUT_GAMEPAD_BUTTON_UP, INPUT_GAMEPAD_BUTTON_DOWN, INPUT_GAMEPAD_AXIS_MOTION, INPUT_TOUCH_UP, INPUT_TOUCH_DOWN, INPUT_TOUCH_POSITION, INPUT_GESTURE, WINDOW_CLOSE, WINDOW_MAXIMIZE, WINDOW_MINIMIZE, WINDOW_RESIZE, ACTION_TAKE_SCREENSHOT, ACTION_SETTARGETFPS } AutomationEventType;
typedef enum {
EVENT_INPUT_KEYBOARD = 0,
EVENT_INPUT_MOUSE = 1,
EVENT_INPUT_GAMEPAD = 2,
EVENT_INPUT_TOUCH = 4,
EVENT_INPUT_GESTURE = 8,
EVENT_WINDOW = 16,
EVENT_CUSTOM = 32
} EventType;
static const char *autoEventTypeName[] = {
"EVENT_NONE",
"INPUT_KEY_UP",
"INPUT_KEY_DOWN",
"INPUT_KEY_PRESSED",
"INPUT_KEY_RELEASED",
"INPUT_MOUSE_BUTTON_UP",
"INPUT_MOUSE_BUTTON_DOWN",
"INPUT_MOUSE_POSITION",
"INPUT_MOUSE_WHEEL_MOTION",
"INPUT_GAMEPAD_CONNECT",
"INPUT_GAMEPAD_DISCONNECT",
"INPUT_GAMEPAD_BUTTON_UP",
"INPUT_GAMEPAD_BUTTON_DOWN",
"INPUT_GAMEPAD_AXIS_MOTION",
"INPUT_TOUCH_UP",
"INPUT_TOUCH_DOWN",
"INPUT_TOUCH_POSITION",
"INPUT_GESTURE",
"WINDOW_CLOSE",
"WINDOW_MAXIMIZE",
"WINDOW_MINIMIZE",
"WINDOW_RESIZE",
"ACTION_TAKE_SCREENSHOT",
"ACTION_SETTARGETFPS"
};
static AutomationEventList *currentEventList = NULL; static bool automationEventRecording = false; #endif
#if SUPPORT_MODULE_RTEXT
extern void LoadFontDefault(void); extern void UnloadFontDefault(void); #endif
extern int InitPlatform(void); extern void ClosePlatform(void);
static void InitTimer(void); static void SetupViewport(int width, int height);
static void ScanDirectoryFiles(const char *basePath, FilePathList *list, const char *filter, unsigned int expectedFileCount, bool scanSubdirs);
#if SUPPORT_AUTOMATION_EVENTS
static void RecordAutomationEvent(void); #endif
#if defined(_WIN32) && !defined(PLATFORM_DESKTOP_RGFW)
__declspec(dllimport) void __stdcall Sleep(unsigned long msTimeout); #endif
#if !SUPPORT_MODULE_RTEXT
const char *TextFormat(const char *text, ...); #endif
#if defined(PLATFORM_DESKTOP)
#define PLATFORM_DESKTOP_GLFW
#endif
#if defined(PLATFORM_DESKTOP_GLFW)
#include "platforms/rcore_desktop_glfw.c"
#elif defined(PLATFORM_DESKTOP_SDL)
#include "platforms/rcore_desktop_sdl.c"
#elif (defined(PLATFORM_DESKTOP_RGFW) || defined(PLATFORM_WEB_RGFW))
#include "platforms/rcore_desktop_rgfw.c"
#elif defined(PLATFORM_DESKTOP_WIN32)
#include "platforms/rcore_desktop_win32.c"
#elif defined(PLATFORM_WEB)
#include "platforms/rcore_web.c"
#elif defined(PLATFORM_DRM)
#include "platforms/rcore_drm.c"
#elif defined(PLATFORM_ANDROID)
#include "platforms/rcore_android.c"
#elif defined(PLATFORM_MEMORY)
#include "platforms/rcore_memory.c"
#else
#pragma message ("WARNING: No [rcore] platform defined")
#endif
void InitWindow(int width, int height, const char *title)
{
TRACELOG(LOG_INFO, "Initializing raylib %s", RAYLIB_VERSION);
#if defined(PLATFORM_DESKTOP_GLFW)
TRACELOG(LOG_INFO, "Platform backend: DESKTOP (GLFW)");
#elif defined(PLATFORM_DESKTOP_SDL)
TRACELOG(LOG_INFO, "Platform backend: DESKTOP (SDL)");
#elif defined(PLATFORM_DESKTOP_RGFW)
TRACELOG(LOG_INFO, "Platform backend: DESKTOP (RGFW)");
#elif defined(PLATFORM_DESKTOP_WIN32)
TRACELOG(LOG_INFO, "Platform backend: DESKTOP (WIN32)");
#elif defined(PLATFORM_WEB_RGFW)
TRACELOG(LOG_INFO, "Platform backend: WEB (RGFW) (HTML5)");
#elif defined(PLATFORM_WEB)
TRACELOG(LOG_INFO, "Platform backend: WEB (HTML5)");
#elif defined(PLATFORM_DRM)
TRACELOG(LOG_INFO, "Platform backend: NATIVE DRM");
#elif defined(PLATFORM_ANDROID)
TRACELOG(LOG_INFO, "Platform backend: ANDROID");
#elif defined(PLATFORM_MEMORY)
TRACELOG(LOG_INFO, "Platform backend: MEMORY (No OS)");
#else
TRACELOG(LOG_INFO, "Platform backend: CUSTOM");
#endif
TRACELOG(LOG_INFO, "Supported raylib modules:");
TRACELOG(LOG_INFO, " > rcore:..... loaded (mandatory)");
TRACELOG(LOG_INFO, " > rlgl:...... loaded (mandatory)");
#if SUPPORT_MODULE_RSHAPES
TRACELOG(LOG_INFO, " > rshapes:... loaded (optional)");
#else
TRACELOG(LOG_INFO, " > rshapes:... not loaded (optional)");
#endif
#if SUPPORT_MODULE_RTEXTURES
TRACELOG(LOG_INFO, " > rtextures:. loaded (optional)");
#else
TRACELOG(LOG_INFO, " > rtextures:. not loaded (optional)");
#endif
#if SUPPORT_MODULE_RTEXT
TRACELOG(LOG_INFO, " > rtext:..... loaded (optional)");
#else
TRACELOG(LOG_INFO, " > rtext:..... not loaded (optional)");
#endif
#if SUPPORT_MODULE_RMODELS
TRACELOG(LOG_INFO, " > rmodels:... loaded (optional)");
#else
TRACELOG(LOG_INFO, " > rmodels:... not loaded (optional)");
#endif
#if SUPPORT_MODULE_RAUDIO
TRACELOG(LOG_INFO, " > raudio:.... loaded (optional)");
#else
TRACELOG(LOG_INFO, " > raudio:.... not loaded (optional)");
#endif
CORE.Window.screen.width = width;
CORE.Window.screen.height = height;
CORE.Window.eventWaiting = false;
CORE.Window.screenScale = MatrixIdentity(); if ((title != NULL) && (title[0] != 0)) CORE.Window.title = title;
memset(&CORE.Input, 0, sizeof(CORE.Input)); CORE.Input.Keyboard.exitKey = KEY_ESCAPE;
CORE.Input.Mouse.scale = (Vector2){ 1.0f, 1.0f };
CORE.Input.Mouse.cursor = MOUSE_CURSOR_ARROW;
CORE.Input.Gamepad.lastButtonPressed = GAMEPAD_BUTTON_UNKNOWN;
int result = InitPlatform();
if (result != 0)
{
TRACELOG(LOG_WARNING, "SYSTEM: Failed to initialize platform");
return;
}
if ((CORE.Window.render.width == 0) || (CORE.Window.render.height == 0))
{
CORE.Window.render.width = CORE.Window.screen.width;
CORE.Window.render.height = CORE.Window.screen.height;
}
rlglInit(CORE.Window.render.width, CORE.Window.render.height);
SetupViewport(CORE.Window.render.width, CORE.Window.render.height);
#if SUPPORT_MODULE_RTEXT
LoadFontDefault();
#if SUPPORT_MODULE_RSHAPES
Rectangle rec = GetFontDefault().recs[95];
if (FLAG_IS_SET(CORE.Window.flags, FLAG_MSAA_4X_HINT))
{
SetShapesTexture(GetFontDefault().texture, (Rectangle){ rec.x + 2, rec.y + 2, 1, 1 });
}
else
{
SetShapesTexture(GetFontDefault().texture, (Rectangle){ rec.x + 1, rec.y + 1, rec.width - 2, rec.height - 2 });
}
#endif
#else
#if SUPPORT_MODULE_RSHAPES
Texture2D texture = { rlGetTextureIdDefault(), 1, 1, 1, PIXELFORMAT_UNCOMPRESSED_R8G8B8A8 };
SetShapesTexture(texture, (Rectangle){ 0.0f, 0.0f, 1.0f, 1.0f }); #endif
#endif
CORE.Time.frameCounter = 0;
CORE.Window.shouldClose = false;
SetRandomSeed((unsigned int)time(NULL));
TRACELOG(LOG_INFO, "SYSTEM: Working Directory: %s", GetWorkingDirectory());
}
void CloseWindow(void)
{
#if SUPPORT_MODULE_RTEXT
UnloadFontDefault(); #endif
rlglClose();
ClosePlatform();
CORE.Window.ready = false;
TRACELOG(LOG_INFO, "Window closed successfully");
}
bool IsWindowReady(void)
{
return CORE.Window.ready;
}
bool IsWindowFullscreen(void)
{
return FLAG_IS_SET(CORE.Window.flags, FLAG_FULLSCREEN_MODE);
}
bool IsWindowHidden(void)
{
return FLAG_IS_SET(CORE.Window.flags, FLAG_WINDOW_HIDDEN);
}
bool IsWindowMinimized(void)
{
return FLAG_IS_SET(CORE.Window.flags, FLAG_WINDOW_MINIMIZED);
}
bool IsWindowMaximized(void)
{
return FLAG_IS_SET(CORE.Window.flags, FLAG_WINDOW_MAXIMIZED);
}
bool IsWindowFocused(void)
{
return !FLAG_IS_SET(CORE.Window.flags, FLAG_WINDOW_UNFOCUSED);
}
bool IsWindowResized(void)
{
return CORE.Window.resizedLastFrame;
}
bool IsWindowState(unsigned int flag)
{
return FLAG_IS_SET(CORE.Window.flags, flag);
}
int GetScreenWidth(void)
{
return CORE.Window.screen.width;
}
int GetScreenHeight(void)
{
return CORE.Window.screen.height;
}
int GetRenderWidth(void)
{
int width = 0;
if (CORE.Window.usingFbo) width = CORE.Window.currentFbo.width;
else width = CORE.Window.render.width;
return width;
}
int GetRenderHeight(void)
{
int height = 0;
if (CORE.Window.usingFbo) height = CORE.Window.currentFbo.height;
else height = CORE.Window.render.height;
return height;
}
void EnableEventWaiting(void)
{
CORE.Window.eventWaiting = true;
}
void DisableEventWaiting(void)
{
CORE.Window.eventWaiting = false;
}
bool IsCursorHidden(void)
{
return CORE.Input.Mouse.cursorHidden;
}
bool IsCursorOnScreen(void)
{
return CORE.Input.Mouse.cursorOnScreen;
}
void ClearBackground(Color color)
{
rlClearColor(color.r, color.g, color.b, color.a); rlClearScreenBuffers(); }
void BeginDrawing(void)
{
CORE.Time.current = GetTime(); CORE.Time.update = CORE.Time.current - CORE.Time.previous;
CORE.Time.previous = CORE.Time.current;
rlLoadIdentity(); rlMultMatrixf(MatrixToFloat(CORE.Window.screenScale));
}
void EndDrawing(void)
{
rlDrawRenderBatchActive();
#if SUPPORT_AUTOMATION_EVENTS
if (automationEventRecording) RecordAutomationEvent(); #endif
#if !SUPPORT_CUSTOM_FRAME_CONTROL
SwapScreenBuffer();
CORE.Time.current = GetTime();
CORE.Time.draw = CORE.Time.current - CORE.Time.previous;
CORE.Time.previous = CORE.Time.current;
CORE.Time.frame = CORE.Time.update + CORE.Time.draw;
if (CORE.Time.frame < CORE.Time.target)
{
WaitTime(CORE.Time.target - CORE.Time.frame);
CORE.Time.current = GetTime();
double waitTime = CORE.Time.current - CORE.Time.previous;
CORE.Time.previous = CORE.Time.current;
CORE.Time.frame += waitTime; }
PollInputEvents(); #endif
#if SUPPORT_SCREEN_CAPTURE
if (IsKeyPressed(KEY_F12))
{
TakeScreenshot(TextFormat("screenshot%03i.png", screenshotCounter));
screenshotCounter++;
}
#endif
CORE.Time.frameCounter++;
}
void BeginMode2D(Camera2D camera)
{
rlDrawRenderBatchActive();
rlLoadIdentity();
rlMultMatrixf(MatrixToFloat(GetCameraMatrix2D(camera)));
}
void EndMode2D(void)
{
rlDrawRenderBatchActive();
rlLoadIdentity();
if (rlGetActiveFramebuffer() == 0) rlMultMatrixf(MatrixToFloat(CORE.Window.screenScale)); }
void BeginMode3D(Camera camera)
{
rlDrawRenderBatchActive();
rlMatrixMode(RL_PROJECTION); rlPushMatrix(); rlLoadIdentity();
float aspect = (float)CORE.Window.currentFbo.width/(float)CORE.Window.currentFbo.height;
if (camera.projection == CAMERA_PERSPECTIVE)
{
double top = rlGetCullDistanceNear()*tan(camera.fovy*0.5*DEG2RAD);
double right = top*aspect;
rlFrustum(-right, right, -top, top, rlGetCullDistanceNear(), rlGetCullDistanceFar());
}
else if (camera.projection == CAMERA_ORTHOGRAPHIC)
{
double top = camera.fovy/2.0;
double right = top*aspect;
rlOrtho(-right, right, -top,top, rlGetCullDistanceNear(), rlGetCullDistanceFar());
}
rlMatrixMode(RL_MODELVIEW); rlLoadIdentity();
Matrix matView = MatrixLookAt(camera.position, camera.target, camera.up);
rlMultMatrixf(MatrixToFloat(matView));
rlEnableDepthTest(); }
void EndMode3D(void)
{
rlDrawRenderBatchActive();
rlMatrixMode(RL_PROJECTION); rlPopMatrix();
rlMatrixMode(RL_MODELVIEW); rlLoadIdentity();
if (rlGetActiveFramebuffer() == 0) rlMultMatrixf(MatrixToFloat(CORE.Window.screenScale));
rlDisableDepthTest(); }
void BeginTextureMode(RenderTexture2D target)
{
rlDrawRenderBatchActive();
rlEnableFramebuffer(target.id);
rlViewport(0, 0, target.texture.width, target.texture.height);
rlSetFramebufferWidth(target.texture.width);
rlSetFramebufferHeight(target.texture.height);
rlMatrixMode(RL_PROJECTION); rlLoadIdentity();
rlOrtho(0, target.texture.width, target.texture.height, 0, 0.0f, 1.0f);
rlMatrixMode(RL_MODELVIEW); rlLoadIdentity();
CORE.Window.currentFbo.width = target.texture.width;
CORE.Window.currentFbo.height = target.texture.height;
CORE.Window.usingFbo = true;
}
void EndTextureMode(void)
{
rlDrawRenderBatchActive();
rlDisableFramebuffer();
SetupViewport(CORE.Window.render.width, CORE.Window.render.height);
rlMatrixMode(RL_MODELVIEW); rlLoadIdentity(); rlMultMatrixf(MatrixToFloat(CORE.Window.screenScale));
CORE.Window.currentFbo.width = CORE.Window.render.width;
CORE.Window.currentFbo.height = CORE.Window.render.height;
CORE.Window.usingFbo = false;
}
void BeginShaderMode(Shader shader)
{
rlSetShader(shader.id, shader.locs);
}
void EndShaderMode(void)
{
rlSetShader(rlGetShaderIdDefault(), rlGetShaderLocsDefault());
}
void BeginBlendMode(int mode)
{
rlSetBlendMode(mode);
}
void EndBlendMode(void)
{
rlSetBlendMode(BLEND_ALPHA);
}
void BeginScissorMode(int x, int y, int width, int height)
{
rlDrawRenderBatchActive();
rlEnableScissorTest();
#if defined(__APPLE__)
if (!CORE.Window.usingFbo)
{
Vector2 scale = GetWindowScaleDPI();
rlScissor((int)(x*scale.x), (int)(GetScreenHeight()*scale.y - (((y + height)*scale.y))), (int)(width*scale.x), (int)(height*scale.y));
}
#else
if (!CORE.Window.usingFbo && FLAG_IS_SET(CORE.Window.flags, FLAG_WINDOW_HIGHDPI))
{
Vector2 scale = GetWindowScaleDPI();
rlScissor((int)(x*scale.x), (int)(CORE.Window.currentFbo.height - (y + height)*scale.y), (int)(width*scale.x), (int)(height*scale.y));
}
#endif
else
{
rlScissor(x, CORE.Window.currentFbo.height - (y + height), width, height);
}
}
void EndScissorMode(void)
{
rlDrawRenderBatchActive(); rlDisableScissorTest();
}
void BeginVrStereoMode(VrStereoConfig config)
{
rlEnableStereoRender();
rlSetMatrixProjectionStereo(config.projection[0], config.projection[1]);
rlSetMatrixViewOffsetStereo(config.viewOffset[0], config.viewOffset[1]);
}
void EndVrStereoMode(void)
{
rlDisableStereoRender();
}
VrStereoConfig LoadVrStereoConfig(VrDeviceInfo device)
{
VrStereoConfig config = { 0 };
if (rlGetVersion() != RL_OPENGL_11)
{
float aspect = ((float)device.hResolution*0.5f)/(float)device.vResolution;
float lensShift = (device.hScreenSize*0.25f - device.lensSeparationDistance*0.5f)/device.hScreenSize;
config.leftLensCenter[0] = 0.25f + lensShift;
config.leftLensCenter[1] = 0.5f;
config.rightLensCenter[0] = 0.75f - lensShift;
config.rightLensCenter[1] = 0.5f;
config.leftScreenCenter[0] = 0.25f;
config.leftScreenCenter[1] = 0.5f;
config.rightScreenCenter[0] = 0.75f;
config.rightScreenCenter[1] = 0.5f;
float lensRadius = fabsf(-1.0f - 4.0f*lensShift);
float lensRadiusSq = lensRadius*lensRadius;
float distortionScale = device.lensDistortionValues[0] +
device.lensDistortionValues[1]*lensRadiusSq +
device.lensDistortionValues[2]*lensRadiusSq*lensRadiusSq +
device.lensDistortionValues[3]*lensRadiusSq*lensRadiusSq*lensRadiusSq;
float normScreenWidth = 0.5f;
float normScreenHeight = 1.0f;
config.scaleIn[0] = 2.0f/normScreenWidth;
config.scaleIn[1] = 2.0f/normScreenHeight/aspect;
config.scale[0] = normScreenWidth*0.5f/distortionScale;
config.scale[1] = normScreenHeight*0.5f*aspect/distortionScale;
float fovy = 2.0f*atan2f(device.vScreenSize*0.5f*distortionScale, device.eyeToScreenDistance);
float projOffset = 4.0f*lensShift; Matrix proj = MatrixPerspective(fovy, aspect, rlGetCullDistanceNear(), rlGetCullDistanceFar());
config.projection[0] = MatrixMultiply(proj, MatrixTranslate(projOffset, 0.0f, 0.0f));
config.projection[1] = MatrixMultiply(proj, MatrixTranslate(-projOffset, 0.0f, 0.0f));
config.viewOffset[0] = MatrixTranslate(device.interpupillaryDistance*0.5f, 0.075f, 0.045f);
config.viewOffset[1] = MatrixTranslate(-device.interpupillaryDistance*0.5f, 0.075f, 0.045f);
}
else TRACELOG(LOG_WARNING, "RLGL: VR Simulator not supported on OpenGL 1.1");
return config;
}
void UnloadVrStereoConfig(VrStereoConfig config)
{
TRACELOG(LOG_INFO, "UnloadVrStereoConfig not implemented in rcore.c");
}
Shader LoadShader(const char *vsFileName, const char *fsFileName)
{
Shader shader = { 0 };
char *vShaderStr = NULL;
char *fShaderStr = NULL;
if (vsFileName != NULL) vShaderStr = LoadFileText(vsFileName);
if (fsFileName != NULL) fShaderStr = LoadFileText(fsFileName);
if ((vShaderStr == NULL) && (fShaderStr == NULL)) TRACELOG(LOG_WARNING, "SHADER: Shader files provided are not valid, using default shader");
shader = LoadShaderFromMemory(vShaderStr, fShaderStr);
UnloadFileText(vShaderStr);
UnloadFileText(fShaderStr);
return shader;
}
Shader LoadShaderFromMemory(const char *vsCode, const char *fsCode)
{
Shader shader = { 0 };
shader.id = rlLoadShaderProgram(vsCode, fsCode);
if (shader.id == 0)
{
shader.locs = (int *)RL_CALLOC(RL_MAX_SHADER_LOCATIONS, sizeof(int));
for (int i = 0; i < RL_MAX_SHADER_LOCATIONS; i++) shader.locs[i] = -1;
}
else if (shader.id == rlGetShaderIdDefault()) shader.locs = rlGetShaderLocsDefault();
else if (shader.id > 0)
{
shader.locs = (int *)RL_CALLOC(RL_MAX_SHADER_LOCATIONS, sizeof(int));
for (int i = 0; i < RL_MAX_SHADER_LOCATIONS; i++) shader.locs[i] = -1;
shader.locs[SHADER_LOC_VERTEX_POSITION] = rlGetLocationAttrib(shader.id, RL_DEFAULT_SHADER_ATTRIB_NAME_POSITION);
shader.locs[SHADER_LOC_VERTEX_TEXCOORD01] = rlGetLocationAttrib(shader.id, RL_DEFAULT_SHADER_ATTRIB_NAME_TEXCOORD);
shader.locs[SHADER_LOC_VERTEX_TEXCOORD02] = rlGetLocationAttrib(shader.id, RL_DEFAULT_SHADER_ATTRIB_NAME_TEXCOORD2);
shader.locs[SHADER_LOC_VERTEX_NORMAL] = rlGetLocationAttrib(shader.id, RL_DEFAULT_SHADER_ATTRIB_NAME_NORMAL);
shader.locs[SHADER_LOC_VERTEX_TANGENT] = rlGetLocationAttrib(shader.id, RL_DEFAULT_SHADER_ATTRIB_NAME_TANGENT);
shader.locs[SHADER_LOC_VERTEX_COLOR] = rlGetLocationAttrib(shader.id, RL_DEFAULT_SHADER_ATTRIB_NAME_COLOR);
shader.locs[SHADER_LOC_VERTEX_BONEIDS] = rlGetLocationAttrib(shader.id, RL_DEFAULT_SHADER_ATTRIB_NAME_BONEINDICES);
shader.locs[SHADER_LOC_VERTEX_BONEWEIGHTS] = rlGetLocationAttrib(shader.id, RL_DEFAULT_SHADER_ATTRIB_NAME_BONEWEIGHTS);
shader.locs[SHADER_LOC_VERTEX_INSTANCETRANSFORM] = rlGetLocationAttrib(shader.id, RL_DEFAULT_SHADER_ATTRIB_NAME_INSTANCETRANSFORM);
shader.locs[SHADER_LOC_MATRIX_MVP] = rlGetLocationUniform(shader.id, RL_DEFAULT_SHADER_UNIFORM_NAME_MVP);
shader.locs[SHADER_LOC_MATRIX_VIEW] = rlGetLocationUniform(shader.id, RL_DEFAULT_SHADER_UNIFORM_NAME_VIEW);
shader.locs[SHADER_LOC_MATRIX_PROJECTION] = rlGetLocationUniform(shader.id, RL_DEFAULT_SHADER_UNIFORM_NAME_PROJECTION);
shader.locs[SHADER_LOC_MATRIX_MODEL] = rlGetLocationUniform(shader.id, RL_DEFAULT_SHADER_UNIFORM_NAME_MODEL);
shader.locs[SHADER_LOC_MATRIX_NORMAL] = rlGetLocationUniform(shader.id, RL_DEFAULT_SHADER_UNIFORM_NAME_NORMAL);
shader.locs[SHADER_LOC_MATRIX_BONETRANSFORMS] = rlGetLocationUniform(shader.id, RL_DEFAULT_SHADER_UNIFORM_NAME_BONEMATRICES);
shader.locs[SHADER_LOC_COLOR_DIFFUSE] = rlGetLocationUniform(shader.id, RL_DEFAULT_SHADER_UNIFORM_NAME_COLOR);
shader.locs[SHADER_LOC_MAP_DIFFUSE] = rlGetLocationUniform(shader.id, RL_DEFAULT_SHADER_SAMPLER2D_NAME_TEXTURE0); shader.locs[SHADER_LOC_MAP_SPECULAR] = rlGetLocationUniform(shader.id, RL_DEFAULT_SHADER_SAMPLER2D_NAME_TEXTURE1); shader.locs[SHADER_LOC_MAP_NORMAL] = rlGetLocationUniform(shader.id, RL_DEFAULT_SHADER_SAMPLER2D_NAME_TEXTURE2);
}
return shader;
}
bool IsShaderValid(Shader shader)
{
return ((shader.id > 0) && (shader.locs != NULL));
}
void UnloadShader(Shader shader)
{
if (shader.id != rlGetShaderIdDefault())
{
rlUnloadShaderProgram(shader.id);
RL_FREE(shader.locs);
}
}
int GetShaderLocation(Shader shader, const char *uniformName)
{
return rlGetLocationUniform(shader.id, uniformName);
}
int GetShaderLocationAttrib(Shader shader, const char *attribName)
{
return rlGetLocationAttrib(shader.id, attribName);
}
void SetShaderValue(Shader shader, int locIndex, const void *value, int uniformType)
{
SetShaderValueV(shader, locIndex, value, uniformType, 1);
}
void SetShaderValueV(Shader shader, int locIndex, const void *value, int uniformType, int count)
{
if (locIndex > -1)
{
rlEnableShader(shader.id);
rlSetUniform(locIndex, value, uniformType, count);
}
}
void SetShaderValueMatrix(Shader shader, int locIndex, Matrix mat)
{
if (locIndex > -1)
{
rlEnableShader(shader.id);
rlSetUniformMatrix(locIndex, mat);
}
}
void SetShaderValueTexture(Shader shader, int locIndex, Texture2D texture)
{
if (locIndex > -1)
{
rlEnableShader(shader.id);
rlSetUniformSampler(locIndex, texture.id);
}
}
Ray GetScreenToWorldRay(Vector2 position, Camera camera)
{
Ray ray = GetScreenToWorldRayEx(position, camera, GetScreenWidth(), GetScreenHeight());
return ray;
}
Ray GetScreenToWorldRayEx(Vector2 position, Camera camera, int width, int height)
{
Ray ray = { 0 };
float x = (2.0f*position.x)/(float)width - 1.0f;
float y = 1.0f - (2.0f*position.y)/(float)height;
float z = 1.0f;
Vector3 deviceCoords = { x, y, z };
Matrix matView = MatrixLookAt(camera.position, camera.target, camera.up);
Matrix matProj = MatrixIdentity();
if (camera.projection == CAMERA_PERSPECTIVE)
{
matProj = MatrixPerspective(camera.fovy*DEG2RAD, ((double)width/(double)height), rlGetCullDistanceNear(), rlGetCullDistanceFar());
}
else if (camera.projection == CAMERA_ORTHOGRAPHIC)
{
double aspect = (double)width/(double)height;
double top = camera.fovy/2.0;
double right = top*aspect;
matProj = MatrixOrtho(-right, right, -top, top, rlGetCullDistanceNear(), rlGetCullDistanceFar());
}
Vector3 nearPoint = Vector3Unproject((Vector3){ deviceCoords.x, deviceCoords.y, 0.0f }, matProj, matView);
Vector3 farPoint = Vector3Unproject((Vector3){ deviceCoords.x, deviceCoords.y, 1.0f }, matProj, matView);
Vector3 cameraPlanePointerPos = Vector3Unproject((Vector3){ deviceCoords.x, deviceCoords.y, -1.0f }, matProj, matView);
Vector3 direction = Vector3Normalize(Vector3Subtract(farPoint, nearPoint));
if (camera.projection == CAMERA_PERSPECTIVE) ray.position = camera.position;
else if (camera.projection == CAMERA_ORTHOGRAPHIC) ray.position = cameraPlanePointerPos;
ray.direction = direction;
return ray;
}
Matrix GetCameraMatrix(Camera camera)
{
Matrix mat = MatrixLookAt(camera.position, camera.target, camera.up);
return mat;
}
Matrix GetCameraMatrix2D(Camera2D camera)
{
Matrix matTransform = { 0 };
Matrix matOrigin = MatrixTranslate(-camera.target.x, -camera.target.y, 0.0f);
Matrix matRotation = MatrixRotate((Vector3){ 0.0f, 0.0f, 1.0f }, camera.rotation*DEG2RAD);
Matrix matScale = MatrixScale(camera.zoom, camera.zoom, 1.0f);
Matrix matTranslation = MatrixTranslate(camera.offset.x, camera.offset.y, 0.0f);
matTransform = MatrixMultiply(MatrixMultiply(matOrigin, MatrixMultiply(matScale, matRotation)), matTranslation);
return matTransform;
}
Vector2 GetWorldToScreen(Vector3 position, Camera camera)
{
Vector2 screenPosition = GetWorldToScreenEx(position, camera, GetScreenWidth(), GetScreenHeight());
return screenPosition;
}
Vector2 GetWorldToScreenEx(Vector3 position, Camera camera, int width, int height)
{
Matrix matProj = MatrixIdentity();
if (camera.projection == CAMERA_PERSPECTIVE)
{
matProj = MatrixPerspective(camera.fovy*DEG2RAD, ((double)width/(double)height), rlGetCullDistanceNear(), rlGetCullDistanceFar());
}
else if (camera.projection == CAMERA_ORTHOGRAPHIC)
{
double aspect = (double)width/(double)height;
double top = camera.fovy/2.0;
double right = top*aspect;
matProj = MatrixOrtho(-right, right, -top, top, rlGetCullDistanceNear(), rlGetCullDistanceFar());
}
Matrix matView = MatrixLookAt(camera.position, camera.target, camera.up);
Quaternion worldPos = { position.x, position.y, position.z, 1.0f };
worldPos = QuaternionTransform(worldPos, matView);
worldPos = QuaternionTransform(worldPos, matProj);
Vector3 ndcPos = { worldPos.x/worldPos.w, -worldPos.y/worldPos.w, worldPos.z/worldPos.w };
Vector2 screenPosition = { (ndcPos.x + 1.0f)/2.0f*(float)width, (ndcPos.y + 1.0f)/2.0f*(float)height };
return screenPosition;
}
Vector2 GetWorldToScreen2D(Vector2 position, Camera2D camera)
{
Matrix matCamera = GetCameraMatrix2D(camera);
Vector3 transform = Vector3Transform((Vector3){ position.x, position.y, 0 }, matCamera);
return (Vector2){ transform.x, transform.y };
}
Vector2 GetScreenToWorld2D(Vector2 position, Camera2D camera)
{
Matrix invMatCamera = MatrixInvert(GetCameraMatrix2D(camera));
Vector3 transform = Vector3Transform((Vector3){ position.x, position.y, 0 }, invMatCamera);
return (Vector2){ transform.x, transform.y };
}
void SetTargetFPS(int fps)
{
if (fps < 1) CORE.Time.target = 0.0;
else CORE.Time.target = 1.0/(double)fps;
TRACELOG(LOG_INFO, "TIMER: Target time per frame: %02.03f milliseconds", (float)CORE.Time.target*1000.0f);
}
int GetFPS(void)
{
int fps = 0;
#if !SUPPORT_CUSTOM_FRAME_CONTROL
#define FPS_CAPTURE_FRAMES_COUNT 30
#define FPS_AVERAGE_TIME_SECONDS 0.5f
#define FPS_STEP (FPS_AVERAGE_TIME_SECONDS/FPS_CAPTURE_FRAMES_COUNT)
static int index = 0;
static float history[FPS_CAPTURE_FRAMES_COUNT] = { 0 };
static float average = 0, last = 0;
float fpsFrame = GetFrameTime();
if (CORE.Time.frameCounter == 0)
{
average = 0;
last = 0;
index = 0;
for (int i = 0; i < FPS_CAPTURE_FRAMES_COUNT; i++) history[i] = 0;
}
if (fpsFrame != 0)
{
if ((GetTime() - last) > FPS_STEP)
{
last = (float)GetTime();
index = (index + 1)%FPS_CAPTURE_FRAMES_COUNT;
average -= history[index];
history[index] = fpsFrame/FPS_CAPTURE_FRAMES_COUNT;
average += history[index];
}
fps = (int)roundf(1.0f/average);
}
else fps = 0;
#endif
return fps;
}
float GetFrameTime(void)
{
return (float)CORE.Time.frame;
}
void WaitTime(double seconds)
{
if (seconds < 0) return;
#if SUPPORT_BUSY_WAIT_LOOP || SUPPORT_PARTIALBUSY_WAIT_LOOP
double destinationTime = GetTime() + seconds;
#endif
#if SUPPORT_BUSY_WAIT_LOOP
while (GetTime() < destinationTime) { }
#else
#if SUPPORT_PARTIALBUSY_WAIT_LOOP
double sleepSeconds = seconds - seconds*0.05; #else
double sleepSeconds = seconds;
#endif
#if defined(_WIN32)
Sleep((unsigned long)(sleepSeconds*1000.0));
#endif
#if defined(__linux__) || defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__EMSCRIPTEN__)
struct timespec req = { 0 };
time_t sec = sleepSeconds;
long nsec = (sleepSeconds - sec)*1000000000L;
req.tv_sec = sec;
req.tv_nsec = nsec;
while (nanosleep(&req, &req) == -1) continue;
#endif
#if defined(__APPLE__)
usleep(sleepSeconds*1000000.0);
#endif
#if SUPPORT_PARTIALBUSY_WAIT_LOOP
while (GetTime() < destinationTime) { }
#endif
#endif
}
void SetRandomSeed(unsigned int seed)
{
#if SUPPORT_RPRAND_GENERATOR
rprand_set_seed(seed);
#else
srand(seed);
#endif
}
int GetRandomValue(int min, int max)
{
int value = 0;
if (min > max)
{
int tmp = max;
max = min;
min = tmp;
}
#if SUPPORT_RPRAND_GENERATOR
value = rprand_get_value(min, max);
#else
if ((unsigned int)(max - min) > (unsigned int)RAND_MAX)
{
TRACELOG(LOG_WARNING, "Invalid GetRandomValue() arguments, range should not be higher than %i", RAND_MAX);
}
int range = (max - min) + 1;
if (range <= 0) value = min;
else
{
unsigned long c = (unsigned long)RAND_MAX + 1UL; unsigned long m = (unsigned long)range; unsigned long t = c - (c%m); unsigned long r = 0;
for (;;)
{
r = (unsigned long)rand();
if (r < t) break; }
value = min + (int)(r%m);
}
#endif
return value;
}
int *LoadRandomSequence(unsigned int count, int min, int max)
{
int *values = NULL;
#if SUPPORT_RPRAND_GENERATOR
values = rprand_load_sequence(count, min, max);
#else
if (count > ((unsigned int)abs(max - min) + 1)) return values;
values = (int *)RL_CALLOC(count, sizeof(int));
int value = 0;
bool dupValue = false;
for (int i = 0; i < (int)count;)
{
value = GetRandomValue(min, max);
dupValue = false;
for (int j = 0; j < i; j++)
{
if (values[j] == value)
{
dupValue = true;
break;
}
}
if (!dupValue)
{
values[i] = value;
i++;
}
}
#endif
return values;
}
void UnloadRandomSequence(int *sequence)
{
#if SUPPORT_RPRAND_GENERATOR
rprand_unload_sequence(sequence);
#else
RL_FREE(sequence);
#endif
}
void TakeScreenshot(const char *fileName)
{
#if SUPPORT_MODULE_RTEXTURES
if (strchr(fileName, '\'') != NULL) { TRACELOG(LOG_WARNING, "SYSTEM: Provided fileName could be potentially malicious, avoid [\'] character"); return; }
Vector2 scale = { 1.0f, 1.0f };
if (FLAG_IS_SET(CORE.Window.flags, FLAG_WINDOW_HIGHDPI)) scale = GetWindowScaleDPI();
unsigned char *imgData = rlReadScreenPixels((int)((float)CORE.Window.render.width*scale.x), (int)((float)CORE.Window.render.height*scale.y));
Image image = { imgData, (int)((float)CORE.Window.render.width*scale.x), (int)((float)CORE.Window.render.height*scale.y), 1, PIXELFORMAT_UNCOMPRESSED_R8G8B8A8 };
char path[MAX_FILEPATH_LENGTH] = { 0 };
strncpy(path, TextFormat("%s/%s", CORE.Storage.basePath, fileName), MAX_FILEPATH_LENGTH - 1);
ExportImage(image, path); RL_FREE(imgData);
if (FileExists(path)) TRACELOG(LOG_INFO, "SYSTEM: [%s] Screenshot taken successfully", path);
else TRACELOG(LOG_WARNING, "SYSTEM: [%s] Screenshot could not be saved", path);
#else
TRACELOG(LOG_WARNING,"IMAGE: ExportImage() requires module: rtextures");
#endif
}
void SetConfigFlags(unsigned int flags)
{
if (CORE.Window.ready) TRACELOG(LOG_WARNING, "WINDOW: SetConfigFlags called after window initialization, Use \"SetWindowState\" to set flags instead");
FLAG_SET(CORE.Window.flags, flags);
}
void SetTraceLogLevel(int logType) { logTypeLevel = logType; }
void TraceLog(int logType, const char *text, ...)
{
#if SUPPORT_TRACELOG
if ((logType < logTypeLevel) || (text == NULL)) return;
va_list args;
va_start(args, text);
if (traceLog)
{
traceLog(logType, text, args);
va_end(args);
return;
}
#if defined(PLATFORM_ANDROID)
switch (logType)
{
case LOG_TRACE: __android_log_vprint(ANDROID_LOG_VERBOSE, "raylib", text, args); break;
case LOG_DEBUG: __android_log_vprint(ANDROID_LOG_DEBUG, "raylib", text, args); break;
case LOG_INFO: __android_log_vprint(ANDROID_LOG_INFO, "raylib", text, args); break;
case LOG_WARNING: __android_log_vprint(ANDROID_LOG_WARN, "raylib", text, args); break;
case LOG_ERROR: __android_log_vprint(ANDROID_LOG_ERROR, "raylib", text, args); break;
case LOG_FATAL: __android_log_vprint(ANDROID_LOG_FATAL, "raylib", text, args); break;
default: break;
}
#else
char buffer[MAX_TRACELOG_MSG_LENGTH] = { 0 };
switch (logType)
{
case LOG_TRACE: strncpy(buffer, "TRACE: ", 8); break;
case LOG_DEBUG: strncpy(buffer, "DEBUG: ", 8); break;
case LOG_INFO: strncpy(buffer, "INFO: ", 7); break;
case LOG_WARNING: strncpy(buffer, "WARNING: ", 10); break;
case LOG_ERROR: strncpy(buffer, "ERROR: ", 8); break;
case LOG_FATAL: strncpy(buffer, "FATAL: ", 8); break;
default: break;
}
unsigned int textLength = (unsigned int)strlen(text);
memcpy(buffer + strlen(buffer), text, (textLength < (MAX_TRACELOG_MSG_LENGTH - 12))? textLength : (MAX_TRACELOG_MSG_LENGTH - 12));
strcat(buffer, "\n");
vprintf(buffer, args);
fflush(stdout);
#endif
va_end(args);
if (logType == LOG_FATAL) exit(EXIT_FAILURE); #endif
}
void SetTraceLogCallback(TraceLogCallback callback)
{
traceLog = callback;
}
void *MemAlloc(unsigned int size)
{
void *ptr = RL_CALLOC(size, 1);
return ptr;
}
void *MemRealloc(void *ptr, unsigned int size)
{
void *ret = RL_REALLOC(ptr, size);
return ret;
}
void MemFree(void *ptr)
{
RL_FREE(ptr);
}
unsigned char *LoadFileData(const char *fileName, int *dataSize)
{
unsigned char *data = NULL;
*dataSize = 0;
if (fileName != NULL)
{
if (loadFileData) return loadFileData(fileName, dataSize);
FILE *file = fopen(fileName, "rb");
if (file != NULL)
{
fseek(file, 0, SEEK_END);
int size = ftell(file); fseek(file, 0, SEEK_SET);
if (size > 0)
{
data = (unsigned char *)RL_CALLOC(size, sizeof(unsigned char));
if (data != NULL)
{
size_t count = fread(data, sizeof(unsigned char), size, file);
if (count > 2147483647)
{
TRACELOG(LOG_WARNING, "FILEIO: [%s] File is bigger than 2147483647 bytes, avoid using LoadFileData()", fileName);
RL_FREE(data);
data = NULL;
}
else
{
*dataSize = (int)count;
if ((*dataSize) != size) TRACELOG(LOG_WARNING, "FILEIO: [%s] File partially loaded (%i bytes out of %i)", fileName, dataSize, count);
else TRACELOG(LOG_INFO, "FILEIO: [%s] File loaded successfully", fileName);
}
}
else TRACELOG(LOG_WARNING, "FILEIO: [%s] Failed to allocated memory for file reading", fileName);
}
else TRACELOG(LOG_WARNING, "FILEIO: [%s] Failed to read file", fileName);
fclose(file);
}
else TRACELOG(LOG_WARNING, "FILEIO: [%s] Failed to open file", fileName);
}
else TRACELOG(LOG_WARNING, "FILEIO: File name provided is not valid");
return data;
}
void UnloadFileData(unsigned char *data)
{
RL_FREE(data);
}
bool SaveFileData(const char *fileName, void *data, int dataSize)
{
bool result = false;
if (fileName != NULL)
{
if (saveFileData) return saveFileData(fileName, data, dataSize);
FILE *file = fopen(fileName, "wb");
if (file != NULL)
{
int count = (int)fwrite(data, sizeof(unsigned char), dataSize, file);
if (count == 0) TRACELOG(LOG_WARNING, "FILEIO: [%s] Failed to write file", fileName);
else if (count != dataSize) TRACELOG(LOG_WARNING, "FILEIO: [%s] File partially written", fileName);
else TRACELOG(LOG_INFO, "FILEIO: [%s] File saved successfully", fileName);
int closed = fclose(file);
if (closed == 0) result = true;
}
else TRACELOG(LOG_WARNING, "FILEIO: [%s] Failed to open file", fileName);
}
else TRACELOG(LOG_WARNING, "FILEIO: File name provided is not valid");
return result;
}
bool ExportDataAsCode(const unsigned char *data, int dataSize, const char *fileName)
{
bool result = false;
#ifndef TEXT_BYTES_PER_LINE
#define TEXT_BYTES_PER_LINE 20
#endif
char *txtData = (char *)RL_CALLOC(dataSize*6 + 2000, sizeof(char));
int byteCount = 0;
byteCount += sprintf(txtData + byteCount, "////////////////////////////////////////////////////////////////////////////////////////\n");
byteCount += sprintf(txtData + byteCount, "// //\n");
byteCount += sprintf(txtData + byteCount, "// DataAsCode exporter v1.0 - Raw data exported as an array of bytes //\n");
byteCount += sprintf(txtData + byteCount, "// //\n");
byteCount += sprintf(txtData + byteCount, "// more info and bugs-report: github.com/raysan5/raylib //\n");
byteCount += sprintf(txtData + byteCount, "// feedback and support: ray[at]raylib.com //\n");
byteCount += sprintf(txtData + byteCount, "// //\n");
byteCount += sprintf(txtData + byteCount, "// Copyright (c) 2022-2026 Ramon Santamaria (@raysan5) //\n");
byteCount += sprintf(txtData + byteCount, "// //\n");
byteCount += sprintf(txtData + byteCount, "////////////////////////////////////////////////////////////////////////////////////////\n\n");
char varFileName[256] = { 0 };
strncpy(varFileName, GetFileNameWithoutExt(fileName), 256 - 1);
for (int i = 0; varFileName[i] != '\0'; i++)
{
if ((varFileName[i] >= 'a') && (varFileName[i] <= 'z')) { varFileName[i] = varFileName[i] - 32; }
else if (varFileName[i] == '.' || varFileName[i] == '-' || varFileName[i] == '?' || varFileName[i] == '!' || varFileName[i] == '+') { varFileName[i] = '_'; }
}
byteCount += sprintf(txtData + byteCount, "#define %s_DATA_SIZE %i\n\n", varFileName, dataSize);
byteCount += sprintf(txtData + byteCount, "static unsigned char %s_DATA[%s_DATA_SIZE] = { ", varFileName, varFileName);
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]);
byteCount += sprintf(txtData + byteCount, "0x%x };\n", data[dataSize - 1]);
result = SaveFileText(fileName, txtData);
RL_FREE(txtData);
if (result != 0) TRACELOG(LOG_INFO, "FILEIO: [%s] Data as code exported successfully", fileName);
else TRACELOG(LOG_WARNING, "FILEIO: [%s] Failed to export data as code", fileName);
return result;
}
char *LoadFileText(const char *fileName)
{
char *text = NULL;
if (fileName != NULL)
{
if (loadFileText) return loadFileText(fileName);
FILE *file = fopen(fileName, "rt");
if (file != NULL)
{
fseek(file, 0, SEEK_END);
unsigned int size = (unsigned int)ftell(file);
fseek(file, 0, SEEK_SET);
if (size > 0)
{
text = (char *)RL_CALLOC(size + 1, sizeof(char));
if (text != NULL)
{
unsigned int count = (unsigned int)fread(text, sizeof(char), size, file);
if (count < size) text = (char *)RL_REALLOC(text, count + 1);
text[count] = '\0';
TRACELOG(LOG_INFO, "FILEIO: [%s] Text file loaded successfully", fileName);
}
else TRACELOG(LOG_WARNING, "FILEIO: [%s] Failed to allocated memory for file reading", fileName);
}
else TRACELOG(LOG_WARNING, "FILEIO: [%s] Failed to read text file", fileName);
fclose(file);
}
else TRACELOG(LOG_WARNING, "FILEIO: [%s] Failed to open text file", fileName);
}
else TRACELOG(LOG_WARNING, "FILEIO: File name provided is not valid");
return text;
}
void UnloadFileText(char *text)
{
RL_FREE(text);
}
bool SaveFileText(const char *fileName, const char *text)
{
bool result = false;
if (fileName != NULL)
{
if (saveFileText) return saveFileText(fileName, text);
FILE *file = fopen(fileName, "wt");
if (file != NULL)
{
int count = fprintf(file, "%s", text);
if (count < 0) TRACELOG(LOG_WARNING, "FILEIO: [%s] Failed to write text file", fileName);
else TRACELOG(LOG_INFO, "FILEIO: [%s] Text file saved successfully", fileName);
int closed = fclose(file);
if (closed == 0) result = true;
}
else TRACELOG(LOG_WARNING, "FILEIO: [%s] Failed to open text file", fileName);
}
else TRACELOG(LOG_WARNING, "FILEIO: File name provided is not valid");
return result;
}
void SetLoadFileDataCallback(LoadFileDataCallback callback)
{
loadFileData = callback;
}
void SetSaveFileDataCallback(SaveFileDataCallback callback)
{
saveFileData = callback;
}
void SetLoadFileTextCallback(LoadFileTextCallback callback)
{
loadFileText = callback;
}
void SetSaveFileTextCallback(SaveFileTextCallback callback)
{
saveFileText = callback;
}
int FileRename(const char *fileName, const char *fileRename)
{
int result = 0;
if (FileExists(fileName))
{
result = rename(fileName, fileRename);
}
else result = -1;
return result;
}
int FileRemove(const char *fileName)
{
int result = 0;
if (FileExists(fileName))
{
result = remove(fileName);
}
else result = -1;
return result;
}
int FileCopy(const char *srcPath, const char *dstPath)
{
int result = 0;
int srcDataSize = 0;
unsigned char *srcFileData = LoadFileData(srcPath, &srcDataSize);
if (!DirectoryExists(GetDirectoryPath(dstPath)))
result = MakeDirectory(GetDirectoryPath(dstPath));
if (result == 0) {
if ((srcFileData != NULL) && (srcDataSize > 0))
result = SaveFileData(dstPath, srcFileData, srcDataSize);
}
UnloadFileData(srcFileData);
return result;
}
int FileMove(const char *srcPath, const char *dstPath)
{
int result = -1;
if (FileExists(srcPath))
{
if (FileCopy(srcPath, dstPath) == 0) result = FileRemove(srcPath);
else TRACELOG(LOG_WARNING, "FILEIO: [%s] Failed to copy file to [%s]", srcPath, dstPath);
}
else TRACELOG(LOG_WARNING, "FILEIO: [%s] Source file does not exist", srcPath);
return result;
}
int FileTextReplace(const char *fileName, const char *search, const char *replacement)
{
int result = 0;
char *fileText = NULL;
char *fileTextUpdated = { 0 };
#if SUPPORT_MODULE_RTEXT
if (FileExists(fileName))
{
fileText = LoadFileText(fileName);
fileTextUpdated = TextReplaceAlloc(fileText, search, replacement);
result = SaveFileText(fileName, fileTextUpdated);
MemFree(fileTextUpdated);
UnloadFileText(fileText);
}
#else
TRACELOG(LOG_WARNING, "FILE: File text replace requires [rtext] module");
#endif
return result;
}
int FileTextFindIndex(const char *fileName, const char *search)
{
int result = -1;
if (FileExists(fileName))
{
char *fileText = LoadFileText(fileName);
char *ptr = strstr(fileText, search);
if (ptr != NULL) result = (int)(ptr - fileText);
UnloadFileText(fileText);
}
return result;
}
bool FileExists(const char *fileName)
{
bool result = false;
if (ACCESS(fileName) != -1) result = true;
return result;
}
bool IsFileExtension(const char *fileName, const char *ext)
{
#define MAX_FILE_EXTENSIONS 32
bool result = false;
const char *fileExt = GetFileExtension(fileName);
if (fileExt != NULL)
{
int fileExtLength = (int)strlen(fileExt);
char fileExtLower[16] = { 0 };
char *fileExtLowerPtr = fileExtLower;
for (int i = 0; (i < fileExtLength) && (i < 16); i++)
{
if ((fileExt[i] >= 'A') && (fileExt[i] <= 'Z')) fileExtLower[i] = fileExt[i] + 32;
else fileExtLower[i] = fileExt[i];
}
int extCount = 1;
int extLength = (int)strlen(ext);
char *extList = (char *)RL_CALLOC(extLength + 1, 1);
char *extListPtrs[MAX_FILE_EXTENSIONS] = { 0 };
strncpy(extList, ext, extLength);
extListPtrs[0] = extList;
for (int i = 0; i < extLength; i++)
{
if ((extList[i] >= 'A') && (extList[i] <= 'Z')) extList[i] += 32;
if ((extList[i] == ';') && (extCount < (MAX_FILE_EXTENSIONS - 1)))
{
extList[i] = '\0';
extListPtrs[extCount] = extList + i + 1;
extCount++;
}
}
for (int i = 0; i < extCount; i++)
{
fileExtLowerPtr = fileExtLower;
if (extListPtrs[i][0] != '.') fileExtLowerPtr++;
if (strcmp(fileExtLowerPtr, extListPtrs[i]) == 0)
{
result = true;
break;
}
}
RL_FREE(extList);
}
return result;
}
bool DirectoryExists(const char *dirPath)
{
bool result = false;
DIR *dir = opendir(dirPath);
if (dir != NULL)
{
result = true;
closedir(dir);
}
return result;
}
int GetFileLength(const char *fileName)
{
int size = 0;
FILE *file = fopen(fileName, "rb");
if (file != NULL)
{
fseek(file, 0L, SEEK_END);
long int fileSize = ftell(file);
if (fileSize > 2147483647) TRACELOG(LOG_WARNING, "[%s] File size overflows expected limit, do not use GetFileLength()", fileName);
else size = (int)fileSize;
fclose(file);
}
return size;
}
long GetFileModTime(const char *fileName)
{
struct stat result = { 0 };
long modTime = 0;
if (stat(fileName, &result) == 0)
{
time_t mod = result.st_mtime;
modTime = (long)mod;
}
return modTime;
}
const char *GetFileExtension(const char *fileName)
{
const char *dot = strrchr(fileName, '.');
if (!dot || (dot == fileName)) return NULL;
return dot;
}
static const char *strprbrk(const char *text, const char *charset)
{
const char *latestMatch = NULL;
for (; (text != NULL) && (text = strpbrk(text, charset)); latestMatch = text++) { }
return latestMatch;
}
const char *GetFileName(const char *filePath)
{
const char *fileName = NULL;
if (filePath != NULL) fileName = strprbrk(filePath, "\\/");
if (fileName == NULL) return filePath;
return fileName + 1;
}
const char *GetFileNameWithoutExt(const char *filePath)
{
#define MAX_FILENAME_LENGTH 256
static char fileName[MAX_FILENAME_LENGTH] = { 0 };
memset(fileName, 0, MAX_FILENAME_LENGTH);
if (filePath != NULL)
{
strncpy(fileName, GetFileName(filePath), MAX_FILENAME_LENGTH - 1); int fileNameLength = (int)strlen(fileName);
for (int i = fileNameLength; i > 0; i--) {
if (fileName[i] == '.')
{
fileName[i] = '\0';
break;
}
}
}
return fileName;
}
const char *GetDirectoryPath(const char *filePath)
{
const char *lastSlash = NULL;
static char dirPath[MAX_FILEPATH_LENGTH] = { 0 };
memset(dirPath, 0, MAX_FILEPATH_LENGTH);
if ((filePath[1] != ':') && (filePath[0] != '\\') && (filePath[0] != '/'))
{
dirPath[0] = '.';
dirPath[1] = '/';
}
lastSlash = strprbrk(filePath, "\\/");
if (lastSlash)
{
if (lastSlash == filePath)
{
dirPath[0] = filePath[0];
dirPath[1] = '\0';
}
else
{
char *dirPathPtr = dirPath;
if ((filePath[1] != ':') && (filePath[0] != '\\') && (filePath[0] != '/')) dirPathPtr += 2; memcpy(dirPathPtr, filePath, strlen(filePath) - (strlen(lastSlash) - 1));
dirPath[strlen(filePath) - strlen(lastSlash) + (((filePath[1] != ':') && (filePath[0] != '\\') && (filePath[0] != '/'))? 2 : 0)] = '\0'; }
}
return dirPath;
}
const char *GetPrevDirectoryPath(const char *dirPath)
{
static char prevDirPath[MAX_FILEPATH_LENGTH] = { 0 };
memset(prevDirPath, 0, MAX_FILEPATH_LENGTH);
int dirPathLength = (int)strlen(dirPath);
if (dirPathLength <= 3) strncpy(prevDirPath, dirPath, MAX_FILEPATH_LENGTH - 1);
for (int i = (dirPathLength - 1); (i >= 0) && (dirPathLength > 3); i--)
{
if ((dirPath[i] == '\\') || (dirPath[i] == '/'))
{
if (((i == 2) && (dirPath[1] ==':')) || (i == 0)) i++;
strncpy(prevDirPath, dirPath, i);
break;
}
}
return prevDirPath;
}
const char *GetWorkingDirectory(void)
{
static char currentDir[MAX_FILEPATH_LENGTH] = { 0 };
memset(currentDir, 0, MAX_FILEPATH_LENGTH);
char *path = GETCWD(currentDir, MAX_FILEPATH_LENGTH - 1);
return path;
}
const char *GetApplicationDirectory(void)
{
static char appDir[MAX_FILEPATH_LENGTH] = { 0 };
memset(appDir, 0, MAX_FILEPATH_LENGTH);
#if defined(_WIN32)
int len = 0;
#if defined(UNICODE)
unsigned short widePath[MAX_PATH];
len = GetModuleFileNameW(NULL, (wchar_t *)widePath, MAX_PATH);
len = WideCharToMultiByte(0, 0, (wchar_t *)widePath, len, appDir, MAX_PATH, NULL, NULL);
#else
len = GetModuleFileNameA(NULL, appDir, MAX_PATH);
#endif
if (len > 0)
{
for (int i = len; i >= 0; i--)
{
if (appDir[i] == '\\')
{
appDir[i + 1] = '\0';
break;
}
}
}
else
{
appDir[0] = '.';
appDir[1] = '\\';
}
#elif defined(__linux__)
unsigned int size = sizeof(appDir);
ssize_t len = readlink("/proc/self/exe", appDir, size);
if (len > 0)
{
for (int i = len; i >= 0; i--)
{
if (appDir[i] == '/')
{
appDir[i + 1] = '\0';
break;
}
}
}
else
{
appDir[0] = '.';
appDir[1] = '/';
}
#elif defined(__APPLE__)
uint32_t size = sizeof(appDir);
if (_NSGetExecutablePath(appDir, &size) == 0)
{
int appDirLength = (int)strlen(appDir);
for (int i = appDirLength; i >= 0; i--)
{
if (appDir[i] == '/')
{
appDir[i + 1] = '\0';
break;
}
}
}
else
{
appDir[0] = '.';
appDir[1] = '/';
}
#elif defined(__FreeBSD__)
size_t size = sizeof(appDir);
int mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_PATHNAME, -1};
if (sysctl(mib, 4, appDir, &size, NULL, 0) == 0)
{
int appDirLength = (int)strlen(appDir);
for (int i = appDirLength; i >= 0; i--)
{
if (appDir[i] == '/')
{
appDir[i + 1] = '\0';
break;
}
}
}
else
{
appDir[0] = '.';
appDir[1] = '/';
}
#elif defined(__wasm__)
appDir[0] = '/';
#endif
return appDir;
}
FilePathList LoadDirectoryFiles(const char *dirPath)
{
return LoadDirectoryFilesEx(dirPath, FILE_FILTER_TAG_ALL, false);
}
FilePathList LoadDirectoryFilesEx(const char *basePath, const char *filter, bool scanSubdirs)
{
FilePathList files = { 0 };
if (DirectoryExists(basePath)) {
if ((filter != NULL) && (filter[0] == '\0')) filter = NULL;
unsigned int fileCounter = GetDirectoryFileCountEx(basePath, filter, scanSubdirs);
files.paths = (char **)RL_CALLOC(fileCounter, sizeof(char *));
for (unsigned int i = 0; i < fileCounter; i++) files.paths[i] = (char *)RL_CALLOC(MAX_FILEPATH_LENGTH, sizeof(char));
ScanDirectoryFiles(basePath, &files, filter, fileCounter, scanSubdirs);
if (files.count != fileCounter)
{
TRACELOG(LOG_WARNING, "FILEIO: Read files count (%u) does not match capacity allocated (%u)", files.count, fileCounter);
files.count = fileCounter; }
}
else TRACELOG(LOG_WARNING, "FILEIO: Directory cannot be opened (%s)", basePath);
return files;
}
void UnloadDirectoryFiles(FilePathList files)
{
if (files.paths != NULL)
{
for (unsigned int i = 0; i < files.count; i++) RL_FREE(files.paths[i]);
RL_FREE(files.paths);
}
}
int MakeDirectory(const char *dirPath)
{
if ((dirPath == NULL) || (dirPath[0] == '\0')) return -1; if (DirectoryExists(dirPath)) return 0;
int dirPathLength = (int)strlen(dirPath) + 1;
char *pathcpy = (char *)RL_CALLOC(dirPathLength, 1);
memcpy(pathcpy, dirPath, dirPathLength);
for (int i = 0; (i < dirPathLength) && (pathcpy[i] != '\0'); i++)
{
if (pathcpy[i] == ':') i++;
else
{
if ((pathcpy[i] == '\\') || (pathcpy[i] == '/'))
{
pathcpy[i] = '\0';
if (!DirectoryExists(pathcpy)) MKDIR(pathcpy);
pathcpy[i] = '/';
}
}
}
if (!DirectoryExists(pathcpy)) MKDIR(pathcpy);
RL_FREE(pathcpy);
if (!DirectoryExists(dirPath)) return -1;
return 0;
}
bool ChangeDirectory(const char *dirPath)
{
bool result = CHDIR(dirPath);
if (result != 0) TRACELOG(LOG_WARNING, "SYSTEM: Failed to change to directory: %s", dirPath);
else TRACELOG(LOG_INFO, "SYSTEM: Working Directory: %s", dirPath);
return (result == 0);
}
bool IsPathFile(const char *path)
{
struct stat result = { 0 };
stat(path, &result);
return S_ISREG(result.st_mode);
}
bool IsFileNameValid(const char *fileName)
{
bool valid = true;
if ((fileName != NULL) && (fileName[0] != '\0'))
{
int fileNameLength = (int)strlen(fileName);
bool allPeriods = true;
for (int i = 0; i < fileNameLength; i++)
{
if ((fileName[i] == '<') ||
(fileName[i] == '>') ||
(fileName[i] == ':') ||
(fileName[i] == '\"') ||
(fileName[i] == '/') ||
(fileName[i] == '\\') ||
(fileName[i] == '|') ||
(fileName[i] == '?') ||
(fileName[i] == '*')) { valid = false; break; }
if ((unsigned char)fileName[i] < 32) { valid = false; break; }
if (fileName[i] != '.') allPeriods = false;
}
if (allPeriods) valid = false;
}
return valid;
}
bool IsFileDropped(void)
{
bool result = false;
if (CORE.Window.dropFileCount > 0) result = true;
return result;
}
FilePathList LoadDroppedFiles(void)
{
FilePathList files = { 0 };
files.count = CORE.Window.dropFileCount;
files.paths = CORE.Window.dropFilepaths;
return files;
}
void UnloadDroppedFiles(FilePathList files)
{
if (files.count > 0)
{
for (unsigned int i = 0; i < files.count; i++) RL_FREE(files.paths[i]);
RL_FREE(files.paths);
CORE.Window.dropFileCount = 0;
CORE.Window.dropFilepaths = NULL;
}
}
unsigned int GetDirectoryFileCount(const char *dirPath)
{
return GetDirectoryFileCountEx(dirPath, FILE_FILTER_TAG_ALL, false);
}
unsigned int GetDirectoryFileCountEx(const char *basePath, const char *filter, bool scanSubdirs)
{
unsigned int fileCounter = 0;
char path[MAX_FILEPATH_LENGTH] = { 0 };
memset(path, 0, MAX_FILEPATH_LENGTH);
struct dirent *entity;
DIR *dir = opendir(basePath);
if (dir != NULL) {
while ((entity = readdir(dir)) != NULL)
{
if ((strcmp(entity->d_name, ".") != 0) && (strcmp(entity->d_name, "..") != 0))
{
#if defined(_WIN32)
int pathLength = snprintf(path, MAX_FILEPATH_LENGTH - 1, "%s\\%s", basePath, entity->d_name);
#else
int pathLength = snprintf(path, MAX_FILEPATH_LENGTH - 1, "%s/%s", basePath, entity->d_name);
#endif
if ((pathLength < 0) || (pathLength >= MAX_FILEPATH_LENGTH))
{
TRACELOG(LOG_WARNING, "FILEIO: Path longer than %d characters (%s...)", MAX_FILEPATH_LENGTH, basePath);
}
else if (IsPathFile(path))
{
if ((filter == NULL) || (strstr(filter, FILE_FILTER_TAG_ALL) != NULL) ||
(strstr(filter, FILE_FILTER_TAG_FILE_ONLY) != NULL) || IsFileExtension(path, filter)) fileCounter++;
}
else
{
if ((filter != NULL) && ((strstr(filter, FILE_FILTER_TAG_ALL) != NULL) || (strstr(filter, FILE_FILTER_TAG_DIR_ONLY) != NULL))) fileCounter++;
if (scanSubdirs) fileCounter += GetDirectoryFileCountEx(path, filter, scanSubdirs);
}
}
}
closedir(dir);
}
else TRACELOG(LOG_WARNING, "FILEIO: Directory cannot be opened (%s)", basePath); return fileCounter;
}
unsigned char *CompressData(const unsigned char *data, int dataSize, int *compDataSize)
{
#define COMPRESSION_QUALITY_DEFLATE 8
unsigned char *compData = NULL;
#if SUPPORT_COMPRESSION_API
struct sdefl *sdefl = (struct sdefl *)RL_CALLOC(1, sizeof(struct sdefl)); int bounds = sdefl_bound(dataSize);
compData = (unsigned char *)RL_CALLOC(bounds, 1);
*compDataSize = sdeflate(sdefl, compData, data, dataSize, COMPRESSION_QUALITY_DEFLATE); RL_FREE(sdefl);
TRACELOG(LOG_INFO, "SYSTEM: Compress data: Original size: %i -> Comp. size: %i", dataSize, *compDataSize);
#endif
return compData;
}
unsigned char *DecompressData(const unsigned char *compData, int compDataSize, int *dataSize)
{
unsigned char *data = NULL;
#if SUPPORT_COMPRESSION_API
unsigned char *data0 = (unsigned char *)RL_CALLOC(MAX_DECOMPRESSION_SIZE*1024*1024, 1);
int size = sinflate(data0, MAX_DECOMPRESSION_SIZE*1024*1024, compData, compDataSize);
data = (unsigned char *)RL_CALLOC(size, 1);
memcpy(data, data0, size);
memset(data0, 0, MAX_DECOMPRESSION_SIZE*1024*1024); RL_FREE(data0);
TRACELOG(LOG_INFO, "SYSTEM: Decompress data: Comp. size: %i -> Original size: %i", compDataSize, size);
*dataSize = size;
#endif
return data;
}
char *EncodeDataBase64(const unsigned char *data, int dataSize, int *outputSize)
{
static const char base64EncodeTable[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
int paddedSize = dataSize;
while (paddedSize%3 != 0) paddedSize++; int estimatedOutputSize = 4*(paddedSize/3);
int padding = paddedSize - dataSize;
estimatedOutputSize += 1;
char *encodedData = (char *)RL_CALLOC(estimatedOutputSize, 1);
if (encodedData == NULL) return NULL;
int outputCount = 0;
for (int i = 0; i < dataSize;)
{
unsigned int octetA = 0;
unsigned int octetB = 0;
unsigned int octetC = 0;
unsigned int octetPack = 0;
octetA = data[i]; octetB = ((i + 1) < dataSize)? data[i + 1] : 0; octetC = ((i + 2) < dataSize)? data[i + 2] : 0;
octetPack = (octetA << 16) | (octetB << 8) | octetC;
encodedData[outputCount + 0] = (unsigned char)(base64EncodeTable[(octetPack >> 18) & 0x3f]);
encodedData[outputCount + 1] = (unsigned char)(base64EncodeTable[(octetPack >> 12) & 0x3f]);
encodedData[outputCount + 2] = (unsigned char)(base64EncodeTable[(octetPack >> 6) & 0x3f]);
encodedData[outputCount + 3] = (unsigned char)(base64EncodeTable[octetPack & 0x3f]);
outputCount += 4;
i += 3;
}
for (int p = 0; p < padding; p++) encodedData[outputCount - p - 1] = '=';
encodedData[outputCount] = '\0';
outputCount++;
if (outputCount != estimatedOutputSize) TRACELOG(LOG_WARNING, "BASE64: Output size differs from estimation");
*outputSize = estimatedOutputSize;
return encodedData;
}
unsigned char *DecodeDataBase64(const char *text, int *outputSize)
{
static const unsigned char base64DecodeTable[256] = {
['A'] = 0, ['B'] = 1, ['C'] = 2, ['D'] = 3, ['E'] = 4, ['F'] = 5, ['G'] = 6, ['H'] = 7,
['I'] = 8, ['J'] = 9, ['K'] = 10, ['L'] = 11, ['M'] = 12, ['N'] = 13, ['O'] = 14, ['P'] = 15,
['Q'] = 16, ['R'] = 17, ['S'] = 18, ['T'] = 19, ['U'] = 20, ['V'] = 21, ['W'] = 22, ['X'] = 23, ['Y'] = 24, ['Z'] = 25,
['a'] = 26, ['b'] = 27, ['c'] = 28, ['d'] = 29, ['e'] = 30, ['f'] = 31, ['g'] = 32, ['h'] = 33,
['i'] = 34, ['j'] = 35, ['k'] = 36, ['l'] = 37, ['m'] = 38, ['n'] = 39, ['o'] = 40, ['p'] = 41,
['q'] = 42, ['r'] = 43, ['s'] = 44, ['t'] = 45, ['u'] = 46, ['v'] = 47, ['w'] = 48, ['x'] = 49, ['y'] = 50, ['z'] = 51,
['0'] = 52, ['1'] = 53, ['2'] = 54, ['3'] = 55, ['4'] = 56, ['5'] = 57, ['6'] = 58, ['7'] = 59,
['8'] = 60, ['9'] = 61, ['+'] = 62, ['/'] = 63
};
*outputSize = 0;
if (text == NULL) return NULL;
int dataSize = (int)strlen(text); int ending = dataSize - 1;
int padding = 0;
while (text[ending] == '=') { padding++; ending--; }
int estimatedOutputSize = 3*(dataSize/4) - padding;
int maxOutputSize = 3*(dataSize/4);
unsigned char *decodedData = (unsigned char *)RL_CALLOC(maxOutputSize, 1);
if (decodedData == NULL) return NULL;
int outputCount = 0;
for (int i = 0; i < dataSize;)
{
if ((i + 2) >= dataSize)
{
TRACELOG(LOG_WARNING, "BASE64: Decoding error: Input data size is not valid");
break;
}
unsigned int sixtetA = base64DecodeTable[(unsigned char)text[i]];
unsigned int sixtetB = base64DecodeTable[(unsigned char)text[i + 1]];
unsigned int sixtetC = (((i + 2) < dataSize) && (unsigned char)text[i + 2] != '=')? base64DecodeTable[(unsigned char)text[i + 2]] : 0;
unsigned int sixtetD = (((i + 3) < dataSize) && (unsigned char)text[i + 3] != '=')? base64DecodeTable[(unsigned char)text[i + 3]] : 0;
unsigned int octetPack = (sixtetA << 18) | (sixtetB << 12) | (sixtetC << 6) | sixtetD;
if ((outputCount + 3) > maxOutputSize)
{
TRACELOG(LOG_WARNING, "BASE64: Decoding error: Output data size is too small");
break;
}
decodedData[outputCount + 0] = (octetPack >> 16) & 0xff;
decodedData[outputCount + 1] = (octetPack >> 8) & 0xff;
decodedData[outputCount + 2] = octetPack & 0xff;
outputCount += 3;
i += 4;
}
if (estimatedOutputSize != (outputCount - padding)) TRACELOG(LOG_WARNING, "BASE64: Decoded size differs from estimation");
*outputSize = estimatedOutputSize;
return decodedData;
}
unsigned int ComputeCRC32(unsigned char *data, int dataSize)
{
static unsigned int crcTable[256] = {
0x00000000, 0x77073096, 0xee0e612c, 0x990951ba, 0x076dc419, 0x706af48f, 0xe963a535, 0x9e6495a3,
0x0edb8832, 0x79dcb8a4, 0xe0d5e91e, 0x97d2d988, 0x09b64c2b, 0x7eb17cbd, 0xe7b82d07, 0x90bf1d91,
0x1db71064, 0x6ab020f2, 0xf3b97148, 0x84be41de, 0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7,
0x136c9856, 0x646ba8c0, 0xfd62f97a, 0x8a65c9ec, 0x14015c4f, 0x63066cd9, 0xfa0f3d63, 0x8d080df5,
0x3b6e20c8, 0x4c69105e, 0xd56041e4, 0xa2677172, 0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b,
0x35b5a8fa, 0x42b2986c, 0xdbbbc9d6, 0xacbcf940, 0x32d86ce3, 0x45df5c75, 0xdcd60dcf, 0xabd13d59,
0x26d930ac, 0x51de003a, 0xc8d75180, 0xbfd06116, 0x21b4f4b5, 0x56b3c423, 0xcfba9599, 0xb8bda50f,
0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924, 0x2f6f7c87, 0x58684c11, 0xc1611dab, 0xb6662d3d,
0x76dc4190, 0x01db7106, 0x98d220bc, 0xefd5102a, 0x71b18589, 0x06b6b51f, 0x9fbfe4a5, 0xe8b8d433,
0x7807c9a2, 0x0f00f934, 0x9609a88e, 0xe10e9818, 0x7f6a0dbb, 0x086d3d2d, 0x91646c97, 0xe6635c01,
0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e, 0x6c0695ed, 0x1b01a57b, 0x8208f4c1, 0xf50fc457,
0x65b0d9c6, 0x12b7e950, 0x8bbeb8ea, 0xfcb9887c, 0x62dd1ddf, 0x15da2d49, 0x8cd37cf3, 0xfbd44c65,
0x4db26158, 0x3ab551ce, 0xa3bc0074, 0xd4bb30e2, 0x4adfa541, 0x3dd895d7, 0xa4d1c46d, 0xd3d6f4fb,
0x4369e96a, 0x346ed9fc, 0xad678846, 0xda60b8d0, 0x44042d73, 0x33031de5, 0xaa0a4c5f, 0xdd0d7cc9,
0x5005713c, 0x270241aa, 0xbe0b1010, 0xc90c2086, 0x5768b525, 0x206f85b3, 0xb966d409, 0xce61e49f,
0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4, 0x59b33d17, 0x2eb40d81, 0xb7bd5c3b, 0xc0ba6cad,
0xedb88320, 0x9abfb3b6, 0x03b6e20c, 0x74b1d29a, 0xead54739, 0x9dd277af, 0x04db2615, 0x73dc1683,
0xe3630b12, 0x94643b84, 0x0d6d6a3e, 0x7a6a5aa8, 0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1,
0xf00f9344, 0x8708a3d2, 0x1e01f268, 0x6906c2fe, 0xf762575d, 0x806567cb, 0x196c3671, 0x6e6b06e7,
0xfed41b76, 0x89d32be0, 0x10da7a5a, 0x67dd4acc, 0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5,
0xd6d6a3e8, 0xa1d1937e, 0x38d8c2c4, 0x4fdff252, 0xd1bb67f1, 0xa6bc5767, 0x3fb506dd, 0x48b2364b,
0xd80d2bda, 0xaf0a1b4c, 0x36034af6, 0x41047a60, 0xdf60efc3, 0xa867df55, 0x316e8eef, 0x4669be79,
0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236, 0xcc0c7795, 0xbb0b4703, 0x220216b9, 0x5505262f,
0xc5ba3bbe, 0xb2bd0b28, 0x2bb45a92, 0x5cb36a04, 0xc2d7ffa7, 0xb5d0cf31, 0x2cd99e8b, 0x5bdeae1d,
0x9b64c2b0, 0xec63f226, 0x756aa39c, 0x026d930a, 0x9c0906a9, 0xeb0e363f, 0x72076785, 0x05005713,
0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0x0cb61b38, 0x92d28e9b, 0xe5d5be0d, 0x7cdcefb7, 0x0bdbdf21,
0x86d3d2d4, 0xf1d4e242, 0x68ddb3f8, 0x1fda836e, 0x81be16cd, 0xf6b9265b, 0x6fb077e1, 0x18b74777,
0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c, 0x8f659eff, 0xf862ae69, 0x616bffd3, 0x166ccf45,
0xa00ae278, 0xd70dd2ee, 0x4e048354, 0x3903b3c2, 0xa7672661, 0xd06016f7, 0x4969474d, 0x3e6e77db,
0xaed16a4a, 0xd9d65adc, 0x40df0b66, 0x37d83bf0, 0xa9bcae53, 0xdebb9ec5, 0x47b2cf7f, 0x30b5ffe9,
0xbdbdf21c, 0xcabac28a, 0x53b39330, 0x24b4a3a6, 0xbad03605, 0xcdd70693, 0x54de5729, 0x23d967bf,
0xb3667a2e, 0xc4614ab8, 0x5d681b02, 0x2a6f2b94, 0xb40bbe37, 0xc30c8ea1, 0x5a05df1b, 0x2d02ef8d
};
unsigned int crc = ~0u;
for (int i = 0; i < dataSize; i++) crc = (crc >> 8) ^ crcTable[data[i] ^ (crc & 0xff)];
return ~crc;
}
unsigned int *ComputeMD5(unsigned char *data, int dataSize)
{
#define ROTATE_LEFT(x, c) (((x) << (c)) | ((x) >> (32 - (c))))
static unsigned int hash[4] = { 0 };
unsigned int r[] = {
7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22,
5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20,
4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23,
6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21
};
unsigned int k[] = {
0xd76aa478, 0xe8c7b756, 0x242070db, 0xc1bdceee,
0xf57c0faf, 0x4787c62a, 0xa8304613, 0xfd469501,
0x698098d8, 0x8b44f7af, 0xffff5bb1, 0x895cd7be,
0x6b901122, 0xfd987193, 0xa679438e, 0x49b40821,
0xf61e2562, 0xc040b340, 0x265e5a51, 0xe9b6c7aa,
0xd62f105d, 0x02441453, 0xd8a1e681, 0xe7d3fbc8,
0x21e1cde6, 0xc33707d6, 0xf4d50d87, 0x455a14ed,
0xa9e3e905, 0xfcefa3f8, 0x676f02d9, 0x8d2a4c8a,
0xfffa3942, 0x8771f681, 0x6d9d6122, 0xfde5380c,
0xa4beea44, 0x4bdecfa9, 0xf6bb4b60, 0xbebfbc70,
0x289b7ec6, 0xeaa127fa, 0xd4ef3085, 0x04881d05,
0xd9d4d039, 0xe6db99e5, 0x1fa27cf8, 0xc4ac5665,
0xf4292244, 0x432aff97, 0xab9423a7, 0xfc93a039,
0x655b59c3, 0x8f0ccc92, 0xffeff47d, 0x85845dd1,
0x6fa87e4f, 0xfe2ce6e0, 0xa3014314, 0x4e0811a1,
0xf7537e82, 0xbd3af235, 0x2ad7d2bb, 0xeb86d391
};
hash[0] = 0x67452301;
hash[1] = 0xefcdab89;
hash[2] = 0x98badcfe;
hash[3] = 0x10325476;
int newDataSize = ((((dataSize + 8)/64) + 1)*64) - 8;
unsigned char *msg = (unsigned char *)RL_CALLOC(newDataSize + 64, 1); memcpy(msg, data, dataSize);
msg[dataSize] = 128;
unsigned int bitsLen = 8*dataSize;
memcpy(msg + newDataSize, &bitsLen, 4);
for (int offset = 0; offset < newDataSize; offset += (512/8))
{
unsigned int *w = (unsigned int *)(msg + offset);
unsigned int a = hash[0];
unsigned int b = hash[1];
unsigned int c = hash[2];
unsigned int d = hash[3];
for (int i = 0; i < 64; i++)
{
unsigned int f = 0;
unsigned int g = 0;
if (i < 16)
{
f = (b & c) | ((~b) & d);
g = i;
}
else if (i < 32)
{
f = (d & b) | ((~d) & c);
g = (5*i + 1)%16;
}
else if (i < 48)
{
f = b ^ c ^ d;
g = (3*i + 5)%16;
}
else
{
f = c ^ (b | (~d));
g = (7*i)%16;
}
unsigned int temp = d;
d = c;
c = b;
b = b + ROTATE_LEFT((a + f + k[i] + w[g]), r[i]);
a = temp;
}
hash[0] += a;
hash[1] += b;
hash[2] += c;
hash[3] += d;
}
RL_FREE(msg);
return hash;
}
unsigned int *ComputeSHA1(unsigned char *data, int dataSize)
{
#define SHA1_ROTATE_LEFT(x, c) (((x) << (c)) | ((x) >> (32 - (c))))
static unsigned int hash[5] = { 0 };
hash[0] = 0x67452301;
hash[1] = 0xEFCDAB89;
hash[2] = 0x98BADCFE;
hash[3] = 0x10325476;
hash[4] = 0xC3D2E1F0;
int newDataSize = ((((dataSize + 8)/64) + 1)*64);
unsigned char *msg = (unsigned char *)RL_CALLOC(newDataSize, 1); memcpy(msg, data, dataSize);
msg[dataSize] = 128;
unsigned long long bitsLen = 8ULL * dataSize;
msg[newDataSize-1] = (unsigned char)(bitsLen);
msg[newDataSize-2] = (unsigned char)(bitsLen >> 8);
msg[newDataSize-3] = (unsigned char)(bitsLen >> 16);
msg[newDataSize-4] = (unsigned char)(bitsLen >> 24);
msg[newDataSize-5] = (unsigned char)(bitsLen >> 32);
msg[newDataSize-6] = (unsigned char)(bitsLen >> 40);
msg[newDataSize-7] = (unsigned char)(bitsLen >> 48);
msg[newDataSize-8] = (unsigned char)(bitsLen >> 56);
for (int offset = 0; offset < newDataSize; offset += (512/8))
{
unsigned int w[80] = { 0 };
for (int i = 0; i < 16; i++)
{
w[i] = (msg[offset + (i*4) + 0] << 24) |
(msg[offset + (i*4) + 1] << 16) |
(msg[offset + (i*4) + 2] << 8) |
(msg[offset + (i*4) + 3]);
}
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);
unsigned int a = hash[0];
unsigned int b = hash[1];
unsigned int c = hash[2];
unsigned int d = hash[3];
unsigned int e = hash[4];
for (int i = 0; i < 80; i++)
{
unsigned int f = 0;
unsigned int k = 0;
if (i < 20)
{
f = (b & c) | ((~b) & d);
k = 0x5A827999;
}
else if (i < 40)
{
f = b ^ c ^ d;
k = 0x6ED9EBA1;
}
else if (i < 60)
{
f = (b & c) | (b & d) | (c & d);
k = 0x8F1BBCDC;
}
else
{
f = b ^ c ^ d;
k = 0xCA62C1D6;
}
unsigned int temp = SHA1_ROTATE_LEFT(a, 5) + f + e + k + w[i];
e = d;
d = c;
c = SHA1_ROTATE_LEFT(b, 30);
b = a;
a = temp;
}
hash[0] += a;
hash[1] += b;
hash[2] += c;
hash[3] += d;
hash[4] += e;
}
RL_FREE(msg);
return hash;
}
unsigned int *ComputeSHA256(unsigned char *data, int dataSize)
{
#define SHA256_ROTATE_RIGHT(x, c) ((x >> c) | (x << ((sizeof(unsigned int)*8) - c)))
#define SHA256_A0(x) (SHA256_ROTATE_RIGHT(x, 7) ^ SHA256_ROTATE_RIGHT(x, 18) ^ (x >> 3))
#define SHA256_A1(x) (SHA256_ROTATE_RIGHT(x, 17) ^ SHA256_ROTATE_RIGHT(x, 19) ^ (x >> 10))
static const unsigned int k[64] = {
0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5,
0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3,
0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc,
0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7,
0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13,
0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3,
0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5,
0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208,
0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2
};
static unsigned int hash[8] = { 0 };
hash[0] = 0x6A09e667;
hash[1] = 0xbb67ae85;
hash[2] = 0x3c6ef372;
hash[3] = 0xa54ff53a;
hash[4] = 0x510e527f;
hash[5] = 0x9b05688c;
hash[6] = 0x1f83d9ab;
hash[7] = 0x5be0cd19;
const unsigned long long int bitLen = ((unsigned long long int)dataSize)*8;
unsigned long long int paddedSize = dataSize + sizeof(dataSize);
paddedSize += (64 - (paddedSize%64));
unsigned char *buffer = (unsigned char *)RL_CALLOC(paddedSize, sizeof(unsigned char));
memcpy(buffer, data, dataSize);
buffer[dataSize] = 0x80;
for (int i = 1; i <= sizeof(bitLen); i++)
{
buffer[(paddedSize - sizeof(bitLen)) + (i - 1)] = (bitLen >> (8*(sizeof(bitLen) - i))) & 0xFF;
}
for (unsigned long long int blockN = 0; blockN < paddedSize/64; blockN++)
{
unsigned int a = hash[0];
unsigned int b = hash[1];
unsigned int c = hash[2];
unsigned int d = hash[3];
unsigned int e = hash[4];
unsigned int f = hash[5];
unsigned int g = hash[6];
unsigned int h = hash[7];
unsigned char *block = buffer + (blockN*64);
unsigned int w[64] = { 0 };
for (int i = 0; i < 16; i++)
{
w[i] = ((unsigned int)block[i*4 + 0] << 24) |
((unsigned int)block[i*4 + 1] << 16) |
((unsigned int)block[i*4 + 2] << 8) |
((unsigned int)block[i*4 + 3]);
}
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];
for (unsigned long long int t = 0; t < 64; t++)
{
unsigned int e1 = (SHA256_ROTATE_RIGHT(e, 6) ^ SHA256_ROTATE_RIGHT(e, 11) ^ SHA256_ROTATE_RIGHT(e, 25));
unsigned int ch = ((e & f) ^ (~e & g));
unsigned int t1 = (h + e1 + ch + k[t] + w[t]);
unsigned int e0 = (SHA256_ROTATE_RIGHT(a, 2) ^ SHA256_ROTATE_RIGHT(a, 13) ^ SHA256_ROTATE_RIGHT(a, 22));
unsigned int maj = ((a & b) ^ (a & c) ^ (b & c));
unsigned int t2 = e0 + maj;
h = g;
g = f;
f = e;
e = d + t1;
d = c;
c = b;
b = a;
a = t1 + t2;
}
hash[0] += a;
hash[1] += b;
hash[2] += c;
hash[3] += d;
hash[4] += e;
hash[5] += f;
hash[6] += g;
hash[7] += h;
}
RL_FREE(buffer);
return hash;
}
AutomationEventList LoadAutomationEventList(const char *fileName)
{
AutomationEventList list = { 0 };
#if SUPPORT_AUTOMATION_EVENTS
list.events = (AutomationEvent *)RL_CALLOC(MAX_AUTOMATION_EVENTS, sizeof(AutomationEvent));
list.capacity = MAX_AUTOMATION_EVENTS;
if (fileName == NULL) TRACELOG(LOG_INFO, "AUTOMATION: New empty events list loaded successfully");
else
{
FILE *raeFile = fopen(fileName, "rt");
if (raeFile != NULL)
{
unsigned int counter = 0;
char buffer[256] = { 0 };
char eventDesc[64] = { 0 };
char *result = fgets(buffer, 256, raeFile);
if (result != buffer) TRACELOG(LOG_WARNING, "AUTOMATION: [%s] Issue reading line to buffer", fileName);
while (!feof(raeFile))
{
switch (buffer[0])
{
case 'c': sscanf(buffer, "c %i", &list.count); break;
case 'e':
{
sscanf(buffer, "e %d %d %d %d %d %d %[^\n]s", &list.events[counter].frame, &list.events[counter].type,
&list.events[counter].params[0], &list.events[counter].params[1], &list.events[counter].params[2], &list.events[counter].params[3], eventDesc);
counter++;
} break;
default: break;
}
result = fgets(buffer, 256, raeFile);
if (result != buffer) TRACELOG(LOG_WARNING, "AUTOMATION: [%s] Issue reading line to buffer", fileName);
}
if (counter != list.count)
{
TRACELOG(LOG_WARNING, "AUTOMATION: Events read from file [%i] do not mach event count specified [%i]", counter, list.count);
list.count = counter;
}
fclose(raeFile);
TRACELOG(LOG_INFO, "AUTOMATION: Events file loaded successfully");
}
TRACELOG(LOG_INFO, "AUTOMATION: Events loaded from file: %i", list.count);
}
#endif
return list;
}
void UnloadAutomationEventList(AutomationEventList list)
{
#if SUPPORT_AUTOMATION_EVENTS
RL_FREE(list.events);
#endif
}
bool ExportAutomationEventList(AutomationEventList list, const char *fileName)
{
bool result = false;
#if SUPPORT_AUTOMATION_EVENTS
char *txtData = (char *)RL_CALLOC(256*list.count + 2048, sizeof(char));
int byteCount = 0;
byteCount += sprintf(txtData + byteCount, "#\n");
byteCount += sprintf(txtData + byteCount, "# Automation events exporter v1.0 - raylib automation events list\n");
byteCount += sprintf(txtData + byteCount, "#\n");
byteCount += sprintf(txtData + byteCount, "# c <events_count>\n");
byteCount += sprintf(txtData + byteCount, "# e <frame> <event_type> <param0> <param1> <param2> <param3> // <event_type_name>\n");
byteCount += sprintf(txtData + byteCount, "#\n");
byteCount += sprintf(txtData + byteCount, "# more info and bugs-report: github.com/raysan5/raylib\n");
byteCount += sprintf(txtData + byteCount, "# feedback and support: ray[at]raylib.com\n");
byteCount += sprintf(txtData + byteCount, "#\n");
byteCount += sprintf(txtData + byteCount, "# Copyright (c) 2023-2026 Ramon Santamaria (@raysan5)\n");
byteCount += sprintf(txtData + byteCount, "#\n\n");
byteCount += sprintf(txtData + byteCount, "c %i\n", list.count);
for (unsigned int i = 0; i < list.count; i++)
{
byteCount += snprintf(txtData + byteCount, 256, "e %i %i %i %i %i %i // Event: %s\n", list.events[i].frame, list.events[i].type,
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]);
}
result = SaveFileText(fileName, txtData);
RL_FREE(txtData);
#endif
return result;
}
void SetAutomationEventList(AutomationEventList *list)
{
#if SUPPORT_AUTOMATION_EVENTS
currentEventList = list;
#endif
}
void SetAutomationEventBaseFrame(int frame)
{
CORE.Time.frameCounter = frame;
}
void StartAutomationEventRecording(void)
{
#if SUPPORT_AUTOMATION_EVENTS
automationEventRecording = true;
#endif
}
void StopAutomationEventRecording(void)
{
#if SUPPORT_AUTOMATION_EVENTS
automationEventRecording = false;
#endif
}
void PlayAutomationEvent(AutomationEvent event)
{
#if SUPPORT_AUTOMATION_EVENTS
if (!automationEventRecording)
{
switch (event.type)
{
case INPUT_KEY_UP: CORE.Input.Keyboard.currentKeyState[event.params[0]] = false; break; case INPUT_KEY_DOWN: { CORE.Input.Keyboard.currentKeyState[event.params[0]] = true;
if (CORE.Input.Keyboard.previousKeyState[event.params[0]] == false)
{
if (CORE.Input.Keyboard.keyPressedQueueCount < MAX_KEY_PRESSED_QUEUE)
{
CORE.Input.Keyboard.keyPressedQueue[CORE.Input.Keyboard.keyPressedQueueCount] = event.params[0];
CORE.Input.Keyboard.keyPressedQueueCount++;
}
}
} break;
case INPUT_MOUSE_BUTTON_UP: CORE.Input.Mouse.currentButtonState[event.params[0]] = false; break; case INPUT_MOUSE_BUTTON_DOWN: CORE.Input.Mouse.currentButtonState[event.params[0]] = true; break; case INPUT_MOUSE_POSITION: {
CORE.Input.Mouse.currentPosition.x = (float)event.params[0];
CORE.Input.Mouse.currentPosition.y = (float)event.params[1];
} break;
case INPUT_MOUSE_WHEEL_MOTION: {
CORE.Input.Mouse.currentWheelMove.x = (float)event.params[0];
CORE.Input.Mouse.currentWheelMove.y = (float)event.params[1];
} break;
case INPUT_TOUCH_UP: CORE.Input.Touch.currentTouchState[event.params[0]] = false; break; case INPUT_TOUCH_DOWN: CORE.Input.Touch.currentTouchState[event.params[0]] = true; break; case INPUT_TOUCH_POSITION: {
CORE.Input.Touch.position[event.params[0]].x = (float)event.params[1];
CORE.Input.Touch.position[event.params[0]].y = (float)event.params[2];
} break;
case INPUT_GAMEPAD_CONNECT: CORE.Input.Gamepad.ready[event.params[0]] = true; break; case INPUT_GAMEPAD_DISCONNECT: CORE.Input.Gamepad.ready[event.params[0]] = false; break; case INPUT_GAMEPAD_BUTTON_UP: CORE.Input.Gamepad.currentButtonState[event.params[0]][event.params[1]] = false; break; case INPUT_GAMEPAD_BUTTON_DOWN: CORE.Input.Gamepad.currentButtonState[event.params[0]][event.params[1]] = true; break; case INPUT_GAMEPAD_AXIS_MOTION: {
CORE.Input.Gamepad.axisState[event.params[0]][event.params[1]] = ((float)event.params[2]/32768.0f);
} break;
#if SUPPORT_GESTURES_SYSTEM
case INPUT_GESTURE: GESTURES.current = event.params[0]; break; #endif
case WINDOW_CLOSE: CORE.Window.shouldClose = true; break;
case WINDOW_MAXIMIZE: MaximizeWindow(); break;
case WINDOW_MINIMIZE: MinimizeWindow(); break;
case WINDOW_RESIZE: SetWindowSize(event.params[0], event.params[1]); break;
#if SUPPORT_SCREEN_CAPTURE
case ACTION_TAKE_SCREENSHOT:
{
TakeScreenshot(TextFormat("screenshot%03i.png", screenshotCounter));
screenshotCounter++;
} break;
#endif
case ACTION_SETTARGETFPS: SetTargetFPS(event.params[0]); break;
default: break;
}
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]);
}
#endif
}
bool IsKeyPressed(int key)
{
bool pressed = false;
if ((key > 0) && (key < MAX_KEYBOARD_KEYS))
{
if ((CORE.Input.Keyboard.previousKeyState[key] == 0) && (CORE.Input.Keyboard.currentKeyState[key] == 1)) pressed = true;
}
return pressed;
}
bool IsKeyPressedRepeat(int key)
{
bool repeat = false;
if ((key > 0) && (key < MAX_KEYBOARD_KEYS))
{
if (CORE.Input.Keyboard.keyRepeatInFrame[key] == 1) repeat = true;
}
return repeat;
}
bool IsKeyDown(int key)
{
bool down = false;
if ((key > 0) && (key < MAX_KEYBOARD_KEYS))
{
if (CORE.Input.Keyboard.currentKeyState[key] == 1) down = true;
}
return down;
}
bool IsKeyReleased(int key)
{
bool released = false;
if ((key > 0) && (key < MAX_KEYBOARD_KEYS))
{
if ((CORE.Input.Keyboard.previousKeyState[key] == 1) && (CORE.Input.Keyboard.currentKeyState[key] == 0)) released = true;
}
return released;
}
bool IsKeyUp(int key)
{
bool up = false;
if ((key > 0) && (key < MAX_KEYBOARD_KEYS))
{
if (CORE.Input.Keyboard.currentKeyState[key] == 0) up = true;
}
return up;
}
int GetKeyPressed(void)
{
int value = 0;
if (CORE.Input.Keyboard.keyPressedQueueCount > 0)
{
value = CORE.Input.Keyboard.keyPressedQueue[0];
for (int i = 0; i < (CORE.Input.Keyboard.keyPressedQueueCount - 1); i++)
CORE.Input.Keyboard.keyPressedQueue[i] = CORE.Input.Keyboard.keyPressedQueue[i + 1];
CORE.Input.Keyboard.keyPressedQueue[CORE.Input.Keyboard.keyPressedQueueCount - 1] = 0;
CORE.Input.Keyboard.keyPressedQueueCount--;
}
return value;
}
int GetCharPressed(void)
{
int value = 0;
if (CORE.Input.Keyboard.charPressedQueueCount > 0)
{
value = CORE.Input.Keyboard.charPressedQueue[0];
for (int i = 0; i < (CORE.Input.Keyboard.charPressedQueueCount - 1); i++)
CORE.Input.Keyboard.charPressedQueue[i] = CORE.Input.Keyboard.charPressedQueue[i + 1];
CORE.Input.Keyboard.charPressedQueue[CORE.Input.Keyboard.charPressedQueueCount - 1] = 0;
CORE.Input.Keyboard.charPressedQueueCount--;
}
return value;
}
void SetExitKey(int key)
{
CORE.Input.Keyboard.exitKey = key;
}
bool IsGamepadAvailable(int gamepad)
{
bool result = false;
if ((gamepad < MAX_GAMEPADS) && CORE.Input.Gamepad.ready[gamepad]) result = true;
return result;
}
const char *GetGamepadName(int gamepad)
{
return CORE.Input.Gamepad.name[gamepad];
}
bool IsGamepadButtonPressed(int gamepad, int button)
{
bool pressed = false;
if ((gamepad < MAX_GAMEPADS) && CORE.Input.Gamepad.ready[gamepad] && (button < MAX_GAMEPAD_BUTTONS))
{
if ((CORE.Input.Gamepad.previousButtonState[gamepad][button] == 0) && (CORE.Input.Gamepad.currentButtonState[gamepad][button] == 1)) pressed = true;
}
return pressed;
}
bool IsGamepadButtonDown(int gamepad, int button)
{
bool down = false;
if ((gamepad < MAX_GAMEPADS) && CORE.Input.Gamepad.ready[gamepad] && (button < MAX_GAMEPAD_BUTTONS))
{
if (CORE.Input.Gamepad.currentButtonState[gamepad][button] == 1) down = true;
}
return down;
}
bool IsGamepadButtonReleased(int gamepad, int button)
{
bool released = false;
if ((gamepad < MAX_GAMEPADS) && CORE.Input.Gamepad.ready[gamepad] && (button < MAX_GAMEPAD_BUTTONS))
{
if ((CORE.Input.Gamepad.previousButtonState[gamepad][button] == 1) && (CORE.Input.Gamepad.currentButtonState[gamepad][button] == 0)) released = true;
}
return released;
}
bool IsGamepadButtonUp(int gamepad, int button)
{
bool up = false;
if ((gamepad < MAX_GAMEPADS) && CORE.Input.Gamepad.ready[gamepad] && (button < MAX_GAMEPAD_BUTTONS))
{
if (CORE.Input.Gamepad.currentButtonState[gamepad][button] == 0) up = true;
}
return up;
}
int GetGamepadButtonPressed(void)
{
return CORE.Input.Gamepad.lastButtonPressed;
}
int GetGamepadAxisCount(int gamepad)
{
return CORE.Input.Gamepad.axisCount[gamepad];
}
float GetGamepadAxisMovement(int gamepad, int axis)
{
float value = ((axis == GAMEPAD_AXIS_LEFT_TRIGGER) || (axis == GAMEPAD_AXIS_RIGHT_TRIGGER))? -1.0f : 0.0f;
if ((gamepad < MAX_GAMEPADS) && CORE.Input.Gamepad.ready[gamepad] && (axis < MAX_GAMEPAD_AXES))
{
float movement = (value < 0.0f)? CORE.Input.Gamepad.axisState[gamepad][axis] : fabsf(CORE.Input.Gamepad.axisState[gamepad][axis]);
if (movement > value) value = CORE.Input.Gamepad.axisState[gamepad][axis];
}
return value;
}
bool IsMouseButtonPressed(int button)
{
bool pressed = false;
if ((button >= 0) && (button <= MOUSE_BUTTON_BACK))
{
if ((CORE.Input.Mouse.currentButtonState[button] == 1) && (CORE.Input.Mouse.previousButtonState[button] == 0)) pressed = true;
if ((CORE.Input.Touch.currentTouchState[button] == 1) && (CORE.Input.Touch.previousTouchState[button] == 0)) pressed = true;
}
return pressed;
}
bool IsMouseButtonDown(int button)
{
bool down = false;
if ((button >= 0) && (button <= MOUSE_BUTTON_BACK))
{
if (CORE.Input.Mouse.currentButtonState[button] == 1) down = true;
if (CORE.Input.Touch.currentTouchState[button] == 1) down = true;
}
return down;
}
bool IsMouseButtonReleased(int button)
{
bool released = false;
if ((button >= 0) && (button <= MOUSE_BUTTON_BACK))
{
if ((CORE.Input.Mouse.currentButtonState[button] == 0) && (CORE.Input.Mouse.previousButtonState[button] == 1)) released = true;
if ((CORE.Input.Touch.currentTouchState[button] == 0) && (CORE.Input.Touch.previousTouchState[button] == 1)) released = true;
}
return released;
}
bool IsMouseButtonUp(int button)
{
bool up = false;
if ((button >= 0) && (button <= MOUSE_BUTTON_BACK))
{
if (CORE.Input.Mouse.currentButtonState[button] == 0) up = true;
if (CORE.Input.Touch.currentTouchState[button] == 0) up = true;
}
return up;
}
int GetMouseX(void)
{
int mouseX = (int)((CORE.Input.Mouse.currentPosition.x + CORE.Input.Mouse.offset.x)*CORE.Input.Mouse.scale.x);
return mouseX;
}
int GetMouseY(void)
{
int mouseY = (int)((CORE.Input.Mouse.currentPosition.y + CORE.Input.Mouse.offset.y)*CORE.Input.Mouse.scale.y);
return mouseY;
}
Vector2 GetMousePosition(void)
{
Vector2 position = { 0 };
position.x = (CORE.Input.Mouse.currentPosition.x + CORE.Input.Mouse.offset.x)*CORE.Input.Mouse.scale.x;
position.y = (CORE.Input.Mouse.currentPosition.y + CORE.Input.Mouse.offset.y)*CORE.Input.Mouse.scale.y;
return position;
}
Vector2 GetMouseDelta(void)
{
Vector2 delta = { 0 };
delta.x = (CORE.Input.Mouse.currentPosition.x - CORE.Input.Mouse.previousPosition.x)*CORE.Input.Mouse.scale.x;
delta.y = (CORE.Input.Mouse.currentPosition.y - CORE.Input.Mouse.previousPosition.y)*CORE.Input.Mouse.scale.y;
return delta;
}
void SetMouseOffset(int offsetX, int offsetY)
{
CORE.Input.Mouse.offset = (Vector2){ (float)offsetX, (float)offsetY };
}
void SetMouseScale(float scaleX, float scaleY)
{
CORE.Input.Mouse.scale = (Vector2){ scaleX, scaleY };
}
float GetMouseWheelMove(void)
{
float result = 0.0f;
if (fabsf(CORE.Input.Mouse.currentWheelMove.x) > fabsf(CORE.Input.Mouse.currentWheelMove.y)) result = (float)CORE.Input.Mouse.currentWheelMove.x;
else result = (float)CORE.Input.Mouse.currentWheelMove.y;
return result;
}
Vector2 GetMouseWheelMoveV(void)
{
Vector2 result = { 0 };
result = CORE.Input.Mouse.currentWheelMove;
return result;
}
int GetTouchX(void)
{
int touchX = (int)CORE.Input.Touch.position[0].x;
return touchX;
}
int GetTouchY(void)
{
int touchY = (int)CORE.Input.Touch.position[0].y;
return touchY;
}
Vector2 GetTouchPosition(int index)
{
Vector2 position = { -1.0f, -1.0f };
if (index < MAX_TOUCH_POINTS) position = CORE.Input.Touch.position[index];
else TRACELOG(LOG_WARNING, "INPUT: Required touch point out of range (Max touch points: %i)", MAX_TOUCH_POINTS);
return position;
}
int GetTouchPointId(int index)
{
int id = -1;
if (index < MAX_TOUCH_POINTS) id = CORE.Input.Touch.pointId[index];
return id;
}
int GetTouchPointCount(void)
{
return CORE.Input.Touch.pointCount;
}
void InitTimer(void)
{
#if defined(_WIN32) && SUPPORT_WINMM_HIGHRES_TIMER && !SUPPORT_BUSY_WAIT_LOOP && !defined(PLATFORM_DESKTOP_SDL)
timeBeginPeriod(1); #endif
#if defined(__linux__) || defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__EMSCRIPTEN__)
struct timespec now = { 0 };
if (clock_gettime(CLOCK_MONOTONIC, &now) == 0) {
CORE.Time.base = (unsigned long long int)now.tv_sec*1000000000LLU + (unsigned long long int)now.tv_nsec;
}
else TRACELOG(LOG_WARNING, "TIMER: Hi-resolution timer not available");
#endif
CORE.Time.previous = GetTime(); }
void SetupViewport(int width, int height)
{
CORE.Window.render.width = width;
CORE.Window.render.height = height;
rlViewport(CORE.Window.renderOffset.x/2, CORE.Window.renderOffset.y/2, CORE.Window.render.width, CORE.Window.render.height);
rlMatrixMode(RL_PROJECTION); rlLoadIdentity();
rlOrtho(0, CORE.Window.render.width, CORE.Window.render.height, 0, 0.0f, 1.0f);
rlMatrixMode(RL_MODELVIEW); rlLoadIdentity(); }
static void ScanDirectoryFiles(const char *basePath, FilePathList *files, const char *filter, unsigned int expectedFileCount, bool scanSubdirs)
{
char path[MAX_FILEPATH_LENGTH] = { 0 };
memset(path, 0, MAX_FILEPATH_LENGTH);
struct dirent *dp = NULL;
DIR *dir = opendir(basePath);
if (dir != NULL)
{
while (((dp = readdir(dir)) != NULL) && (files->count < expectedFileCount))
{
if ((strcmp(dp->d_name, ".") != 0) && (strcmp(dp->d_name, "..") != 0))
{
#if defined(_WIN32)
int pathLength = snprintf(path, MAX_FILEPATH_LENGTH - 1, "%s\\%s", basePath, dp->d_name);
#else
int pathLength = snprintf(path, MAX_FILEPATH_LENGTH - 1, "%s/%s", basePath, dp->d_name);
#endif
if ((pathLength < 0) || (pathLength >= MAX_FILEPATH_LENGTH))
{
TRACELOG(LOG_WARNING, "FILEIO: Path longer than %d characters (%s...)", MAX_FILEPATH_LENGTH, basePath);
}
else if (IsPathFile(path))
{
if ((filter == NULL) || (strstr(filter, FILE_FILTER_TAG_ALL) != NULL) ||
(strstr(filter, FILE_FILTER_TAG_FILE_ONLY) != NULL) || IsFileExtension(path, filter))
{
strncpy(files->paths[files->count], path, MAX_FILEPATH_LENGTH - 1);
files->count++;
}
}
else
{
if ((filter != NULL) && ((strstr(filter, FILE_FILTER_TAG_DIR_ONLY) != NULL) || (strstr(filter, FILE_FILTER_TAG_ALL) != NULL)))
{
strncpy(files->paths[files->count], path, MAX_FILEPATH_LENGTH - 1);
files->count++;
}
if (scanSubdirs) ScanDirectoryFiles(path, files, filter, expectedFileCount, scanSubdirs);
}
}
}
closedir(dir);
}
else TRACELOG(LOG_WARNING, "FILEIO: Directory cannot be opened (%s)", basePath); }
#if SUPPORT_AUTOMATION_EVENTS
static void RecordAutomationEvent(void)
{
if (currentEventList->count == currentEventList->capacity) return;
for (int key = 0; key < MAX_KEYBOARD_KEYS; key++)
{
if (CORE.Input.Keyboard.previousKeyState[key] && !CORE.Input.Keyboard.currentKeyState[key])
{
currentEventList->events[currentEventList->count].frame = CORE.Time.frameCounter;
currentEventList->events[currentEventList->count].type = INPUT_KEY_UP;
currentEventList->events[currentEventList->count].params[0] = key;
currentEventList->events[currentEventList->count].params[1] = 0;
currentEventList->events[currentEventList->count].params[2] = 0;
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]);
currentEventList->count++;
}
if (currentEventList->count == currentEventList->capacity) return;
if (CORE.Input.Keyboard.currentKeyState[key])
{
currentEventList->events[currentEventList->count].frame = CORE.Time.frameCounter;
currentEventList->events[currentEventList->count].type = INPUT_KEY_DOWN;
currentEventList->events[currentEventList->count].params[0] = key;
currentEventList->events[currentEventList->count].params[1] = 0;
currentEventList->events[currentEventList->count].params[2] = 0;
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]);
currentEventList->count++;
}
if (currentEventList->count == currentEventList->capacity) return; }
for (int button = 0; button < MAX_MOUSE_BUTTONS; button++)
{
if (CORE.Input.Mouse.previousButtonState[button] && !CORE.Input.Mouse.currentButtonState[button])
{
currentEventList->events[currentEventList->count].frame = CORE.Time.frameCounter;
currentEventList->events[currentEventList->count].type = INPUT_MOUSE_BUTTON_UP;
currentEventList->events[currentEventList->count].params[0] = button;
currentEventList->events[currentEventList->count].params[1] = 0;
currentEventList->events[currentEventList->count].params[2] = 0;
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]);
currentEventList->count++;
}
if (currentEventList->count == currentEventList->capacity) return;
if (CORE.Input.Mouse.currentButtonState[button])
{
currentEventList->events[currentEventList->count].frame = CORE.Time.frameCounter;
currentEventList->events[currentEventList->count].type = INPUT_MOUSE_BUTTON_DOWN;
currentEventList->events[currentEventList->count].params[0] = button;
currentEventList->events[currentEventList->count].params[1] = 0;
currentEventList->events[currentEventList->count].params[2] = 0;
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]);
currentEventList->count++;
}
if (currentEventList->count == currentEventList->capacity) return; }
if (((int)CORE.Input.Mouse.currentPosition.x != (int)CORE.Input.Mouse.previousPosition.x) ||
((int)CORE.Input.Mouse.currentPosition.y != (int)CORE.Input.Mouse.previousPosition.y))
{
currentEventList->events[currentEventList->count].frame = CORE.Time.frameCounter;
currentEventList->events[currentEventList->count].type = INPUT_MOUSE_POSITION;
currentEventList->events[currentEventList->count].params[0] = (int)CORE.Input.Mouse.currentPosition.x;
currentEventList->events[currentEventList->count].params[1] = (int)CORE.Input.Mouse.currentPosition.y;
currentEventList->events[currentEventList->count].params[2] = 0;
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]);
currentEventList->count++;
if (currentEventList->count == currentEventList->capacity) return; }
if (((int)CORE.Input.Mouse.currentWheelMove.x != (int)CORE.Input.Mouse.previousWheelMove.x) ||
((int)CORE.Input.Mouse.currentWheelMove.y != (int)CORE.Input.Mouse.previousWheelMove.y))
{
currentEventList->events[currentEventList->count].frame = CORE.Time.frameCounter;
currentEventList->events[currentEventList->count].type = INPUT_MOUSE_WHEEL_MOTION;
currentEventList->events[currentEventList->count].params[0] = (int)CORE.Input.Mouse.currentWheelMove.x;
currentEventList->events[currentEventList->count].params[1] = (int)CORE.Input.Mouse.currentWheelMove.y;
currentEventList->events[currentEventList->count].params[2] = 0;
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]);
currentEventList->count++;
if (currentEventList->count == currentEventList->capacity) return; }
for (int id = 0; id < MAX_TOUCH_POINTS; id++)
{
if (CORE.Input.Touch.previousTouchState[id] && !CORE.Input.Touch.currentTouchState[id])
{
currentEventList->events[currentEventList->count].frame = CORE.Time.frameCounter;
currentEventList->events[currentEventList->count].type = INPUT_TOUCH_UP;
currentEventList->events[currentEventList->count].params[0] = id;
currentEventList->events[currentEventList->count].params[1] = 0;
currentEventList->events[currentEventList->count].params[2] = 0;
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]);
currentEventList->count++;
}
if (currentEventList->count == currentEventList->capacity) return;
if (CORE.Input.Touch.currentTouchState[id])
{
currentEventList->events[currentEventList->count].frame = CORE.Time.frameCounter;
currentEventList->events[currentEventList->count].type = INPUT_TOUCH_DOWN;
currentEventList->events[currentEventList->count].params[0] = id;
currentEventList->events[currentEventList->count].params[1] = 0;
currentEventList->events[currentEventList->count].params[2] = 0;
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]);
currentEventList->count++;
}
if (currentEventList->count == currentEventList->capacity) return;
if (((int)CORE.Input.Touch.position[id].x != (int)CORE.Input.Touch.previousPosition[id].x) ||
((int)CORE.Input.Touch.position[id].y != (int)CORE.Input.Touch.previousPosition[id].y))
{
currentEventList->events[currentEventList->count].frame = CORE.Time.frameCounter;
currentEventList->events[currentEventList->count].type = INPUT_TOUCH_POSITION;
currentEventList->events[currentEventList->count].params[0] = id;
currentEventList->events[currentEventList->count].params[1] = (int)CORE.Input.Touch.position[id].x;
currentEventList->events[currentEventList->count].params[2] = (int)CORE.Input.Touch.position[id].y;
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]);
currentEventList->count++;
}
if (currentEventList->count == currentEventList->capacity) return; }
for (int gamepad = 0; gamepad < MAX_GAMEPADS; gamepad++)
{
for (int button = 0; button < MAX_GAMEPAD_BUTTONS; button++)
{
if (CORE.Input.Gamepad.previousButtonState[gamepad][button] && !CORE.Input.Gamepad.currentButtonState[gamepad][button])
{
currentEventList->events[currentEventList->count].frame = CORE.Time.frameCounter;
currentEventList->events[currentEventList->count].type = INPUT_GAMEPAD_BUTTON_UP;
currentEventList->events[currentEventList->count].params[0] = gamepad;
currentEventList->events[currentEventList->count].params[1] = button;
currentEventList->events[currentEventList->count].params[2] = 0;
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]);
currentEventList->count++;
}
if (currentEventList->count == currentEventList->capacity) return;
if (CORE.Input.Gamepad.currentButtonState[gamepad][button])
{
currentEventList->events[currentEventList->count].frame = CORE.Time.frameCounter;
currentEventList->events[currentEventList->count].type = INPUT_GAMEPAD_BUTTON_DOWN;
currentEventList->events[currentEventList->count].params[0] = gamepad;
currentEventList->events[currentEventList->count].params[1] = button;
currentEventList->events[currentEventList->count].params[2] = 0;
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]);
currentEventList->count++;
}
if (currentEventList->count == currentEventList->capacity) return; }
for (int axis = 0; axis < MAX_GAMEPAD_AXES; axis++)
{
float defaultMovement = ((axis == GAMEPAD_AXIS_LEFT_TRIGGER) || (axis == GAMEPAD_AXIS_RIGHT_TRIGGER))? -1.0f : 0.0f;
if (GetGamepadAxisMovement(gamepad, axis) != defaultMovement)
{
currentEventList->events[currentEventList->count].frame = CORE.Time.frameCounter;
currentEventList->events[currentEventList->count].type = INPUT_GAMEPAD_AXIS_MOTION;
currentEventList->events[currentEventList->count].params[0] = gamepad;
currentEventList->events[currentEventList->count].params[1] = axis;
currentEventList->events[currentEventList->count].params[2] = (int)(CORE.Input.Gamepad.axisState[gamepad][axis]*32768.0f);
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]);
currentEventList->count++;
}
if (currentEventList->count == currentEventList->capacity) return; }
}
#if SUPPORT_GESTURES_SYSTEM
if (GESTURES.current != GESTURE_NONE)
{
currentEventList->events[currentEventList->count].frame = CORE.Time.frameCounter;
currentEventList->events[currentEventList->count].type = INPUT_GESTURE;
currentEventList->events[currentEventList->count].params[0] = GESTURES.current;
currentEventList->events[currentEventList->count].params[1] = 0;
currentEventList->events[currentEventList->count].params[2] = 0;
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]);
currentEventList->count++;
if (currentEventList->count == currentEventList->capacity) return; }
#endif
}
#endif
#if !SUPPORT_MODULE_RTEXT
const char *TextFormat(const char *text, ...)
{
#ifndef MAX_TEXTFORMAT_BUFFERS
#define MAX_TEXTFORMAT_BUFFERS 4
#endif
#ifndef MAX_TEXT_BUFFER_LENGTH
#define MAX_TEXT_BUFFER_LENGTH 1024
#endif
static char buffers[MAX_TEXTFORMAT_BUFFERS][MAX_TEXT_BUFFER_LENGTH] = { 0 };
static int index = 0;
char *currentBuffer = buffers[index];
memset(currentBuffer, 0, MAX_TEXT_BUFFER_LENGTH);
if (text != NULL)
{
va_list args;
va_start(args, text);
int requiredByteCount = vsnprintf(currentBuffer, MAX_TEXT_BUFFER_LENGTH, text, args);
va_end(args);
if (requiredByteCount >= MAX_TEXT_BUFFER_LENGTH)
{
char *truncBuffer = buffers[index] + MAX_TEXT_BUFFER_LENGTH - 4; snprintf(truncBuffer, 4, "...");
}
index += 1; if (index >= MAX_TEXTFORMAT_BUFFERS) index = 0;
}
return currentBuffer;
}
#endif