#if (defined(__linux__) || defined(PLATFORM_WEB)) && (_XOPEN_SOURCE < 500)
#undef _XOPEN_SOURCE
#define _XOPEN_SOURCE 500
#endif
#if (defined(__linux__) || defined(PLATFORM_WEB)) && (_POSIX_C_SOURCE < 199309L)
#undef _POSIX_C_SOURCE
#define _POSIX_C_SOURCE 199309L
#endif
#include "raylib.h"
#if !defined(EXTERNAL_CONFIG_FLAGS)
#include "config.h"
#endif
#include "utils.h"
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <time.h>
#include <math.h>
#define RLGL_IMPLEMENTATION
#include "rlgl.h"
#define RAYMATH_IMPLEMENTATION
#include "raymath.h"
#if defined(SUPPORT_GESTURES_SYSTEM)
#define RGESTURES_IMPLEMENTATION
#include "rgestures.h"
#endif
#if defined(SUPPORT_CAMERA_SYSTEM)
#define RCAMERA_IMPLEMENTATION
#include "rcamera.h"
#endif
#if defined(SUPPORT_GIF_RECORDING)
#define MSF_GIF_MALLOC(contextPointer, newSize) RL_MALLOC(newSize)
#define MSF_GIF_REALLOC(contextPointer, oldMemory, oldSize, newSize) RL_REALLOC(oldMemory, newSize)
#define MSF_GIF_FREE(contextPointer, oldMemory, oldSize) RL_FREE(oldMemory)
#define MSF_GIF_IMPL
#include "external/msf_gif.h"
#endif
#if defined(SUPPORT_COMPRESSION_API)
#define SINFL_IMPLEMENTATION
#define SINFL_NO_SIMD
#include "external/sinfl.h"
#define SDEFL_IMPLEMENTATION
#include "external/sdefl.h"
#endif
#if defined(SUPPORT_RPRAND_GENERATOR)
#define RPRAND_IMPLEMENTATION
#include "external/rprand.h"
#endif
#if defined(__linux__) && !defined(_GNU_SOURCE)
#define _GNU_SOURCE
#endif
#if (defined(_WIN32) && !defined(PLATFORM_DESKTOP_RGFW)) || (defined(_MSC_VER) && defined(PLATFORM_DESKTOP_RGFW))
#ifndef MAX_PATH
#define MAX_PATH 1025
#endif
__declspec(dllimport) unsigned long __stdcall GetModuleFileNameA(void *hModule, void *lpFilename, unsigned long nSize);
__declspec(dllimport) unsigned long __stdcall GetModuleFileNameW(void *hModule, void *lpFilename, unsigned long nSize);
__declspec(dllimport) int __stdcall WideCharToMultiByte(unsigned int cp, unsigned long flags, void *widestr, int cchwide, void *str, int cbmb, void *defchar, int *used_default);
__declspec(dllimport) unsigned int __stdcall timeBeginPeriod(unsigned int uPeriod);
__declspec(dllimport) unsigned int __stdcall timeEndPeriod(unsigned int uPeriod);
#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)
#else
#include <unistd.h>
#define GETCWD getcwd
#define CHDIR chdir
#define MKDIR(dir) mkdir(dir, 0777)
#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_AXIS
#define MAX_GAMEPAD_AXIS 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 DIRECTORY_FILTER_TAG
#define DIRECTORY_FILTER_TAG "DIR"
#endif
#define FLAG_SET(n, f) ((n) |= (f))
#define FLAG_CLEAR(n, f) ((n) &= ~(f))
#define FLAG_TOGGLE(n, f) ((n) ^= (f))
#define FLAG_CHECK(n, f) ((n) & (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 fullscreen; bool shouldClose; bool resizedLastFrame; bool eventWaiting; bool usingFbo;
Point position; Point previousPosition; Size display; Size screen; Size previousScreen; Size currentFbo; Size render; Point renderOffset; 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;
int cursor; bool cursorHidden; 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]; 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][64]; char currentButtonState[MAX_GAMEPADS][MAX_GAMEPAD_BUTTONS]; char previousButtonState[MAX_GAMEPADS][MAX_GAMEPAD_BUTTONS]; float axisState[MAX_GAMEPADS][MAX_GAMEPAD_AXIS];
} 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 };
bool isGpuReady = false;
#if defined(SUPPORT_SCREEN_CAPTURE)
static int screenshotCounter = 0; #endif
#if defined(SUPPORT_GIF_RECORDING)
static unsigned int gifFrameCounter = 0; static bool gifRecording = false; static MsfGifState gifState = { 0 }; #endif
#if defined(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 defined(SUPPORT_MODULE_RTEXT) && defined(SUPPORT_DEFAULT_FONT)
extern void LoadFontDefault(void); extern void UnloadFontDefault(void); #endif
extern int InitPlatform(void); extern void ClosePlatform(void);
static void InitTimer(void); static void SetupFramebuffer(int width, int height); static void SetupViewport(int width, int height);
static void ScanDirectoryFiles(const char *basePath, FilePathList *list, const char *filter); static void ScanDirectoryFilesRecursively(const char *basePath, FilePathList *list, const char *filter);
#if defined(SUPPORT_AUTOMATION_EVENTS)
static void RecordAutomationEvent(void); #endif
#if defined(_WIN32) && !defined(PLATFORM_DESKTOP_RGFW)
void __stdcall Sleep(unsigned long msTimeout); #endif
#if !defined(SUPPORT_MODULE_RTEXT)
const char *TextFormat(const char *text, ...); #endif
#if defined(PLATFORM_DESKTOP)
#define PLATFORM_DESKTOP_GLFW
#endif
#if defined(SUPPORT_CLIPBOARD_IMAGE)
#if !defined(SUPPORT_MODULE_RTEXTURES)
#pragma message ("Warning: Enabling SUPPORT_CLIPBOARD_IMAGE requires SUPPORT_MODULE_RTEXTURES to work properly")
#endif
#if !defined(SUPPORT_FILEFORMAT_BMP) && defined(_WIN32)
#pragma message ("Warning: Enabling SUPPORT_CLIPBOARD_IMAGE requires SUPPORT_FILEFORMAT_BMP, specially on Windows")
#endif
#if (!defined(SUPPORT_FILEFORMAT_PNG) || !defined(SUPPORT_FILEFORMAT_JPG)) && !defined(_WIN32)
#pragma message ("Warning: Getting image from the clipboard might not work without SUPPORT_FILEFORMAT_PNG or SUPPORT_FILEFORMAT_JPG")
#endif
#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)
#include "platforms/rcore_desktop_rgfw.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"
#else
#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_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");
#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 defined(SUPPORT_MODULE_RSHAPES)
TRACELOG(LOG_INFO, " > rshapes:... loaded (optional)");
#else
TRACELOG(LOG_INFO, " > rshapes:... not loaded (optional)");
#endif
#if defined(SUPPORT_MODULE_RTEXTURES)
TRACELOG(LOG_INFO, " > rtextures:. loaded (optional)");
#else
TRACELOG(LOG_INFO, " > rtextures:. not loaded (optional)");
#endif
#if defined(SUPPORT_MODULE_RTEXT)
TRACELOG(LOG_INFO, " > rtext:..... loaded (optional)");
#else
TRACELOG(LOG_INFO, " > rtext:..... not loaded (optional)");
#endif
#if defined(SUPPORT_MODULE_RMODELS)
TRACELOG(LOG_INFO, " > rmodels:... loaded (optional)");
#else
TRACELOG(LOG_INFO, " > rmodels:... not loaded (optional)");
#endif
#if defined(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;
InitPlatform();
rlglInit(CORE.Window.currentFbo.width, CORE.Window.currentFbo.height);
isGpuReady = true;
SetupViewport(CORE.Window.currentFbo.width, CORE.Window.currentFbo.height);
#if defined(SUPPORT_MODULE_RTEXT)
#if defined(SUPPORT_DEFAULT_FONT)
LoadFontDefault();
#if defined(SUPPORT_MODULE_RSHAPES)
Rectangle rec = GetFontDefault().recs[95];
if (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
#endif
#else
#if defined(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 defined(SUPPORT_GIF_RECORDING)
if (gifRecording)
{
MsfGifResult result = msf_gif_end(&gifState);
msf_gif_free(result);
gifRecording = false;
}
#endif
#if defined(SUPPORT_MODULE_RTEXT) && defined(SUPPORT_DEFAULT_FONT)
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 CORE.Window.fullscreen;
}
bool IsWindowHidden(void)
{
return ((CORE.Window.flags & FLAG_WINDOW_HIDDEN) > 0);
}
bool IsWindowMinimized(void)
{
return ((CORE.Window.flags & FLAG_WINDOW_MINIMIZED) > 0);
}
bool IsWindowMaximized(void)
{
return ((CORE.Window.flags & FLAG_WINDOW_MAXIMIZED) > 0);
}
bool IsWindowFocused(void)
{
return ((CORE.Window.flags & FLAG_WINDOW_UNFOCUSED) == 0);
}
bool IsWindowResized(void)
{
return CORE.Window.resizedLastFrame;
}
bool IsWindowState(unsigned int flag)
{
return ((CORE.Window.flags & flag) > 0);
}
int GetScreenWidth(void)
{
return CORE.Window.screen.width;
}
int GetScreenHeight(void)
{
return CORE.Window.screen.height;
}
int GetRenderWidth(void)
{
int width = 0;
#if defined(__APPLE__)
Vector2 scale = GetWindowScaleDPI();
width = (int)((float)CORE.Window.render.width*scale.x);
#else
width = CORE.Window.render.width;
#endif
return width;
}
int GetRenderHeight(void)
{
int height = 0;
#if defined(__APPLE__)
Vector2 scale = GetWindowScaleDPI();
height = (int)((float)CORE.Window.render.height*scale.y);
#else
height = CORE.Window.render.height;
#endif
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 defined(SUPPORT_GIF_RECORDING)
if (gifRecording)
{
#ifndef GIF_RECORD_FRAMERATE
#define GIF_RECORD_FRAMERATE 10
#endif
gifFrameCounter += (unsigned int)(GetFrameTime()*1000);
if (gifFrameCounter > 1000/GIF_RECORD_FRAMERATE)
{
Vector2 scale = GetWindowScaleDPI();
unsigned char *screenData = rlReadScreenPixels((int)((float)CORE.Window.render.width*scale.x), (int)((float)CORE.Window.render.height*scale.y));
#ifndef GIF_RECORD_BITRATE
#define GIF_RECORD_BITRATE 16
#endif
msf_gif_frame(&gifState, screenData, gifFrameCounter/10, GIF_RECORD_BITRATE, (int)((float)CORE.Window.render.width*scale.x)*4);
gifFrameCounter -= 1000/GIF_RECORD_FRAMERATE;
RL_FREE(screenData); }
#if defined(SUPPORT_MODULE_RSHAPES) && defined(SUPPORT_MODULE_RTEXT)
if ((int)(GetTime()/0.5)%2 == 1)
{
DrawCircle(30, CORE.Window.screen.height - 20, 10, MAROON); DrawText("GIF RECORDING", 50, CORE.Window.screen.height - 25, 10, RED); }
#endif
rlDrawRenderBatchActive(); }
#endif
#if defined(SUPPORT_AUTOMATION_EVENTS)
if (automationEventRecording) RecordAutomationEvent(); #endif
#if !defined(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 defined(SUPPORT_SCREEN_CAPTURE)
if (IsKeyPressed(KEY_F12))
{
#if defined(SUPPORT_GIF_RECORDING)
if (IsKeyDown(KEY_LEFT_CONTROL))
{
if (gifRecording)
{
gifRecording = false;
MsfGifResult result = msf_gif_end(&gifState);
SaveFileData(TextFormat("%s/screenrec%03i.gif", CORE.Storage.basePath, screenshotCounter), result.data, (unsigned int)result.dataSize);
msf_gif_free(result);
TRACELOG(LOG_INFO, "SYSTEM: Finish animated GIF recording");
}
else
{
gifRecording = true;
gifFrameCounter = 0;
Vector2 scale = GetWindowScaleDPI();
msf_gif_begin(&gifState, (int)((float)CORE.Window.render.width*scale.x), (int)((float)CORE.Window.render.height*scale.y));
screenshotCounter++;
TRACELOG(LOG_INFO, "SYSTEM: Start animated GIF recording: %s", TextFormat("screenrec%03i.gif", screenshotCounter));
}
}
else
#endif {
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 && ((CORE.Window.flags & FLAG_WINDOW_HIGHDPI) > 0))
{
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);
shader = LoadShaderFromMemory(vShaderStr, fShaderStr);
UnloadFileText(vShaderStr);
UnloadFileText(fShaderStr);
return shader;
}
Shader LoadShaderFromMemory(const char *vsCode, const char *fsCode)
{
Shader shader = { 0 };
shader.id = rlLoadShaderCode(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;
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_BONEIDS);
shader.locs[SHADER_LOC_VERTEX_BONEWEIGHTS] = rlGetLocationAttrib(shader.id, RL_DEFAULT_SHADER_ATTRIB_NAME_BONEWEIGHTS);
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_BONE_MATRICES] = rlGetLocationUniform(shader.id, RL_DEFAULT_SHADER_UNIFORM_NAME_BONE_MATRICES);
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, 0.01, 1000.0);
}
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 !defined(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) return 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);
#endif
return fps;
}
float GetFrameTime(void)
{
return (float)CORE.Time.frame;
}
void WaitTime(double seconds)
{
if (seconds < 0) return;
#if defined(SUPPORT_BUSY_WAIT_LOOP) || defined(SUPPORT_PARTIALBUSY_WAIT_LOOP)
double destinationTime = GetTime() + seconds;
#endif
#if defined(SUPPORT_BUSY_WAIT_LOOP)
while (GetTime() < destinationTime) { }
#else
#if defined(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 defined(SUPPORT_PARTIALBUSY_WAIT_LOOP)
while (GetTime() < destinationTime) { }
#endif
#endif
}
void SetRandomSeed(unsigned int seed)
{
#if defined(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 defined(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);
}
value = (rand()%(abs(max - min) + 1) + min);
#endif
return value;
}
int *LoadRandomSequence(unsigned int count, int min, int max)
{
int *values = NULL;
#if defined(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 = (rand()%(abs(max - min) + 1) + min);
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 defined(SUPPORT_RPRAND_GENERATOR)
rprand_unload_sequence(sequence);
#else
RL_FREE(sequence);
#endif
}
void TakeScreenshot(const char *fileName)
{
#if defined(SUPPORT_MODULE_RTEXTURES)
if (strchr(fileName, '\'') != NULL) { TRACELOG(LOG_WARNING, "SYSTEM: Provided fileName could be potentially malicious, avoid [\'] character"); return; }
Vector2 scale = GetWindowScaleDPI();
unsigned char *imgData = rlReadScreenPixels((int)((float)CORE.Window.render.width*scale.x), (int)((float)CORE.Window.render.height*scale.y));
Image image = { imgData, (int)((float)CORE.Window.render.width*scale.x), (int)((float)CORE.Window.render.height*scale.y), 1, PIXELFORMAT_UNCOMPRESSED_R8G8B8A8 };
char path[512] = { 0 };
strcpy(path, TextFormat("%s/%s", CORE.Storage.basePath, GetFileName(fileName)));
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)
{
CORE.Window.flags |= flags;
}
bool FileExists(const char *fileName)
{
bool result = false;
#if defined(_WIN32)
if (_access(fileName, 0) != -1) result = true;
#else
if (access(fileName, F_OK) != -1) result = true;
#endif
return result;
}
bool IsFileExtension(const char *fileName, const char *ext)
{
#define MAX_FILE_EXTENSION_LENGTH 16
bool result = false;
const char *fileExt = GetFileExtension(fileName);
if (fileExt != NULL)
{
#if defined(SUPPORT_MODULE_RTEXT) && defined(SUPPORT_TEXT_MANIPULATION)
int extCount = 0;
const char **checkExts = TextSplit(ext, ';', &extCount);
char fileExtLower[MAX_FILE_EXTENSION_LENGTH + 1] = { 0 };
strncpy(fileExtLower, TextToLower(fileExt), MAX_FILE_EXTENSION_LENGTH);
for (int i = 0; i < extCount; i++)
{
if (strcmp(fileExtLower, TextToLower(checkExts[i])) == 0)
{
result = true;
break;
}
}
#else
if (strcmp(fileExt, ext) == 0) result = true;
#endif
}
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;
}
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 *s, const char *charset)
{
const char *latestMatch = NULL;
for (; s = strpbrk(s, charset), s != NULL; latestMatch = s++) { }
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)
{
strcpy(fileName, GetFileName(filePath)); int size = (int)strlen(fileName);
for (int i = size; 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 pathLen = (int)strlen(dirPath);
if (pathLen <= 3) strcpy(prevDirPath, dirPath);
for (int i = (pathLen - 1); (i >= 0) && (pathLen > 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, widePath, MAX_PATH);
len = WideCharToMultiByte(0, 0, 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 len = strlen(appDir);
for (int i = len; 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 len = strlen(appDir);
for (int i = len; i >= 0; --i)
{
if (appDir[i] == '/')
{
appDir[i + 1] = '\0';
break;
}
}
}
else
{
appDir[0] = '.';
appDir[1] = '/';
}
#endif
return appDir;
}
FilePathList LoadDirectoryFiles(const char *dirPath)
{
FilePathList files = { 0 };
unsigned int fileCounter = 0;
struct dirent *entity;
DIR *dir = opendir(dirPath);
if (dir != NULL) {
while ((entity = readdir(dir)) != NULL)
{
if ((strcmp(entity->d_name, ".") != 0) && (strcmp(entity->d_name, "..") != 0)) fileCounter++;
}
files.capacity = fileCounter;
files.paths = (char **)RL_MALLOC(files.capacity*sizeof(char *));
for (unsigned int i = 0; i < files.capacity; i++) files.paths[i] = (char *)RL_MALLOC(MAX_FILEPATH_LENGTH*sizeof(char));
closedir(dir);
ScanDirectoryFiles(dirPath, &files, NULL);
if (files.count != files.capacity) TRACELOG(LOG_WARNING, "FILEIO: Read files count do not match capacity allocated");
}
else TRACELOG(LOG_WARNING, "FILEIO: Failed to open requested directory");
return files;
}
FilePathList LoadDirectoryFilesEx(const char *basePath, const char *filter, bool scanSubdirs)
{
FilePathList files = { 0 };
files.capacity = MAX_FILEPATH_CAPACITY;
files.paths = (char **)RL_CALLOC(files.capacity, sizeof(char *));
for (unsigned int i = 0; i < files.capacity; i++) files.paths[i] = (char *)RL_CALLOC(MAX_FILEPATH_LENGTH, sizeof(char));
if (scanSubdirs) ScanDirectoryFilesRecursively(basePath, &files, filter);
else ScanDirectoryFiles(basePath, &files, filter);
return files;
}
void UnloadDirectoryFiles(FilePathList files)
{
for (unsigned int i = 0; i < files.capacity; 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 len = (int)strlen(dirPath) + 1;
char *pathcpy = (char *)RL_CALLOC(len, 1);
memcpy(pathcpy, dirPath, len);
for (int i = 0; (i < len) && (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);
return 0;
}
bool ChangeDirectory(const char *dir)
{
bool result = CHDIR(dir);
if (result != 0) TRACELOG(LOG_WARNING, "SYSTEM: Failed to change to directory: %s", dir);
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 length = (int)strlen(fileName);
bool allPeriods = true;
for (int i = 0; i < length; 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;
}
}
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;
}
unsigned char *CompressData(const unsigned char *data, int dataSize, int *compDataSize)
{
#define COMPRESSION_QUALITY_DEFLATE 8
unsigned char *compData = NULL;
#if defined(SUPPORT_COMPRESSION_API)
struct sdefl *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 defined(SUPPORT_COMPRESSION_API)
data = (unsigned char *)RL_CALLOC(MAX_DECOMPRESSION_SIZE*1024*1024, 1);
int length = sinflate(data, MAX_DECOMPRESSION_SIZE*1024*1024, compData, compDataSize);
unsigned char *temp = (unsigned char *)RL_REALLOC(data, length);
if (temp != NULL) data = temp;
else TRACELOG(LOG_WARNING, "SYSTEM: Failed to re-allocate required decompression memory");
*dataSize = length;
TRACELOG(LOG_INFO, "SYSTEM: Decompress data: Comp. size: %i -> Original size: %i", compDataSize, *dataSize);
#endif
return data;
}
char *EncodeDataBase64(const unsigned char *data, int dataSize, int *outputSize)
{
static const unsigned char base64encodeTable[] = {
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X',
'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/'
};
static const int modTable[] = { 0, 2, 1 };
*outputSize = 4*((dataSize + 2)/3);
char *encodedData = (char *)RL_MALLOC(*outputSize);
if (encodedData == NULL) return NULL;
for (int i = 0, j = 0; i < dataSize;)
{
unsigned int octetA = (i < dataSize)? (unsigned char)data[i++] : 0;
unsigned int octetB = (i < dataSize)? (unsigned char)data[i++] : 0;
unsigned int octetC = (i < dataSize)? (unsigned char)data[i++] : 0;
unsigned int triple = (octetA << 0x10) + (octetB << 0x08) + octetC;
encodedData[j++] = base64encodeTable[(triple >> 3*6) & 0x3F];
encodedData[j++] = base64encodeTable[(triple >> 2*6) & 0x3F];
encodedData[j++] = base64encodeTable[(triple >> 1*6) & 0x3F];
encodedData[j++] = base64encodeTable[(triple >> 0*6) & 0x3F];
}
for (int i = 0; i < modTable[dataSize%3]; i++) encodedData[*outputSize - 1 - i] = '=';
return encodedData;
}
unsigned char *DecodeDataBase64(const unsigned char *data, int *outputSize)
{
static const unsigned char base64decodeTable[] = {
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 62, 0, 0, 0, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 0, 0, 0, 0, 0, 0, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36,
37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51
};
int outSize = 0;
for (int i = 0; data[4*i] != 0; i++)
{
if (data[4*i + 3] == '=')
{
if (data[4*i + 2] == '=') outSize += 1;
else outSize += 2;
}
else outSize += 3;
}
unsigned char *decodedData = (unsigned char *)RL_MALLOC(outSize);
for (int i = 0; i < outSize/3; i++)
{
unsigned char a = base64decodeTable[(int)data[4*i]];
unsigned char b = base64decodeTable[(int)data[4*i + 1]];
unsigned char c = base64decodeTable[(int)data[4*i + 2]];
unsigned char d = base64decodeTable[(int)data[4*i + 3]];
decodedData[3*i] = (a << 2) | (b >> 4);
decodedData[3*i + 1] = (b << 4) | (c >> 2);
decodedData[3*i + 2] = (c << 6) | d;
}
if (outSize%3 == 1)
{
int n = outSize/3;
unsigned char a = base64decodeTable[(int)data[4*n]];
unsigned char b = base64decodeTable[(int)data[4*n + 1]];
decodedData[outSize - 1] = (a << 2) | (b >> 4);
}
else if (outSize%3 == 2)
{
int n = outSize/3;
unsigned char a = base64decodeTable[(int)data[4*n]];
unsigned char b = base64decodeTable[(int)data[4*n + 1]];
unsigned char c = base64decodeTable[(int)data[4*n + 2]];
decodedData[outSize - 2] = (a << 2) | (b >> 4);
decodedData[outSize - 1] = (b << 4) | (c >> 2);
}
*outputSize = outSize;
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 = 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 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 = RL_CALLOC(newDataSize, 1); memcpy(msg, data, dataSize);
msg[dataSize] = 128;
unsigned int bitsLen = 8*dataSize;
msg[newDataSize-1] = bitsLen;
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] = 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 = ROTATE_LEFT(a, 5) + f + e + k + w[i];
e = d;
d = c;
c = ROTATE_LEFT(b, 30);
b = a;
a = temp;
}
hash[0] += a;
hash[1] += b;
hash[2] += c;
hash[3] += d;
hash[4] += e;
}
free(msg);
return hash;
}
AutomationEventList LoadAutomationEventList(const char *fileName)
{
AutomationEventList list = { 0 };
list.events = (AutomationEvent *)RL_CALLOC(MAX_AUTOMATION_EVENTS, sizeof(AutomationEvent));
list.capacity = MAX_AUTOMATION_EVENTS;
#if defined(SUPPORT_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 };
fgets(buffer, 256, raeFile);
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;
}
fgets(buffer, 256, raeFile);
}
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 defined(SUPPORT_AUTOMATION_EVENTS)
RL_FREE(list.events);
#endif
}
bool ExportAutomationEventList(AutomationEventList list, const char *fileName)
{
bool success = false;
#if defined(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-2024 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]);
}
success = SaveFileText(fileName, txtData);
RL_FREE(txtData);
#endif
return success;
}
void SetAutomationEventList(AutomationEventList *list)
{
#if defined(SUPPORT_AUTOMATION_EVENTS)
currentEventList = list;
#endif
}
void SetAutomationEventBaseFrame(int frame)
{
CORE.Time.frameCounter = frame;
}
void StartAutomationEventRecording(void)
{
#if defined(SUPPORT_AUTOMATION_EVENTS)
automationEventRecording = true;
#endif
}
void StopAutomationEventRecording(void)
{
#if defined(SUPPORT_AUTOMATION_EVENTS)
automationEventRecording = false;
#endif
}
void PlayAutomationEvent(AutomationEvent event)
{
#if defined(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 defined(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 defined(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) &&
(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) &&
(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) &&
(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) &&
(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_AXIS))
{
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 ((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 (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 ((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 (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;
delta.y = CORE.Input.Mouse.currentPosition.y - CORE.Input.Mouse.previousPosition.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) && defined(SUPPORT_WINMM_HIGHRES_TIMER) && !defined(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;
#if defined(__APPLE__)
Vector2 scale = GetWindowScaleDPI();
rlViewport(CORE.Window.renderOffset.x/2*scale.x, CORE.Window.renderOffset.y/2*scale.y, (CORE.Window.render.width)*scale.x, (CORE.Window.render.height)*scale.y);
#else
rlViewport(CORE.Window.renderOffset.x/2, CORE.Window.renderOffset.y/2, CORE.Window.render.width, CORE.Window.render.height);
#endif
rlMatrixMode(RL_PROJECTION); rlLoadIdentity();
rlOrtho(0, CORE.Window.render.width, CORE.Window.render.height, 0, 0.0f, 1.0f);
rlMatrixMode(RL_MODELVIEW); rlLoadIdentity(); }
void SetupFramebuffer(int width, int height)
{
if ((CORE.Window.screen.width > CORE.Window.display.width) || (CORE.Window.screen.height > CORE.Window.display.height))
{
TRACELOG(LOG_WARNING, "DISPLAY: Downscaling required: Screen size (%ix%i) is bigger than display size (%ix%i)", CORE.Window.screen.width, CORE.Window.screen.height, CORE.Window.display.width, CORE.Window.display.height);
float widthRatio = (float)CORE.Window.display.width/(float)CORE.Window.screen.width;
float heightRatio = (float)CORE.Window.display.height/(float)CORE.Window.screen.height;
if (widthRatio <= heightRatio)
{
CORE.Window.render.width = CORE.Window.display.width;
CORE.Window.render.height = (int)round((float)CORE.Window.screen.height*widthRatio);
CORE.Window.renderOffset.x = 0;
CORE.Window.renderOffset.y = (CORE.Window.display.height - CORE.Window.render.height);
}
else
{
CORE.Window.render.width = (int)round((float)CORE.Window.screen.width*heightRatio);
CORE.Window.render.height = CORE.Window.display.height;
CORE.Window.renderOffset.x = (CORE.Window.display.width - CORE.Window.render.width);
CORE.Window.renderOffset.y = 0;
}
float scaleRatio = (float)CORE.Window.render.width/(float)CORE.Window.screen.width;
CORE.Window.screenScale = MatrixScale(scaleRatio, scaleRatio, 1.0f);
CORE.Window.render.width = CORE.Window.display.width;
CORE.Window.render.height = CORE.Window.display.height;
TRACELOG(LOG_WARNING, "DISPLAY: Downscale matrix generated, content will be rendered at (%ix%i)", CORE.Window.render.width, CORE.Window.render.height);
}
else if ((CORE.Window.screen.width < CORE.Window.display.width) || (CORE.Window.screen.height < CORE.Window.display.height))
{
TRACELOG(LOG_INFO, "DISPLAY: Upscaling required: Screen size (%ix%i) smaller than display size (%ix%i)", CORE.Window.screen.width, CORE.Window.screen.height, CORE.Window.display.width, CORE.Window.display.height);
if ((CORE.Window.screen.width == 0) || (CORE.Window.screen.height == 0))
{
CORE.Window.screen.width = CORE.Window.display.width;
CORE.Window.screen.height = CORE.Window.display.height;
}
float displayRatio = (float)CORE.Window.display.width/(float)CORE.Window.display.height;
float screenRatio = (float)CORE.Window.screen.width/(float)CORE.Window.screen.height;
if (displayRatio <= screenRatio)
{
CORE.Window.render.width = CORE.Window.screen.width;
CORE.Window.render.height = (int)round((float)CORE.Window.screen.width/displayRatio);
CORE.Window.renderOffset.x = 0;
CORE.Window.renderOffset.y = (CORE.Window.render.height - CORE.Window.screen.height);
}
else
{
CORE.Window.render.width = (int)round((float)CORE.Window.screen.height*displayRatio);
CORE.Window.render.height = CORE.Window.screen.height;
CORE.Window.renderOffset.x = (CORE.Window.render.width - CORE.Window.screen.width);
CORE.Window.renderOffset.y = 0;
}
}
else
{
CORE.Window.render.width = CORE.Window.screen.width;
CORE.Window.render.height = CORE.Window.screen.height;
CORE.Window.renderOffset.x = 0;
CORE.Window.renderOffset.y = 0;
}
}
static void ScanDirectoryFiles(const char *basePath, FilePathList *files, const char *filter)
{
static 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)
{
if ((strcmp(dp->d_name, ".") != 0) &&
(strcmp(dp->d_name, "..") != 0))
{
#if defined(_WIN32)
sprintf(path, "%s\\%s", basePath, dp->d_name);
#else
sprintf(path, "%s/%s", basePath, dp->d_name);
#endif
if (filter != NULL)
{
if (IsPathFile(path))
{
if (IsFileExtension(path, filter))
{
strcpy(files->paths[files->count], path);
files->count++;
}
}
else
{
if (TextFindIndex(filter, DIRECTORY_FILTER_TAG) >= 0)
{
strcpy(files->paths[files->count], path);
files->count++;
}
}
}
else
{
strcpy(files->paths[files->count], path);
files->count++;
}
}
}
closedir(dir);
}
else TRACELOG(LOG_WARNING, "FILEIO: Directory cannot be opened (%s)", basePath);
}
static void ScanDirectoryFilesRecursively(const char *basePath, FilePathList *files, const char *filter)
{
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 < files->capacity))
{
if ((strcmp(dp->d_name, ".") != 0) && (strcmp(dp->d_name, "..") != 0))
{
#if defined(_WIN32)
sprintf(path, "%s\\%s", basePath, dp->d_name);
#else
sprintf(path, "%s/%s", basePath, dp->d_name);
#endif
if (IsPathFile(path))
{
if (filter != NULL)
{
if (IsFileExtension(path, filter))
{
strcpy(files->paths[files->count], path);
files->count++;
}
}
else
{
strcpy(files->paths[files->count], path);
files->count++;
}
if (files->count >= files->capacity)
{
TRACELOG(LOG_WARNING, "FILEIO: Maximum filepath scan capacity reached (%i files)", files->capacity);
break;
}
}
else
{
if ((filter != NULL) && (TextFindIndex(filter, DIRECTORY_FILTER_TAG) >= 0))
{
strcpy(files->paths[files->count], path);
files->count++;
}
if (files->count >= files->capacity)
{
TRACELOG(LOG_WARNING, "FILEIO: Maximum filepath scan capacity reached (%i files)", files->capacity);
break;
}
ScanDirectoryFilesRecursively(path, files, filter);
}
}
}
closedir(dir);
}
else TRACELOG(LOG_WARNING, "FILEIO: Directory cannot be opened (%s)", basePath);
}
#if defined(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 (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_AXIS; 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 defined(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 !defined(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);
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; sprintf(truncBuffer, "...");
}
index += 1; if (index >= MAX_TEXTFORMAT_BUFFERS) index = 0;
return currentBuffer;
}
#endif