Merge remote-tracking branch 'upstream/master'

This commit is contained in:
Joao M Coelho 2019-10-29 12:32:29 +00:00
commit c8e46cd713
102 changed files with 5405 additions and 3071 deletions

4
.github/FUNDING.yml vendored
View File

@ -1,8 +1,8 @@
# These are supported funding model platforms # These are supported funding model platforms
github: raysan5 github: raysan5
patreon: raylib patreon: # raylib
open_collective: # Replace with a single Open Collective username open_collective: # Replace with a single Open Collective username
ko_fi: raysan ko_fi: # raysan
tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel
custom: # Replace with a single custom sponsorship URL custom: # Replace with a single custom sponsorship URL

View File

@ -12,6 +12,7 @@ Some people ported raylib to other languages in form of bindings or wrappers to
- [cray](https://github.com/tapgg/cray) : raylib **Crystal** binding - [cray](https://github.com/tapgg/cray) : raylib **Crystal** binding
- [Graphics::Raylib](https://metacpan.org/pod/Graphics::Raylib) : raylib **Perl** wrapper - [Graphics::Raylib](https://metacpan.org/pod/Graphics::Raylib) : raylib **Perl** wrapper
- [raylib-pascal](https://github.com/drezgames/raylib-pascal) - raylib **Pascal** binding - [raylib-pascal](https://github.com/drezgames/raylib-pascal) - raylib **Pascal** binding
- [raylib-pas](https://github.com/tazdij/raylib-pas) - raylib **Pascal** binding (including rlgl & raymath)
- [Raylib-cs](https://github.com/ChrisDill/Raylib-cs) : raylib **C#** binding - [Raylib-cs](https://github.com/ChrisDill/Raylib-cs) : raylib **C#** binding
- [RaylibSharp](https://github.com/TheLumaio/RaylibSharp) : raylib **C#** binding - [RaylibSharp](https://github.com/TheLumaio/RaylibSharp) : raylib **C#** binding
- [raylib-ruby-ffi](https://github.com/D3nX/raylib-ruby-ffi) : raylib **Ruby** binding - [raylib-ruby-ffi](https://github.com/D3nX/raylib-ruby-ffi) : raylib **Ruby** binding

View File

@ -385,9 +385,9 @@ EXAMPLES = \
shapes/shapes_draw_circle_sector \ shapes/shapes_draw_circle_sector \
shapes/shapes_draw_rectangle_rounded \ shapes/shapes_draw_rectangle_rounded \
text/text_raylib_fonts \ text/text_raylib_fonts \
text/text_sprite_fonts \ text/text_font_spritefont \
text/text_ttf_loading \ text/text_font_loading \
text/text_bmfont_ttf \ text/text_font_filters \
text/text_font_sdf \ text/text_font_sdf \
text/text_format_text \ text/text_format_text \
text/text_input_box \ text/text_input_box \
@ -420,8 +420,7 @@ EXAMPLES = \
models/models_material_pbr \ models/models_material_pbr \
models/models_mesh_generation \ models/models_mesh_generation \
models/models_mesh_picking \ models/models_mesh_picking \
models/models_obj_loading \ models/models_loading \
models/models_obj_viewer \
models/models_orthographic_projection \ models/models_orthographic_projection \
models/models_rlgl_solar_system \ models/models_rlgl_solar_system \
models/models_skybox \ models/models_skybox \
@ -438,6 +437,8 @@ EXAMPLES = \
shaders/shaders_julia_set \ shaders/shaders_julia_set \
shaders/shaders_eratosthenes \ shaders/shaders_eratosthenes \
shaders/shaders_basic_lighting \ shaders/shaders_basic_lighting \
shaders/shaders_fog \
shaders/shaders_simple_mask \
audio/audio_module_playing \ audio/audio_module_playing \
audio/audio_music_stream \ audio/audio_music_stream \
audio/audio_raw_stream \ audio/audio_raw_stream \
@ -471,7 +472,7 @@ ifeq ($(PLATFORM),PLATFORM_DESKTOP)
del *.o *.exe /s del *.o *.exe /s
endif endif
ifeq ($(PLATFORM_OS),LINUX) ifeq ($(PLATFORM_OS),LINUX)
find -type f -executable | xargs file -i | grep -E 'x-object|x-archive|x-sharedlib|x-executable' | rev | cut -d ':' -f 2- | rev | xargs rm -fv find -type f -executable | xargs file -i | grep -E 'x-object|x-archive|x-sharedlib|x-executable|x-pie-executable' | rev | cut -d ':' -f 2- | rev | xargs rm -fv
endif endif
ifeq ($(PLATFORM_OS),OSX) ifeq ($(PLATFORM_OS),OSX)
find . -type f -perm +ugo+x -delete find . -type f -perm +ugo+x -delete

View File

@ -46,13 +46,13 @@ int main(void)
circles[i].radius = GetRandomValue(10, 40); circles[i].radius = GetRandomValue(10, 40);
circles[i].position.x = GetRandomValue(circles[i].radius, screenWidth - circles[i].radius); circles[i].position.x = GetRandomValue(circles[i].radius, screenWidth - circles[i].radius);
circles[i].position.y = GetRandomValue(circles[i].radius, screenHeight - circles[i].radius); circles[i].position.y = GetRandomValue(circles[i].radius, screenHeight - circles[i].radius);
circles[i].speed = (float)GetRandomValue(1, 100)/20000.0f; circles[i].speed = (float)GetRandomValue(1, 100)/2000.0f;
circles[i].color = colors[GetRandomValue(0, 13)]; circles[i].color = colors[GetRandomValue(0, 13)];
} }
Music xm = LoadMusicStream("resources/chiptun1.mod"); Music music = LoadMusicStream("resources/mini1111.xm");
PlayMusicStream(xm); PlayMusicStream(music);
float timePlayed = 0.0f; float timePlayed = 0.0f;
bool pause = false; bool pause = false;
@ -65,13 +65,13 @@ int main(void)
{ {
// Update // Update
//---------------------------------------------------------------------------------- //----------------------------------------------------------------------------------
UpdateMusicStream(xm); // Update music buffer with new stream data UpdateMusicStream(music); // Update music buffer with new stream data
// Restart music playing (stop and play) // Restart music playing (stop and play)
if (IsKeyPressed(KEY_SPACE)) if (IsKeyPressed(KEY_SPACE))
{ {
StopMusicStream(xm); StopMusicStream(music);
PlayMusicStream(xm); PlayMusicStream(music);
} }
// Pause/Resume music playing // Pause/Resume music playing
@ -79,12 +79,12 @@ int main(void)
{ {
pause = !pause; pause = !pause;
if (pause) PauseMusicStream(xm); if (pause) PauseMusicStream(music);
else ResumeMusicStream(xm); else ResumeMusicStream(music);
} }
// Get timePlayed scaled to bar dimensions // Get timePlayed scaled to bar dimensions
timePlayed = GetMusicTimePlayed(xm)/GetMusicTimeLength(xm)*(screenWidth - 40); timePlayed = GetMusicTimePlayed(music)/GetMusicTimeLength(music)*(screenWidth - 40);
// Color circles animation // Color circles animation
for (int i = MAX_CIRCLES - 1; (i >= 0) && !pause; i--) for (int i = MAX_CIRCLES - 1; (i >= 0) && !pause; i--)
@ -101,7 +101,7 @@ int main(void)
circles[i].position.x = GetRandomValue(circles[i].radius, screenWidth - circles[i].radius); circles[i].position.x = GetRandomValue(circles[i].radius, screenWidth - circles[i].radius);
circles[i].position.y = GetRandomValue(circles[i].radius, screenHeight - circles[i].radius); circles[i].position.y = GetRandomValue(circles[i].radius, screenHeight - circles[i].radius);
circles[i].color = colors[GetRandomValue(0, 13)]; circles[i].color = colors[GetRandomValue(0, 13)];
circles[i].speed = (float)GetRandomValue(1, 100)/20000.0f; circles[i].speed = (float)GetRandomValue(1, 100)/2000.0f;
} }
} }
//---------------------------------------------------------------------------------- //----------------------------------------------------------------------------------
@ -128,7 +128,7 @@ int main(void)
// De-Initialization // De-Initialization
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
UnloadMusicStream(xm); // Unload music stream buffers from RAM UnloadMusicStream(music); // Unload music stream buffers from RAM
CloseAudioDevice(); // Close audio device (music streaming is automatically stopped) CloseAudioDevice(); // Close audio device (music streaming is automatically stopped)

View File

@ -99,7 +99,7 @@ int main(void)
} }
// Refill audio stream if required // Refill audio stream if required
if (IsAudioBufferProcessed(stream)) if (IsAudioStreamProcessed(stream))
{ {
// Synthesize a buffer that is exactly the requested size // Synthesize a buffer that is exactly the requested size
int writeCursor = 0; int writeCursor = 0;

View File

@ -42,7 +42,7 @@ int main(void)
Camera2D camera = { 0 }; Camera2D camera = { 0 };
camera.target = (Vector2){ player.x + 20, player.y + 20 }; camera.target = (Vector2){ player.x + 20, player.y + 20 };
camera.offset = (Vector2){ 0, 0 }; camera.offset = (Vector2){ screenWidth/2, screenHeight/2 };
camera.rotation = 0.0f; camera.rotation = 0.0f;
camera.zoom = 1.0f; camera.zoom = 1.0f;
@ -54,16 +54,10 @@ int main(void)
{ {
// Update // Update
//---------------------------------------------------------------------------------- //----------------------------------------------------------------------------------
if (IsKeyDown(KEY_RIGHT))
{ // Player movement
player.x += 2; // Player movement if (IsKeyDown(KEY_RIGHT)) player.x += 2;
camera.offset.x -= 2; // Camera displacement with player movement else if (IsKeyDown(KEY_LEFT)) player.x -= 2;
}
else if (IsKeyDown(KEY_LEFT))
{
player.x -= 2; // Player movement
camera.offset.x += 2; // Camera displacement with player movement
}
// Camera target follows player // Camera target follows player
camera.target = (Vector2){ player.x + 20, player.y + 20 }; camera.target = (Vector2){ player.x + 20, player.y + 20 };

View File

@ -0,0 +1,284 @@
/*******************************************************************************************
*
* raylib [core] example - 2d camera extended
*
* This example has been created using raylib 1.5 (www.raylib.com)
* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details)
*
* Copyright (c) 2016 Ramon Santamaria (@raysan5)
*
********************************************************************************************/
#include "raylib.h"
#include "raymath.h"
#define G 400
#define PLAYER_JUMP_SPD 350.f
#define PLAYER_HOR_SPD 200.f
typedef struct Player {
Vector2 pos;
float vel;
int canJump;
} Player;
typedef struct EnvItem {
Rectangle rect;
int blocking;
Color color;
} EnvItem;
void updateCameraCenter(
float delta,
Camera2D *camera,
Player *player,
EnvItem *envItems,
int envItemsLength,
int width, int height
) {
camera->offset = (Vector2){ width/2, height/2 };
camera->target = player->pos;
}
void updateCameraCenterInsideMap(
float delta,
Camera2D *camera,
Player *player,
EnvItem *envItems,
int envItemsLength,
int width, int height
) {
camera->target = player->pos;
camera->offset = (Vector2){ width/2, height/2 };
float minX = 1000, minY = 1000, maxX = -1000, maxY = -1000;
for (int i = 0; i < envItemsLength; i++) {
EnvItem *ei = envItems + i;
minX = fminf(ei->rect.x, minX);
maxX = fmaxf(ei->rect.x + ei->rect.width, maxX);
minY = fminf(ei->rect.y, minY);
maxY = fmaxf(ei->rect.y + ei->rect.height, maxY);
}
Vector2 max = GetWorldToScreen2D((Vector2){ maxX, maxY }, *camera);
Vector2 min = GetWorldToScreen2D((Vector2){ minX, minY }, *camera);
if (max.x < width) {
camera->offset.x = width - (max.x - width/2);
}
if (max.y < height) {
camera->offset.y = height - (max.y - height/2);
}
if (min.x > 0) {
camera->offset.x = width/2 - min.x;
}
if (min.y > 0) {
camera->offset.y = height/2- min.y;
}
}
void updateCameraCenterSmoothFollow(
float delta,
Camera2D *camera,
Player *player,
EnvItem *envItems,
int envItemsLength,
int width, int height
) {
static float minSpeed = 30;
static float minEffectLength = 10;
static float fractionSpeed = 0.8f;
camera->offset = (Vector2){ width/2, height/2 };
Vector2 diff = Vector2Subtract(player->pos, camera->target);
float length = Vector2Length(diff);
if (length > minEffectLength) {
float speed = fmaxf(fractionSpeed * length, minSpeed);
camera->target = Vector2Add(camera->target, Vector2Scale(diff, speed*delta/length));
}
}
void updateCameraEvenOutOnLanding(
float delta,
Camera2D *camera,
Player *player,
EnvItem *envItems,
int envItemsLength,
int width, int height
) {
static float evenOutSpeed = 700;
static int eveningOut = false;
static float evenOutTarget;
camera->offset = (Vector2){ width/2, height/2 };
camera->target.x = player->pos.x;
if (eveningOut) {
if (evenOutTarget > camera->target.y) {
camera->target.y += evenOutSpeed * delta;
if (camera->target.y > evenOutTarget) {
camera->target.y = evenOutTarget;
eveningOut = 0;
}
} else {
camera->target.y -= evenOutSpeed * delta;
if (camera->target.y < evenOutTarget) {
camera->target.y = evenOutTarget;
eveningOut = 0;
}
}
} else {
if (player->canJump &&
player->vel == 0 &&
player->pos.y != camera->target.y
) {
eveningOut = 1;
evenOutTarget = player->pos.y;
}
}
}
void updateCameraPlayerBoundsPush(
float delta,
Camera2D *camera,
Player *player,
EnvItem *envItems,
int envItemsLength,
int width, int height
) {
static Vector2 bbox = { 0.2f, 0.2f };
Vector2 bboxWorldMin = GetScreenToWorld2D((Vector2){ (1 - bbox.x) * 0.5 * width, (1 - bbox.y) * 0.5 * height }, *camera);
Vector2 bboxWorldMax = GetScreenToWorld2D((Vector2){ (1 + bbox.x) * 0.5 * width, (1 + bbox.y) * 0.5 * height }, *camera);
camera->offset = (Vector2){ (1 - bbox.x) * 0.5 * width, (1 - bbox.y) * 0.5 * height };
if (player->pos.x < bboxWorldMin.x) {
camera->target.x = player->pos.x;
}
if (player->pos.y < bboxWorldMin.y) {
camera->target.y = player->pos.y;
}
if (player->pos.x > bboxWorldMax.x) {
camera->target.x = bboxWorldMin.x + (player->pos.x - bboxWorldMax.x);
}
if (player->pos.y > bboxWorldMax.y) {
camera->target.y = bboxWorldMin.y + (player->pos.y - bboxWorldMax.y);
}
}
void updatePlayer(float delta, Player *player, EnvItem *envItems, int envItemsLength) {
if (IsKeyDown(KEY_LEFT)) player->pos.x -= PLAYER_HOR_SPD*delta;
if (IsKeyDown(KEY_RIGHT)) player->pos.x += PLAYER_HOR_SPD*delta;
if (IsKeyDown(KEY_SPACE) && player->canJump) {
player->vel = -PLAYER_JUMP_SPD;
player->canJump = 0;
}
int hitObstacle = 0;
for (int i = 0; i < envItemsLength; i++) {
EnvItem *ei = envItems + i;
Vector2 *p = &(player->pos);
if (ei->blocking &&
ei->rect.x <= p->x &&
ei->rect.x + ei->rect.width >= p->x &&
ei->rect.y >= p->y &&
ei->rect.y < p->y + player->vel * delta)
{
hitObstacle = 1;
player->vel = 0.0f;
p->y = ei->rect.y;
}
}
if (!hitObstacle) {
player->pos.y += player->vel * delta;
player->vel += G * delta;
player->canJump = 0;
} else {
player->canJump = 1;
}
}
void renderWorld(Player *player, EnvItem *envItems, int envItemsLength) {
for (int i = 0; i < envItemsLength; i++) {
DrawRectangleRec(envItems[i].rect, envItems[i].color);
}
Rectangle playerRect = { player->pos.x - 20, player->pos.y - 40, 40, 40 };
DrawRectangleRec(playerRect, RED);
}
int main(void)
{
const int screenWidth = 800;
const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [core] example - 2d camera");
SetTargetFPS(60);
Player player;
player.pos = (Vector2){ 400, 280 };
player.vel = 0;
player.canJump = 0;
EnvItem envItems[] = {
{{ 0, 0, 1000, 400 }, 0, LIGHTGRAY },
{{ 0, 400, 1000, 200 }, 1, GRAY },
{{ 300, 200, 400, 10 }, 1, GRAY },
{{ 250, 300, 100, 10 }, 1, GRAY },
{{ 650, 300, 100, 10 }, 1, GRAY }
};
int envItemsLength = sizeof(envItems) / sizeof (envItems[0]);
Camera2D camera = { 0 };
camera.target = player.pos;
camera.offset = (Vector2){ screenWidth/2, screenHeight/2 };
camera.rotation = 0.0f;
camera.zoom = 1.0f;
int cameraOption = 0;
void (*cameraUpdaters[])(float, Camera2D*, Player*, EnvItem*, int, int, int) = {
updateCameraCenter,
updateCameraCenterInsideMap,
updateCameraCenterSmoothFollow,
updateCameraEvenOutOnLanding,
updateCameraPlayerBoundsPush
};
int cameraUpdatersLength = sizeof(cameraUpdaters) / sizeof(cameraUpdaters[0]);
char* cameraDescriptions[] = {
"Follow player center",
"Follow player center, but clamp to map edges",
"Follow player center; smoothed",
"Follow player center horizontally; updateplayer center vertically after landing",
"Player push camera on getting too close to screen edge"
};
while (!WindowShouldClose()) {
float delta = GetFrameTime();
updatePlayer(delta, &player, envItems, envItemsLength);
camera.zoom += ((float)GetMouseWheelMove()*0.05f);
if (camera.zoom > 3.0f) camera.zoom = 3.0f;
else if (camera.zoom < 0.25f) camera.zoom = 0.25f;
if (IsKeyPressed(KEY_R))
{
camera.zoom = 1.0f;
}
if (IsKeyPressed(KEY_C)) {
cameraOption = (cameraOption + 1) % cameraUpdatersLength;
}
cameraUpdaters[cameraOption](delta, &camera, &player, envItems, envItemsLength, screenWidth, screenHeight);
BeginDrawing();
ClearBackground(RAYWHITE);
BeginMode2D(camera);
renderWorld(&player, envItems, envItemsLength);
EndMode2D();
DrawText("Controls:", 20, 20, 10, BLACK);
DrawText("- Right/Left to move", 40, 40, 10, DARKGRAY);
DrawText("- Space to jump", 40, 60, 10, DARKGRAY);
DrawText("- Mouse Wheel to Zoom in-out, R to reset zoom", 40, 80, 10, DARKGRAY);
DrawText("- C to change camera mode", 40, 100, 10, DARKGRAY);
DrawText("Current camera mode:", 20, 120, 10, BLACK);
DrawText(cameraDescriptions[cameraOption], 40, 140, 10, DARKGRAY);
EndDrawing();
}
CloseWindow(); // Close window and OpenGL context
return 0;
}

View File

@ -11,14 +11,14 @@ uniform sampler2D texture0;
uniform vec4 colDiffuse; uniform vec4 colDiffuse;
// NOTE: Add here your custom variables // NOTE: Add here your custom variables
uniform vec2 leftLensCenter = vec2(0.288, 0.5); uniform vec2 leftLensCenter;
uniform vec2 rightLensCenter = vec2(0.712, 0.5); uniform vec2 rightLensCenter;
uniform vec2 leftScreenCenter = vec2(0.25, 0.5); uniform vec2 leftScreenCenter;
uniform vec2 rightScreenCenter = vec2(0.75, 0.5); uniform vec2 rightScreenCenter;
uniform vec2 scale = vec2(0.25, 0.45); uniform vec2 scale;
uniform vec2 scaleIn = vec2(4, 2.2222); uniform vec2 scaleIn;
uniform vec4 hmdWarpParam = vec4(1, 0.22, 0.24, 0); uniform vec4 hmdWarpParam;
uniform vec4 chromaAbParam = vec4(0.996, -0.004, 1.014, 0.0); uniform vec4 chromaAbParam;
void main() void main()
{ {

View File

@ -9,8 +9,15 @@
* *
* Copyright (c) 2019 Culacant (@culacant) and Ramon Santamaria (@raysan5) * Copyright (c) 2019 Culacant (@culacant) and Ramon Santamaria (@raysan5)
* *
********************************************************************************************
*
* To export a model from blender, make sure it is not posed, the vertices need to be in the
* same position as they would be in edit mode.
* and that the scale of your models is set to 0. Scaling can be done from the export menu.
*
********************************************************************************************/ ********************************************************************************************/
#include <stdlib.h>
#include "raylib.h" #include "raylib.h"
int main(void) int main(void)
@ -91,8 +98,11 @@ int main(void)
// De-Initialization // De-Initialization
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
UnloadTexture(texture); // Unload texture
// Unload model animations data // Unload model animations data
for (int i = 0; i < animsCount; i++) UnloadModelAnimation(anims[i]); for (int i = 0; i < animsCount; i++) UnloadModelAnimation(anims[i]);
RL_FREE(anims);
UnloadModel(model); // Unload model UnloadModel(model); // Unload model

View File

@ -0,0 +1,142 @@
/*******************************************************************************************
*
* raylib [models] example - Models loading
*
* raylib supports multiple models file formats:
*
* - OBJ > Text file, must include vertex position-texcoords-normals information,
* if files references some .mtl materials file, it will be loaded (or try to)
* - GLTF > Modern text/binary file format, includes lot of information and it could
* also reference external files, raylib will try loading mesh and materials data
* - IQM > Binary file format including mesh vertex data but also animation data,
* raylib can load .iqm animations.
*
* This example has been created using raylib 2.6 (www.raylib.com)
* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details)
*
* Copyright (c) 2014-2019 Ramon Santamaria (@raysan5)
*
********************************************************************************************/
#include "raylib.h"
int main(void)
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [models] example - models loading");
// Define the camera to look into our 3d world
Camera camera = { 0 };
camera.position = (Vector3){ 50.0f, 50.0f, 50.0f }; // Camera position
camera.target = (Vector3){ 0.0f, 10.0f, 0.0f }; // Camera looking at point
camera.up = (Vector3){ 0.0f, 1.0f, 0.0f }; // Camera up vector (rotation towards target)
camera.fovy = 45.0f; // Camera field-of-view Y
camera.type = CAMERA_PERSPECTIVE; // Camera mode type
Model model = LoadModel("resources/models/castle.obj"); // Load model
Texture2D texture = LoadTexture("resources/models/castle_diffuse.png"); // Load model texture
model.materials[0].maps[MAP_DIFFUSE].texture = texture; // Set map diffuse texture
Vector3 position = { 0.0f, 0.0f, 0.0f }; // Set model position
BoundingBox bounds = MeshBoundingBox(model.meshes[0]); // Set model bounds
// NOTE: bounds are calculated from the original size of the model,
// if model is scaled on drawing, bounds must be also scaled
SetCameraMode(camera, CAMERA_FREE); // Set a free camera mode
bool selected = false; // Selected object flag
SetTargetFPS(60); // Set our game to run at 60 frames-per-second
//--------------------------------------------------------------------------------------
// Main game loop
while (!WindowShouldClose()) // Detect window close button or ESC key
{
// Update
//----------------------------------------------------------------------------------
UpdateCamera(&camera);
// Load new models/textures on drag&drop
if (IsFileDropped())
{
int count = 0;
char **droppedFiles = GetDroppedFiles(&count);
if (count == 1) // Only support one file dropped
{
if (IsFileExtension(droppedFiles[0], ".obj") ||
IsFileExtension(droppedFiles[0], ".gltf") ||
IsFileExtension(droppedFiles[0], ".iqm")) // Model file formats supported
{
UnloadModel(model); // Unload previous model
model = LoadModel(droppedFiles[0]); // Load new model
model.materials[0].maps[MAP_DIFFUSE].texture = texture; // Set current map diffuse texture
bounds = MeshBoundingBox(model.meshes[0]);
// TODO: Move camera position from target enough distance to visualize model properly
}
else if (IsFileExtension(droppedFiles[0], ".png")) // Texture file formats supported
{
// Unload current model texture and load new one
UnloadTexture(texture);
texture = LoadTexture(droppedFiles[0]);
model.materials[0].maps[MAP_DIFFUSE].texture = texture;
}
}
ClearDroppedFiles(); // Clear internal buffers
}
// Select model on mouse click
if (IsMouseButtonPressed(MOUSE_LEFT_BUTTON))
{
// Check collision between ray and box
if (CheckCollisionRayBox(GetMouseRay(GetMousePosition(), camera), bounds)) selected = !selected;
else selected = false;
}
//----------------------------------------------------------------------------------
// Draw
//----------------------------------------------------------------------------------
BeginDrawing();
ClearBackground(RAYWHITE);
BeginMode3D(camera);
DrawModel(model, position, 1.0f, WHITE); // Draw 3d model with texture
DrawGrid(20, 10.0f); // Draw a grid
if (selected) DrawBoundingBox(bounds, GREEN); // Draw selection box
EndMode3D();
DrawText("Drag & drop model to load mesh/texture.", 10, GetScreenHeight() - 20, 10, DARKGRAY);
if (selected) DrawText("MODEL SELECTED", GetScreenWidth() - 110, 10, 10, GREEN);
DrawText("(c) Castle 3D model by Alberto Cano", screenWidth - 200, screenHeight - 20, 10, GRAY);
DrawFPS(10, 10);
EndDrawing();
//----------------------------------------------------------------------------------
}
// De-Initialization
//--------------------------------------------------------------------------------------
UnloadTexture(texture); // Unload texture
UnloadModel(model); // Unload model
CloseWindow(); // Close window and OpenGL context
//--------------------------------------------------------------------------------------
return 0;
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 217 KiB

View File

@ -50,16 +50,15 @@ int main(void)
// NOTE: New VBO for tangents is generated at default location and also binded to mesh VAO // NOTE: New VBO for tangents is generated at default location and also binded to mesh VAO
MeshTangents(&model.meshes[0]); MeshTangents(&model.meshes[0]);
UnloadMaterial(model.materials[0]); // get rid of default material
model.materials[0] = LoadMaterialPBR((Color){ 255, 255, 255, 255 }, 1.0f, 1.0f); model.materials[0] = LoadMaterialPBR((Color){ 255, 255, 255, 255 }, 1.0f, 1.0f);
// Define lights attributes // Create lights
// NOTE: Shader is passed to every light on creation to define shader bindings internally // NOTE: Lights are added to an internal lights pool automatically
Light lights[MAX_LIGHTS] = { CreateLight(LIGHT_POINT, (Vector3){ LIGHT_DISTANCE, LIGHT_HEIGHT, 0.0f }, (Vector3){ 0.0f, 0.0f, 0.0f }, (Color){ 255, 0, 0, 255 }, model.materials[0].shader);
CreateLight(LIGHT_POINT, (Vector3){ LIGHT_DISTANCE, LIGHT_HEIGHT, 0.0f }, (Vector3){ 0.0f, 0.0f, 0.0f }, (Color){ 255, 0, 0, 255 }, model.materials[0].shader), CreateLight(LIGHT_POINT, (Vector3){ 0.0f, LIGHT_HEIGHT, LIGHT_DISTANCE }, (Vector3){ 0.0f, 0.0f, 0.0f }, (Color){ 0, 255, 0, 255 }, model.materials[0].shader);
CreateLight(LIGHT_POINT, (Vector3){ 0.0f, LIGHT_HEIGHT, LIGHT_DISTANCE }, (Vector3){ 0.0f, 0.0f, 0.0f }, (Color){ 0, 255, 0, 255 }, model.materials[0].shader), CreateLight(LIGHT_POINT, (Vector3){ -LIGHT_DISTANCE, LIGHT_HEIGHT, 0.0f }, (Vector3){ 0.0f, 0.0f, 0.0f }, (Color){ 0, 0, 255, 255 }, model.materials[0].shader);
CreateLight(LIGHT_POINT, (Vector3){ -LIGHT_DISTANCE, LIGHT_HEIGHT, 0.0f }, (Vector3){ 0.0f, 0.0f, 0.0f }, (Color){ 0, 0, 255, 255 }, model.materials[0].shader), CreateLight(LIGHT_DIRECTIONAL, (Vector3){ 0.0f, LIGHT_HEIGHT*2.0f, -LIGHT_DISTANCE }, (Vector3){ 0.0f, 0.0f, 0.0f }, (Color){ 255, 0, 255, 255 }, model.materials[0].shader);
CreateLight(LIGHT_DIRECTIONAL, (Vector3){ 0.0f, LIGHT_HEIGHT*2.0f, -LIGHT_DISTANCE }, (Vector3){ 0.0f, 0.0f, 0.0f }, (Color){ 255, 0, 255, 255 }, model.materials[0].shader)
};
SetCameraMode(camera, CAMERA_ORBITAL); // Set an orbital camera mode SetCameraMode(camera, CAMERA_ORBITAL); // Set an orbital camera mode
@ -100,7 +99,20 @@ int main(void)
// De-Initialization // De-Initialization
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
UnloadModel(model); // Unload skybox model
// Shaders and textures must be unloaded by user,
// they could be in use by other models
UnloadTexture(model.materials[0].maps[MAP_ALBEDO].texture);
UnloadTexture(model.materials[0].maps[MAP_NORMAL].texture);
UnloadTexture(model.materials[0].maps[MAP_METALNESS].texture);
UnloadTexture(model.materials[0].maps[MAP_ROUGHNESS].texture);
UnloadTexture(model.materials[0].maps[MAP_OCCLUSION].texture);
UnloadTexture(model.materials[0].maps[MAP_IRRADIANCE].texture);
UnloadTexture(model.materials[0].maps[MAP_PREFILTER].texture);
UnloadTexture(model.materials[0].maps[MAP_BRDF].texture);
UnloadShader(model.materials[0].shader);
UnloadModel(model); // Unload model
CloseWindow(); // Close window and OpenGL context CloseWindow(); // Close window and OpenGL context
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
@ -112,7 +124,7 @@ int main(void)
// NOTE: PBR shader is loaded inside this function // NOTE: PBR shader is loaded inside this function
static Material LoadMaterialPBR(Color albedo, float metalness, float roughness) static Material LoadMaterialPBR(Color albedo, float metalness, float roughness)
{ {
Material mat = { 0 }; // NOTE: All maps textures are set to { 0 } Material mat = LoadMaterialDefault(); // Initialize material to default
#if defined(PLATFORM_DESKTOP) #if defined(PLATFORM_DESKTOP)
mat.shader = LoadShader("resources/shaders/glsl330/pbr.vs", "resources/shaders/glsl330/pbr.fs"); mat.shader = LoadShader("resources/shaders/glsl330/pbr.vs", "resources/shaders/glsl330/pbr.fs");
@ -135,7 +147,7 @@ static Material LoadMaterialPBR(Color albedo, float metalness, float roughness)
// Set view matrix location // Set view matrix location
mat.shader.locs[LOC_MATRIX_MODEL] = GetShaderLocation(mat.shader, "matModel"); mat.shader.locs[LOC_MATRIX_MODEL] = GetShaderLocation(mat.shader, "matModel");
mat.shader.locs[LOC_MATRIX_VIEW] = GetShaderLocation(mat.shader, "view"); //mat.shader.locs[LOC_MATRIX_VIEW] = GetShaderLocation(mat.shader, "view");
mat.shader.locs[LOC_VECTOR_VIEW] = GetShaderLocation(mat.shader, "viewPos"); mat.shader.locs[LOC_VECTOR_VIEW] = GetShaderLocation(mat.shader, "viewPos");
// Set PBR standard maps // Set PBR standard maps

View File

@ -115,6 +115,7 @@ int main(void)
// De-Initialization // De-Initialization
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
UnloadTexture(texture); // Unload texture
// Unload models data (GPU VRAM) // Unload models data (GPU VRAM)
for (int i = 0; i < NUM_MODELS; i++) UnloadModel(models[i]); for (int i = 0; i < NUM_MODELS; i++) UnloadModel(models[i]);

View File

@ -105,7 +105,7 @@ int main(void)
// Check ray collision against model // Check ray collision against model
// NOTE: It considers model.transform matrix! // NOTE: It considers model.transform matrix!
meshHitInfo = GetCollisionRayModel(ray, &tower); meshHitInfo = GetCollisionRayModel(ray, tower);
if ((meshHitInfo.hit) && (meshHitInfo.distance < nearestHit.distance)) if ((meshHitInfo.hit) && (meshHitInfo.distance < nearestHit.distance))
{ {

View File

@ -1,80 +0,0 @@
/*******************************************************************************************
*
* raylib [models] example - Load and draw a 3d model (OBJ)
*
* This example has been created using raylib 1.3 (www.raylib.com)
* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details)
*
* Copyright (c) 2014 Ramon Santamaria (@raysan5)
*
********************************************************************************************/
#include "raylib.h"
int main(void)
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [models] example - obj model loading");
// Define the camera to look into our 3d world
Camera camera = { 0 };
camera.position = (Vector3){ 8.0f, 8.0f, 8.0f }; // Camera position
camera.target = (Vector3){ 0.0f, 2.5f, 0.0f }; // Camera looking at point
camera.up = (Vector3){ 0.0f, 1.0f, 0.0f }; // Camera up vector (rotation towards target)
camera.fovy = 45.0f; // Camera field-of-view Y
camera.type = CAMERA_PERSPECTIVE; // Camera mode type
Model model = LoadModel("resources/models/castle.obj"); // Load OBJ model
Texture2D texture = LoadTexture("resources/models/castle_diffuse.png"); // Load model texture
model.materials[0].maps[MAP_DIFFUSE].texture = texture; // Set map diffuse texture
Vector3 position = { 0.0f, 0.0f, 0.0f }; // Set model position
SetTargetFPS(60); // Set our game to run at 60 frames-per-second
//--------------------------------------------------------------------------------------
// Main game loop
while (!WindowShouldClose()) // Detect window close button or ESC key
{
// Update
//----------------------------------------------------------------------------------
//...
//----------------------------------------------------------------------------------
// Draw
//----------------------------------------------------------------------------------
BeginDrawing();
ClearBackground(RAYWHITE);
BeginMode3D(camera);
DrawModel(model, position, 0.2f, WHITE); // Draw 3d model with texture
DrawGrid(10, 1.0f); // Draw a grid
DrawGizmo(position); // Draw gizmo
EndMode3D();
DrawText("(c) Castle 3D model by Alberto Cano", screenWidth - 200, screenHeight - 20, 10, GRAY);
DrawFPS(10, 10);
EndDrawing();
//----------------------------------------------------------------------------------
}
// De-Initialization
//--------------------------------------------------------------------------------------
UnloadTexture(texture); // Unload texture
UnloadModel(model); // Unload model
CloseWindow(); // Close window and OpenGL context
//--------------------------------------------------------------------------------------
return 0;
}

Binary file not shown.

Before

Width:  |  Height:  |  Size: 260 KiB

View File

@ -1,127 +0,0 @@
/*******************************************************************************************
*
* raylib [models] example - OBJ models viewer
*
* This example has been created using raylib 2.0 (www.raylib.com)
* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details)
*
* Copyright (c) 2014-2019 Ramon Santamaria (@raysan5)
*
********************************************************************************************/
#include "raylib.h"
#include <string.h> // Required for: strcpy()
int main(void)
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib example - obj viewer");
// Define the camera to look into our 3d world
Camera camera = { { 30.0f, 30.0f, 30.0f }, { 0.0f, 10.0f, 0.0f }, { 0.0f, 1.0f, 0.0f }, 45.0f, 0 };
Model model = LoadModel("resources/models/turret.obj"); // Load default model obj
Texture2D texture = LoadTexture("resources/models/turret_diffuse.png"); // Load default model texture
model.materials[0].maps[MAP_DIFFUSE].texture = texture; // Bind texture to model
Vector3 position = { 0.0, 0.0, 0.0 }; // Set model position
BoundingBox bounds = MeshBoundingBox(model.meshes[0]); // Set model bounds
bool selected = false; // Selected object flag
SetCameraMode(camera, CAMERA_FREE); // Set a free camera mode
char objFilename[64] = "turret.obj";
SetTargetFPS(60); // Set our game to run at 60 frames-per-second
//--------------------------------------------------------------------------------------
// Main game loop
while (!WindowShouldClose()) // Detect window close button or ESC key
{
// Update
//----------------------------------------------------------------------------------
if (IsFileDropped())
{
int count = 0;
char **droppedFiles = GetDroppedFiles(&count);
if (count == 1)
{
if (IsFileExtension(droppedFiles[0], ".obj"))
{
for (int i = 0; i < model.meshCount; i++) UnloadMesh(&model.meshes[i]);
model.meshes = LoadMeshes(droppedFiles[0], &model.meshCount);
bounds = MeshBoundingBox(model.meshes[0]);
}
else if (IsFileExtension(droppedFiles[0], ".png"))
{
UnloadTexture(texture);
texture = LoadTexture(droppedFiles[0]);
model.materials[0].maps[MAP_DIFFUSE].texture = texture;
}
strcpy(objFilename, GetFileName(droppedFiles[0]));
}
ClearDroppedFiles(); // Clear internal buffers
}
UpdateCamera(&camera);
// Select model on mouse click
if (IsMouseButtonPressed(MOUSE_LEFT_BUTTON))
{
// Check collision between ray and box
if (CheckCollisionRayBox(GetMouseRay(GetMousePosition(), camera), bounds)) selected = !selected;
else selected = false;
}
//----------------------------------------------------------------------------------
// Draw
//----------------------------------------------------------------------------------
BeginDrawing();
ClearBackground(RAYWHITE);
BeginMode3D(camera);
DrawModel(model, position, 1.0f, WHITE); // Draw 3d model with texture
DrawGrid(20.0, 10.0); // Draw a grid
if (selected) DrawBoundingBox(bounds, GREEN);
EndMode3D();
DrawText("Free camera default controls:", 10, 20, 10, DARKGRAY);
DrawText("- Mouse Wheel to Zoom in-out", 20, 40, 10, GRAY);
DrawText("- Mouse Wheel Pressed to Pan", 20, 60, 10, GRAY);
DrawText("- Alt + Mouse Wheel Pressed to Rotate", 20, 80, 10, GRAY);
DrawText("- Alt + Ctrl + Mouse Wheel Pressed for Smooth Zoom", 20, 100, 10, GRAY);
DrawText("Drag & drop .obj/.png to load mesh/texture.", 10, GetScreenHeight() - 20, 10, DARKGRAY);
DrawText(FormatText("Current file: %s", objFilename), 250, GetScreenHeight() - 20, 10, GRAY);
if (selected) DrawText("MODEL SELECTED", GetScreenWidth() - 110, 10, 10, GREEN);
DrawText("(c) Turret 3D model by Alberto Cano", screenWidth - 200, screenHeight - 20, 10, GRAY);
EndDrawing();
//----------------------------------------------------------------------------------
}
// De-Initialization
//--------------------------------------------------------------------------------------
UnloadModel(model); // Unload model
ClearDroppedFiles(); // Clear internal buffers
CloseWindow(); // Close window and OpenGL context
//--------------------------------------------------------------------------------------
return 0;
}

Binary file not shown.

Before

Width:  |  Height:  |  Size: 95 KiB

View File

@ -89,7 +89,10 @@ int main(void)
// De-Initialization // De-Initialization
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
UnloadModel(skybox); // Unload skybox model (and textures) UnloadShader(skybox.materials[0].shader);
UnloadTexture(skybox.materials[0].maps[MAP_CUBEMAP].texture);
UnloadModel(skybox); // Unload skybox model
CloseWindow(); // Close window and OpenGL context CloseWindow(); // Close window and OpenGL context
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------

View File

@ -92,6 +92,7 @@ int main(void)
while (pitchOffset < -180) pitchOffset += 360; while (pitchOffset < -180) pitchOffset += 360;
pitchOffset *= 10; pitchOffset *= 10;
/* matrix transform done with multiplication to combine rotations
Matrix transform = MatrixIdentity(); Matrix transform = MatrixIdentity();
transform = MatrixMultiply(transform, MatrixRotateZ(DEG2RAD*roll)); transform = MatrixMultiply(transform, MatrixRotateZ(DEG2RAD*roll));
@ -99,8 +100,11 @@ int main(void)
transform = MatrixMultiply(transform, MatrixRotateY(DEG2RAD*yaw)); transform = MatrixMultiply(transform, MatrixRotateY(DEG2RAD*yaw));
model.transform = transform; model.transform = transform;
//---------------------------------------------------------------------------------- */
// matrix created from multiple axes at once
model.transform = MatrixRotateXYZ((Vector3){DEG2RAD*pitch,DEG2RAD*yaw,DEG2RAD*roll});
//----------------------------------------------------------------------------------
// Draw // Draw
//---------------------------------------------------------------------------------- //----------------------------------------------------------------------------------
BeginDrawing(); BeginDrawing();
@ -165,6 +169,7 @@ int main(void)
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
// Unload all loaded data // Unload all loaded data
UnloadTexture(model.materials[0].maps[MAP_DIFFUSE].texture);
UnloadModel(model); UnloadModel(model);
UnloadRenderTexture(framebuffer); UnloadRenderTexture(framebuffer);

Binary file not shown.

View File

@ -0,0 +1,219 @@
{
"asset": {
"generator": "COLLADA2GLTF",
"version": "2.0"
},
"scene": 0,
"scenes": [
{
"nodes": [
0
]
}
],
"nodes": [
{
"children": [
2,
1
],
"matrix": [
0.009999999776482582,
0.0,
0.0,
0.0,
0.0,
0.009999999776482582,
0.0,
0.0,
0.0,
0.0,
0.009999999776482582,
0.0,
0.0,
0.0,
0.0,
1.0
]
},
{
"matrix": [
-0.7289686799049377,
0.0,
-0.6845470666885376,
0.0,
-0.4252049028873444,
0.7836934328079224,
0.4527972936630249,
0.0,
0.5364750623703003,
0.6211478114128113,
-0.571287989616394,
0.0,
400.1130065917969,
463.2640075683594,
-431.0780334472656,
1.0
],
"camera": 0
},
{
"mesh": 0
}
],
"cameras": [
{
"perspective": {
"aspectRatio": 1.5,
"yfov": 0.6605925559997559,
"zfar": 10000.0,
"znear": 1.0
},
"type": "perspective"
}
],
"meshes": [
{
"primitives": [
{
"attributes": {
"NORMAL": 1,
"POSITION": 2,
"TEXCOORD_0": 3
},
"indices": 0,
"mode": 4,
"material": 0
}
],
"name": "LOD3spShape"
}
],
"accessors": [
{
"bufferView": 0,
"byteOffset": 0,
"componentType": 5123,
"count": 12636,
"max": [
2398
],
"min": [
0
],
"type": "SCALAR"
},
{
"bufferView": 1,
"byteOffset": 0,
"componentType": 5126,
"count": 2399,
"max": [
0.9995989799499512,
0.999580979347229,
0.9984359741210938
],
"min": [
-0.9990839958190918,
-1.0,
-0.9998319745063782
],
"type": "VEC3"
},
{
"bufferView": 1,
"byteOffset": 28788,
"componentType": 5126,
"count": 2399,
"max": [
96.17990112304688,
163.97000122070313,
53.92519760131836
],
"min": [
-69.29850006103516,
9.929369926452637,
-61.32819747924805
],
"type": "VEC3"
},
{
"bufferView": 2,
"byteOffset": 0,
"componentType": 5126,
"count": 2399,
"max": [
0.9833459854125976,
0.9800369739532472
],
"min": [
0.026409000158309938,
0.01996302604675293
],
"type": "VEC2"
}
],
"materials": [
{
"pbrMetallicRoughness": {
"baseColorTexture": {
"index": 0
},
"metallicFactor": 0.0
},
"emissiveFactor": [
0.0,
0.0,
0.0
],
"name": "blinn3-fx"
}
],
"textures": [
{
"sampler": 0,
"source": 0
}
],
"images": [
{
"uri": "DuckCM.png"
}
],
"samplers": [
{
"magFilter": 9729,
"minFilter": 9986,
"wrapS": 10497,
"wrapT": 10497
}
],
"bufferViews": [
{
"buffer": 0,
"byteOffset": 76768,
"byteLength": 25272,
"target": 34963
},
{
"buffer": 0,
"byteOffset": 0,
"byteLength": 57576,
"byteStride": 12,
"target": 34962
},
{
"buffer": 0,
"byteOffset": 57576,
"byteLength": 19192,
"byteStride": 8,
"target": 34962
}
],
"buffers": [
{
"byteLength": 102040,
"uri": "Duck0.bin"
}
]
}

Binary file not shown.

Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB

View File

@ -0,0 +1,14 @@
# Duck
## Screenshot
![screenshot](screenshot/screenshot.png)
## License Information
Copyright 2006 Sony Computer Entertainment Inc.
Licensed under the SCEA Shared Source License, Version 1.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at:
http://research.scea.com/scea_shared_source_license.html
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Binary file not shown.

Before

Width:  |  Height:  |  Size: 364 KiB

After

Width:  |  Height:  |  Size: 295 KiB

View File

@ -73,6 +73,8 @@ vec3 fresnelSchlick(float cosTheta, vec3 F0);
vec3 fresnelSchlickRoughness(float cosTheta, vec3 F0, float roughness); vec3 fresnelSchlickRoughness(float cosTheta, vec3 F0, float roughness);
vec2 ParallaxMapping(vec2 texCoords, vec3 viewDir); vec2 ParallaxMapping(vec2 texCoords, vec3 viewDir);
// WARNING: There is some weird behaviour with this function, always returns black!
// Yes, I even tried: return texture(property.sampler, texCoord).rgb;
vec3 ComputeMaterialProperty(MaterialProperty property) vec3 ComputeMaterialProperty(MaterialProperty property)
{ {
vec3 result = vec3(0.0, 0.0, 0.0); vec3 result = vec3(0.0, 0.0, 0.0);
@ -187,17 +189,17 @@ void main()
else texCoord = fragTexCoord; // Use default texture coordinates else texCoord = fragTexCoord; // Use default texture coordinates
// Fetch material values from texture sampler or color attributes // Fetch material values from texture sampler or color attributes
vec3 color = ComputeMaterialProperty(albedo); vec3 color = texture(albedo.sampler, texCoord).rgb; //ComputeMaterialProperty(albedo);
vec3 metal = ComputeMaterialProperty(metalness); vec3 metal = texture(metalness.sampler, texCoord).rgb; //ComputeMaterialProperty(metalness);
vec3 rough = ComputeMaterialProperty(roughness); vec3 rough = texture(roughness.sampler, texCoord).rgb; //ComputeMaterialProperty(roughness);
vec3 emiss = ComputeMaterialProperty(emission); vec3 emiss = texture(emission.sampler, texCoord).rgb; //ComputeMaterialProperty(emission);
vec3 ao = ComputeMaterialProperty(occlusion); vec3 ao = texture(occlusion.sampler, texCoord).rgb; //ComputeMaterialProperty(occlusion);
// Check if normal mapping is enabled // Check if normal mapping is enabled
if (normals.useSampler == 1) if (normals.useSampler == 1)
{ {
// Fetch normal map color and transform lighting values to tangent space // Fetch normal map color and transform lighting values to tangent space
normal = ComputeMaterialProperty(normals); normal = texture(normals.sampler, texCoord).rgb; //ComputeMaterialProperty(normals);
normal = normalize(normal*2.0 - 1.0); normal = normalize(normal*2.0 - 1.0);
normal = normalize(normal*TBN); normal = normalize(normal*TBN);

View File

@ -33,6 +33,8 @@
#ifndef RLIGHTS_H #ifndef RLIGHTS_H
#define RLIGHTS_H #define RLIGHTS_H
#include "raylib.h"
//---------------------------------------------------------------------------------- //----------------------------------------------------------------------------------
// Defines and Macros // Defines and Macros
//---------------------------------------------------------------------------------- //----------------------------------------------------------------------------------
@ -65,15 +67,10 @@ typedef struct {
extern "C" { // Prevents name mangling of functions extern "C" { // Prevents name mangling of functions
#endif #endif
//----------------------------------------------------------------------------------
// Global Variables Definition
//----------------------------------------------------------------------------------
int lightsCount = 0; // Current amount of created lights
//---------------------------------------------------------------------------------- //----------------------------------------------------------------------------------
// Module Functions Declaration // Module Functions Declaration
//---------------------------------------------------------------------------------- //----------------------------------------------------------------------------------
Light CreateLight(int type, Vector3 pos, Vector3 targ, Color color, Shader shader); // Defines a light and get locations from PBR shader void CreateLight(int type, Vector3 pos, Vector3 targ, Color color, Shader shader); // Defines a light and get locations from PBR shader
void UpdateLightValues(Shader shader, Light light); // Send to PBR shader light values void UpdateLightValues(Shader shader, Light light); // Send to PBR shader light values
#ifdef __cplusplus #ifdef __cplusplus
@ -106,7 +103,8 @@ void UpdateLightValues(Shader shader, Light light);
//---------------------------------------------------------------------------------- //----------------------------------------------------------------------------------
// Global Variables Definition // Global Variables Definition
//---------------------------------------------------------------------------------- //----------------------------------------------------------------------------------
// ... static Light lights[MAX_LIGHTS] = { 0 };
static int lightsCount = 0; // Current amount of created lights
//---------------------------------------------------------------------------------- //----------------------------------------------------------------------------------
// Module specific Functions Declaration // Module specific Functions Declaration
@ -118,7 +116,7 @@ void UpdateLightValues(Shader shader, Light light);
//---------------------------------------------------------------------------------- //----------------------------------------------------------------------------------
// Defines a light and get locations from PBR shader // Defines a light and get locations from PBR shader
Light CreateLight(int type, Vector3 pos, Vector3 targ, Color color, Shader shader) void CreateLight(int type, Vector3 pos, Vector3 targ, Color color, Shader shader)
{ {
Light light = { 0 }; Light light = { 0 };
@ -148,10 +146,10 @@ Light CreateLight(int type, Vector3 pos, Vector3 targ, Color color, Shader shade
light.colorLoc = GetShaderLocation(shader, colorName); light.colorLoc = GetShaderLocation(shader, colorName);
UpdateLightValues(shader, light); UpdateLightValues(shader, light);
lights[lightsCount] = light;
lightsCount++; lightsCount++;
} }
return light;
} }
// Send to PBR shader light values // Send to PBR shader light values

View File

@ -120,6 +120,10 @@ int main(void)
// De-Initialization // De-Initialization
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
DestroyPhysicsBody(circleA);
DestroyPhysicsBody(circleB);
DestroyPhysicsBody(circleC);
DestroyPhysicsBody(floor);
ClosePhysics(); // Unitialize physics ClosePhysics(); // Unitialize physics
CloseWindow(); // Close window and OpenGL context CloseWindow(); // Close window and OpenGL context

Binary file not shown.

After

Width:  |  Height:  |  Size: 73 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 568 KiB

View File

@ -8,8 +8,6 @@ varying vec4 fragColor;
uniform vec3 viewEye; uniform vec3 viewEye;
uniform vec3 viewCenter; uniform vec3 viewCenter;
uniform vec3 viewUp;
uniform float deltaTime;
uniform float runTime; uniform float runTime;
uniform vec2 resolution; uniform vec2 resolution;

View File

@ -0,0 +1,99 @@
#version 330
// Input vertex attributes (from vertex shader)
in vec2 fragTexCoord;
in vec4 fragColor;
in vec3 fragPosition;
in vec3 fragNormal;
// Input uniform values
uniform sampler2D texture0;
uniform vec4 colDiffuse;
// Output fragment color
out vec4 finalColor;
// NOTE: Add here your custom variables
#define MAX_LIGHTS 4
#define LIGHT_DIRECTIONAL 0
#define LIGHT_POINT 1
struct MaterialProperty {
vec3 color;
int useSampler;
sampler2D sampler;
};
struct Light {
int enabled;
int type;
vec3 position;
vec3 target;
vec4 color;
};
// Input lighting values
uniform Light lights[MAX_LIGHTS];
uniform vec4 ambient;
uniform vec3 viewPos;
uniform float fogDensity;
void main()
{
// Texel color fetching from texture sampler
vec4 texelColor = texture(texture0, fragTexCoord);
vec3 lightDot = vec3(0.0);
vec3 normal = normalize(fragNormal);
vec3 viewD = normalize(viewPos - fragPosition);
vec3 specular = vec3(0.0);
// NOTE: Implement here your fragment shader code
for (int i = 0; i < MAX_LIGHTS; i++)
{
if (lights[i].enabled == 1)
{
vec3 light = vec3(0.0);
if (lights[i].type == LIGHT_DIRECTIONAL) {
light = -normalize(lights[i].target - lights[i].position);
}
if (lights[i].type == LIGHT_POINT) {
light = normalize(lights[i].position - fragPosition);
}
float NdotL = max(dot(normal, light), 0.0);
lightDot += lights[i].color.rgb * NdotL;
float specCo = 0.0;
if(NdotL > 0.0)
specCo = pow(max(0.0, dot(viewD, reflect(-(light), normal))), 16);//16 =shine
specular += specCo;
}
}
finalColor = (texelColor * ((colDiffuse+vec4(specular,1)) * vec4(lightDot, 1.0)));
finalColor += texelColor * (ambient/10.0);
// Gamma correction
finalColor = pow(finalColor, vec4(1.0/2.2));
// Fog calculation
float dist = length(viewPos - fragPosition);
// these could be parameters...
const vec4 fogColor = vec4(0.5, 0.5, 0.5, 1.0);
//const float fogDensity = 0.16;
// Exponential fog
float fogFactor = 1.0/exp((dist*fogDensity)*(dist*fogDensity));
// Linear fog (less nice)
//const float fogStart = 2.0;
//const float fogEnd = 10.0;
//float fogFactor = (fogEnd - dist)/(fogEnd - fogStart);
fogFactor = clamp(fogFactor, 0.0, 1.0);
finalColor = mix(fogColor, finalColor, fogFactor);
}

View File

@ -0,0 +1,32 @@
#version 330
// Input vertex attributes
in vec3 vertexPosition;
in vec2 vertexTexCoord;
in vec3 vertexNormal;
in vec4 vertexColor;
// Input uniform values
uniform mat4 mvp;
uniform mat4 matModel;
// Output vertex attributes (to fragment shader)
out vec2 fragTexCoord;
out vec4 fragColor;
out vec3 fragPosition;
out vec3 fragNormal;
// NOTE: Add here your custom variables
void main()
{
// Send vertex attributes to fragment shader
fragTexCoord = vertexTexCoord;
fragColor = vertexColor;
fragPosition = vec3(matModel*vec4(vertexPosition, 1.0f));
mat3 normalMatrix = transpose(inverse(mat3(matModel)));
fragNormal = normalize(normalMatrix*vertexNormal);
// Calculate final vertex position
gl_Position = mvp*vec4(vertexPosition, 1.0);
}

View File

@ -0,0 +1,21 @@
#version 330
// Input vertex attributes (from vertex shader)
in vec2 fragTexCoord;
// Input uniform values
uniform sampler2D texture0;
uniform sampler2D mask;
uniform int frame;
// Output fragment color
out vec4 finalColor;
void main()
{
vec4 maskColour = texture(mask, fragTexCoord+vec2(sin(-frame/150.0)/10.0,cos(-frame/170.0)/10.0));
if (maskColour.r < 0.25) discard;
vec4 texelColor = texture(texture0, fragTexCoord+vec2(sin(frame/90.0)/8.0,cos(frame/60.0)/8.0));
finalColor = texelColor * maskColour;
}

View File

@ -0,0 +1,21 @@
#version 330
// Input vertex attributes
in vec3 vertexPosition;
in vec2 vertexTexCoord;
// Input uniform values
uniform mat4 mvp;
uniform mat4 matModel;
// Output vertex attributes (to fragment shader)
out vec2 fragTexCoord;
void main()
{
// Send vertex attributes to fragment shader
fragTexCoord = vertexTexCoord;
// Calculate final vertex position
gl_Position = mvp*vec4(vertexPosition, 1.0);
}

View File

@ -9,8 +9,6 @@ out vec4 finalColor;
uniform vec3 viewEye; uniform vec3 viewEye;
uniform vec3 viewCenter; uniform vec3 viewCenter;
uniform vec3 viewUp;
uniform float deltaTime;
uniform float runTime; uniform float runTime;
uniform vec2 resolution; uniform vec2 resolution;

View File

@ -0,0 +1,153 @@
/*******************************************************************************************
*
* raylib [shaders] example - fog
*
* NOTE: This example requires raylib OpenGL 3.3 or ES2 versions for shaders support,
* OpenGL 1.1 does not support shaders, recompile raylib to OpenGL 3.3 version.
*
* NOTE: Shaders used in this example are #version 330 (OpenGL 3.3).
*
* This example has been created using raylib 2.5 (www.raylib.com)
* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details)
*
* Example contributed by Chris Camacho (@codifies) and reviewed by Ramon Santamaria (@raysan5)
*
* Chris Camacho (@codifies - http://bedroomcoders.co.uk/) notes:
*
* This is based on the PBR lighting example, but greatly simplified to aid learning...
* actually there is very little of the PBR example left!
* When I first looked at the bewildering complexity of the PBR example I feared
* I would never understand how I could do simple lighting with raylib however its
* a testement to the authors of raylib (including rlights.h) that the example
* came together fairly quickly.
*
* Copyright (c) 2019 Chris Camacho (@codifies) and Ramon Santamaria (@raysan5)
*
********************************************************************************************/
#include "raylib.h"
#include "raymath.h"
#define RLIGHTS_IMPLEMENTATION
#include "rlights.h"
int main(void)
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
SetConfigFlags(FLAG_MSAA_4X_HINT); // Enable Multi Sampling Anti Aliasing 4x (if available)
InitWindow(screenWidth, screenHeight, "raylib [shaders] example - fog");
// Define the camera to look into our 3d world
Camera camera = {
(Vector3){ 2.0f, 2.0f, 6.0f }, // position
(Vector3){ 0.0f, 0.5f, 0.0f }, // target
(Vector3){ 0.0f, 1.0f, 0.0f }, // up
45.0f, CAMERA_PERSPECTIVE }; // fov, type
// Load models and texture
Model modelA = LoadModelFromMesh(GenMeshTorus(0.4f, 1.0f, 16, 32));
Model modelB = LoadModelFromMesh(GenMeshCube(1.0f, 1.0f, 1.0f));
Model modelC = LoadModelFromMesh(GenMeshSphere(0.5f, 32, 32));
Texture texture = LoadTexture("resources/texel_checker.png");
// Assign texture to default model material
modelA.materials[0].maps[MAP_DIFFUSE].texture = texture;
modelB.materials[0].maps[MAP_DIFFUSE].texture = texture;
modelC.materials[0].maps[MAP_DIFFUSE].texture = texture;
// Load shader and set up some uniforms
Shader shader = LoadShader("resources/shaders/glsl330/fog.vs", "resources/shaders/glsl330/fog.fs");
shader.locs[LOC_MATRIX_MODEL] = GetShaderLocation(shader, "matModel");
shader.locs[LOC_VECTOR_VIEW] = GetShaderLocation(shader, "viewPos");
// Ambient light level
int ambientLoc = GetShaderLocation(shader, "ambient");
SetShaderValue(shader, ambientLoc, (float[4]){ 0.2f, 0.2f, 0.2f, 1.0f }, UNIFORM_VEC4);
float fogDensity = 0.15f;
int fogDensityLoc = GetShaderLocation(shader, "fogDensity");
SetShaderValue(shader, fogDensityLoc, &fogDensity, UNIFORM_FLOAT);
// NOTE: All models share the same shader
modelA.materials[0].shader = shader;
modelB.materials[0].shader = shader;
modelC.materials[0].shader = shader;
// Using just 1 point lights
CreateLight(LIGHT_POINT, (Vector3){ 0, 2, 6 }, Vector3Zero(), WHITE, shader);
SetCameraMode(camera, CAMERA_ORBITAL); // Set an orbital camera mode
SetTargetFPS(60); // Set our game to run at 60 frames-per-second
//--------------------------------------------------------------------------------------
// Main game loop
while (!WindowShouldClose()) // Detect window close button or ESC key
{
// Update
//----------------------------------------------------------------------------------
UpdateCamera(&camera); // Update camera
if (IsKeyDown(KEY_UP))
{
fogDensity += 0.001;
if (fogDensity > 1.0) fogDensity = 1.0;
}
if (IsKeyDown(KEY_DOWN))
{
fogDensity -= 0.001;
if (fogDensity < 0.0) fogDensity = 0.0;
}
SetShaderValue(shader, fogDensityLoc, &fogDensity, UNIFORM_FLOAT);
// Rotate the torus
modelA.transform = MatrixMultiply(modelA.transform, MatrixRotateX(-0.025));
modelA.transform = MatrixMultiply(modelA.transform, MatrixRotateZ(0.012));
// Update the light shader with the camera view position
SetShaderValue(shader, shader.locs[LOC_VECTOR_VIEW], &camera.position.x, UNIFORM_VEC3);
//----------------------------------------------------------------------------------
// Draw
//----------------------------------------------------------------------------------
BeginDrawing();
ClearBackground(GRAY);
BeginMode3D(camera);
// Draw the three models
DrawModel(modelA, Vector3Zero(), 1.0f, WHITE);
DrawModel(modelB, (Vector3){ -2.6, 0, 0 }, 1.0f, WHITE);
DrawModel(modelC, (Vector3){ 2.6, 0, 0 }, 1.0f, WHITE);
for (int i = -20; i < 20; i += 2) DrawModel(modelA,(Vector3){ i, 0, 2 }, 1.0f, WHITE);
EndMode3D();
DrawText(TextFormat("Use KEY_UP/KEY_DOWN to change fog density [%.2f]", fogDensity), 10, 10, 20, RAYWHITE);
EndDrawing();
//----------------------------------------------------------------------------------
}
// De-Initialization
//--------------------------------------------------------------------------------------
UnloadModel(modelA); // Unload the model A
UnloadModel(modelB); // Unload the model B
UnloadModel(modelC); // Unload the model C
UnloadTexture(texture); // Unload the texture
UnloadShader(shader); // Unload shader
CloseWindow(); // Close window and OpenGL context
//--------------------------------------------------------------------------------------
return 0;
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 80 KiB

View File

@ -28,9 +28,10 @@ int main(void)
{ {
// Initialization // Initialization
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
const int screenWidth = 800; int screenWidth = 800;
const int screenHeight = 450; int screenHeight = 450;
SetConfigFlags(FLAG_WINDOW_RESIZABLE);
InitWindow(screenWidth, screenHeight, "raylib [shaders] example - raymarching shapes"); InitWindow(screenWidth, screenHeight, "raylib [shaders] example - raymarching shapes");
Camera camera = { 0 }; Camera camera = { 0 };
@ -48,12 +49,10 @@ int main(void)
// Get shader locations for required uniforms // Get shader locations for required uniforms
int viewEyeLoc = GetShaderLocation(shader, "viewEye"); int viewEyeLoc = GetShaderLocation(shader, "viewEye");
int viewCenterLoc = GetShaderLocation(shader, "viewCenter"); int viewCenterLoc = GetShaderLocation(shader, "viewCenter");
int viewUpLoc = GetShaderLocation(shader, "viewUp");
int deltaTimeLoc = GetShaderLocation(shader, "deltaTime");
int runTimeLoc = GetShaderLocation(shader, "runTime"); int runTimeLoc = GetShaderLocation(shader, "runTime");
int resolutionLoc = GetShaderLocation(shader, "resolution"); int resolutionLoc = GetShaderLocation(shader, "resolution");
float resolution[2] = { screenWidth, screenHeight }; float resolution[2] = { (float)screenWidth, (float)screenHeight };
SetShaderValue(shader, resolutionLoc, resolution, UNIFORM_VEC2); SetShaderValue(shader, resolutionLoc, resolution, UNIFORM_VEC2);
float runTime = 0.0f; float runTime = 0.0f;
@ -64,13 +63,22 @@ int main(void)
// Main game loop // Main game loop
while (!WindowShouldClose()) // Detect window close button or ESC key while (!WindowShouldClose()) // Detect window close button or ESC key
{ {
// Check if screen is resized
//----------------------------------------------------------------------------------
if(IsWindowResized())
{
screenWidth = GetScreenWidth();
screenHeight = GetScreenHeight();
float resolution[2] = { (float)screenWidth, (float)screenHeight };
SetShaderValue(shader, resolutionLoc, resolution, UNIFORM_VEC2);
}
// Update // Update
//---------------------------------------------------------------------------------- //----------------------------------------------------------------------------------
UpdateCamera(&camera); // Update camera UpdateCamera(&camera); // Update camera
float cameraPos[3] = { camera.position.x, camera.position.y, camera.position.z }; float cameraPos[3] = { camera.position.x, camera.position.y, camera.position.z };
float cameraTarget[3] = { camera.target.x, camera.target.y, camera.target.z }; float cameraTarget[3] = { camera.target.x, camera.target.y, camera.target.z };
float cameraUp[3] = { camera.up.x, camera.up.y, camera.up.z };
float deltaTime = GetFrameTime(); float deltaTime = GetFrameTime();
runTime += deltaTime; runTime += deltaTime;
@ -78,8 +86,6 @@ int main(void)
// Set shader required uniform values // Set shader required uniform values
SetShaderValue(shader, viewEyeLoc, cameraPos, UNIFORM_VEC3); SetShaderValue(shader, viewEyeLoc, cameraPos, UNIFORM_VEC3);
SetShaderValue(shader, viewCenterLoc, cameraTarget, UNIFORM_VEC3); SetShaderValue(shader, viewCenterLoc, cameraTarget, UNIFORM_VEC3);
SetShaderValue(shader, viewUpLoc, cameraUp, UNIFORM_VEC3);
SetShaderValue(shader, deltaTimeLoc, &deltaTime, UNIFORM_FLOAT);
SetShaderValue(shader, runTimeLoc, &runTime, UNIFORM_FLOAT); SetShaderValue(shader, runTimeLoc, &runTime, UNIFORM_FLOAT);
//---------------------------------------------------------------------------------- //----------------------------------------------------------------------------------
@ -95,7 +101,7 @@ int main(void)
DrawRectangle(0, 0, screenWidth, screenHeight, WHITE); DrawRectangle(0, 0, screenWidth, screenHeight, WHITE);
EndShaderMode(); EndShaderMode();
DrawText("(c) Raymarching shader by Iñigo Quilez. MIT License.", screenWidth - 280, screenHeight - 20, 10, GRAY); DrawText("(c) Raymarching shader by Iñigo Quilez. MIT License.", screenWidth - 280, screenHeight - 20, 10, BLACK);
EndDrawing(); EndDrawing();
//---------------------------------------------------------------------------------- //----------------------------------------------------------------------------------

View File

@ -0,0 +1,139 @@
/*******************************************************************************************
*
* raylib [shaders] example - Simple shader mask
*
* This example has been created using raylib 2.5 (www.raylib.com)
* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details)
*
* Example contributed by Chris Camacho (@codifies) and reviewed by Ramon Santamaria (@raysan5)
*
* Copyright (c) 2019 Chris Camacho (@codifies) and Ramon Santamaria (@raysan5)
*
********************************************************************************************
*
* After a model is loaded it has a default material, this material can be
* modified in place rather than creating one from scratch...
* While all of the maps have particular names, they can be used for any purpose
* except for three maps that are applied as cubic maps (see below)
*
********************************************************************************************/
#include "raylib.h"
#include "raymath.h"
int main(void)
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib - simple shader mask");
// Define the camera to look into our 3d world
Camera camera = { 0 };
camera.position = (Vector3){ 0.0f, 1.0f, 2.0f };
camera.target = (Vector3){ 0.0f, 0.0f, 0.0f };
camera.up = (Vector3){ 0.0f, 1.0f, 0.0f };
camera.fovy = 45.0f;
camera.type = CAMERA_PERSPECTIVE;
// Define our three models to show the shader on
Mesh torus = GenMeshTorus(.3, 1, 16, 32);
Model model1 = LoadModelFromMesh(torus);
Mesh cube = GenMeshCube(.8,.8,.8);
Model model2 = LoadModelFromMesh(cube);
// Generate model to be shaded just to see the gaps in the other two
Mesh sphere = GenMeshSphere(1, 16, 16);
Model model3 = LoadModelFromMesh(sphere);
// Load the shader
Shader shader = LoadShader("resources/shaders/glsl330/mask.vs", "resources/shaders/glsl330/mask.fs");
// Load and apply the diffuse texture (colour map)
Texture texDiffuse = LoadTexture("resources/plasma.png");
model1.materials[0].maps[MAP_DIFFUSE].texture = texDiffuse;
model2.materials[0].maps[MAP_DIFFUSE].texture = texDiffuse;
// Using MAP_EMISSION as a spare slot to use for 2nd texture
// NOTE: Don't use MAP_IRRADIANCE, MAP_PREFILTER or MAP_CUBEMAP
// as they are bound as cube maps
Texture texMask = LoadTexture("resources/mask.png");
model1.materials[0].maps[MAP_EMISSION].texture = texMask;
model2.materials[0].maps[MAP_EMISSION].texture = texMask;
shader.locs[LOC_MAP_EMISSION] = GetShaderLocation(shader, "mask");
// Frame is incremented each frame to animate the shader
int shaderFrame = GetShaderLocation(shader, "framesCounter");
// Apply the shader to the two models
model1.materials[0].shader = shader;
model2.materials[0].shader = shader;
int framesCounter = 0;
Vector3 rotation = { 0 }; // Model rotation angles
SetTargetFPS(60); // Set to run at 60 frames-per-second
//--------------------------------------------------------------------------------------
// Main game loop
while (!WindowShouldClose()) // Detect window close button or ESC key
{
// Update
//----------------------------------------------------------------------------------
framesCounter++;
rotation.x += 0.01f;
rotation.y += 0.005f;
rotation.z -= 0.0025f;
// Send frames counter to shader for animation
SetShaderValue(shader, shaderFrame, &framesCounter, UNIFORM_INT);
// Rotate one of the models
model1.transform = MatrixRotateXYZ(rotation);
UpdateCamera(&camera);
//----------------------------------------------------------------------------------
// Draw
//----------------------------------------------------------------------------------
BeginDrawing();
ClearBackground(DARKBLUE);
BeginMode3D(camera);
DrawModel(model1, (Vector3){0.5,0,0}, 1, WHITE);
DrawModelEx(model2, (Vector3){-.5,0,0}, (Vector3){1,1,0}, 50, (Vector3){1,1,1}, WHITE);
DrawModel(model3,(Vector3){0,0,-1.5}, 1, WHITE);
DrawGrid(10, 1.0f); // Draw a grid
EndMode3D();
DrawRectangle(16, 698, MeasureText(FormatText("Frame: %i", framesCounter), 20) + 8, 42, BLUE);
DrawText(FormatText("Frame: %i", framesCounter), 20, 700, 20, WHITE);
DrawFPS(10, 10);
EndDrawing();
//----------------------------------------------------------------------------------
}
// De-Initialization
//--------------------------------------------------------------------------------------
UnloadModel(model1);
UnloadModel(model2);
UnloadModel(model3);
UnloadTexture(texDiffuse); // Unload default diffuse texture
UnloadTexture(texMask); // Unload texture mask
UnloadShader(shader); // Unload shader
CloseWindow(); // Close window and OpenGL context
//--------------------------------------------------------------------------------------
return 0;
}

View File

@ -1,6 +1,10 @@
/******************************************************************************************* /*******************************************************************************************
* *
* raylib [text] example - TTF loading and usage * raylib [text] example - Font filters
*
* After font loading, font texture atlas filter could be configured for a softer
* display of the font when scaling it to different sizes, that way, it's not required
* to generate multiple fonts at multiple sizes (as long as the scaling is not very different)
* *
* This example has been created using raylib 1.3.0 (www.raylib.com) * This example has been created using raylib 1.3.0 (www.raylib.com)
* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details) * raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details)
@ -18,9 +22,9 @@ int main(void)
const int screenWidth = 800; const int screenWidth = 800;
const int screenHeight = 450; const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [text] example - ttf loading"); InitWindow(screenWidth, screenHeight, "raylib [text] example - font filters");
const char msg[50] = "TTF Font"; const char msg[50] = "Loaded Font";
// NOTE: Textures/Fonts MUST be loaded after Window initialization (OpenGL context is required) // NOTE: Textures/Fonts MUST be loaded after Window initialization (OpenGL context is required)
@ -78,7 +82,8 @@ int main(void)
int count = 0; int count = 0;
char **droppedFiles = GetDroppedFiles(&count); char **droppedFiles = GetDroppedFiles(&count);
if (count == 1) // Only support one ttf file dropped // NOTE: We only support first ttf file dropped
if (IsFileExtension(droppedFiles[0], ".ttf"))
{ {
UnloadFont(font); UnloadFont(font);
font = LoadFontEx(droppedFiles[0], fontSize, 0, 0); font = LoadFontEx(droppedFiles[0], fontSize, 0, 0);

Binary file not shown.

After

Width:  |  Height:  |  Size: 59 KiB

View File

@ -1,11 +1,20 @@
/******************************************************************************************* /*******************************************************************************************
* *
* raylib [text] example - BMFont and TTF Fonts loading * raylib [text] example - Font loading
* *
* This example has been created using raylib 1.4 (www.raylib.com) * raylib can load fonts from multiple file formats:
*
* - TTF/OTF > Sprite font atlas is generated on loading, user can configure
* some of the generation parameters (size, characters to include)
* - BMFonts > Angel code font fileformat, sprite font image must be provided
* together with the .fnt file, font generation cna not be configured
* - XNA Spritefont > Sprite font image, following XNA Spritefont conventions,
* Characters in image must follow some spacing and order rules
*
* This example has been created using raylib 2.6 (www.raylib.com)
* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details) * raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details)
* *
* Copyright (c) 2016 Ramon Santamaria (@raysan5) * Copyright (c) 2016-2019 Ramon Santamaria (@raysan5)
* *
********************************************************************************************/ ********************************************************************************************/
@ -18,7 +27,7 @@ int main(void)
const int screenWidth = 800; const int screenWidth = 800;
const int screenHeight = 450; const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [text] example - bmfont and ttf sprite fonts loading"); InitWindow(screenWidth, screenHeight, "raylib [text] example - font loading");
// Define characters to draw // Define characters to draw
// NOTE: raylib supports UTF-8 encoding, following list is actually codified as UTF8 internally // NOTE: raylib supports UTF-8 encoding, following list is actually codified as UTF8 internally

View File

Before

Width:  |  Height:  |  Size: 20 KiB

After

Width:  |  Height:  |  Size: 20 KiB

View File

@ -1,6 +1,15 @@
/******************************************************************************************* /*******************************************************************************************
* *
* raylib [text] example - Font loading and usage * raylib [text] example - Sprite font loading
*
* Loaded sprite fonts have been generated following XNA SpriteFont conventions:
* - Characters must be ordered starting with character 32 (Space)
* - Every character must be contained within the same Rectangle height
* - Every character and every line must be separated the same distance
* - Rectangles must be defined by a MAGENTA color background
*
* If following this constraints, a font can be provided just by an image,
* this is quite handy to avoid additional information files (like BMFonts use).
* *
* This example has been created using raylib 1.0 (www.raylib.com) * This example has been created using raylib 1.0 (www.raylib.com)
* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details) * raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details)
@ -18,7 +27,7 @@ int main(void)
const int screenWidth = 800; const int screenWidth = 800;
const int screenHeight = 450; const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [text] example - sprite fonts usage"); InitWindow(screenWidth, screenHeight, "raylib [text] example - sprite font loading");
const char msg1[50] = "THIS IS A custom SPRITE FONT..."; const char msg1[50] = "THIS IS A custom SPRITE FONT...";
const char msg2[50] = "...and this is ANOTHER CUSTOM font..."; const char msg2[50] = "...and this is ANOTHER CUSTOM font...";

View File

Before

Width:  |  Height:  |  Size: 19 KiB

After

Width:  |  Height:  |  Size: 19 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 54 KiB

View File

@ -271,7 +271,7 @@ int main(int argc, char **argv)
// Draw the info text below the main message // Draw the info text below the main message
int size = strlen(messages[message].text); int size = strlen(messages[message].text);
unsigned int len = TextCountCodepoints(messages[message].text); int len = GetCodepointsCount(messages[message].text);
const char *info = TextFormat("%s %u characters %i bytes", messages[message].language, len, size); const char *info = TextFormat("%s %u characters %i bytes", messages[message].language, len, size);
sz = MeasureTextEx(GetFontDefault(), info, 10, 1.0f); sz = MeasureTextEx(GetFontDefault(), info, 10, 1.0f);
Vector2 pos = { textRect.x + textRect.width - sz.x, msgRect.y + msgRect.height - sz.y - 2 }; Vector2 pos = { textRect.x + textRect.width - sz.x, msgRect.y + msgRect.height - sz.y - 2 };

View File

@ -13,7 +13,7 @@
#include <stdlib.h> // Required for: malloc(), free() #include <stdlib.h> // Required for: malloc(), free()
#define MAX_BUNNIES 100000 // 100K bunnies limit #define MAX_BUNNIES 50000 // 50K bunnies limit
// This is the maximum amount of elements (quads) per batch // This is the maximum amount of elements (quads) per batch
// NOTE: This value is defined in [rlgl] module and can be changed there // NOTE: This value is defined in [rlgl] module and can be changed there

View File

@ -1,7 +1,8 @@
cmake_minimum_required(VERSION 3.11) # FetchContent is available in 3.11+ cmake_minimum_required(VERSION 3.11) # FetchContent is available in 3.11+
project(example) project(example)
find_package(raylib 2.0 QUIET) # Let CMake search for a raylib-config.cmake # Set this to the minimal version you want to support
find_package(raylib 2.5 QUIET) # Let CMake search for a raylib-config.cmake
# You could change the QUIET above to REQUIRED and remove this if() clause # You could change the QUIET above to REQUIRED and remove this if() clause
# This part downloads raylib and builds it if it's not installed on your system # This part downloads raylib and builds it if it's not installed on your system

View File

@ -4,14 +4,17 @@ This folder contains raylib templates for some common IDEs.
IDE | Platform | Template type | State IDE | Platform | Template type | State
----| ---------| ------------- | ----- ----| ---------| ------------- | -----
[4coder](http://4coder.net/) | Windows | example compiling | DONE
[Builder](https://wiki.gnome.org/Apps/Builder) | Linux | example compiling | DONE [Builder](https://wiki.gnome.org/Apps/Builder) | Linux | example compiling | DONE
[CMake](https://cmake.org/) | n/a | example compiling and raylib source downloading/building if necessary | DONE [CMake](https://cmake.org/) | n/a | example compiling and raylib source downloading/building if necessary | DONE
[CodeBlocks](http://www.codeblocks.org/) | Linux, Windows | example compiling | DONE [CodeBlocks](http://www.codeblocks.org/) | Linux, Windows | example compiling | DONE
[Geany](https://www.geany.org/) | Linux, Windows | - | INCOMPLETE [Geany](https://www.geany.org/) | Linux, Windows | - | DONE
[KDevelop](https://www.kdevelop.org/) | Linux, Windows, macOS | - | INCOMPLETE [KDevelop](https://www.kdevelop.org/) | Linux, Windows, macOS | - | INCOMPLETE
[Notepad++](https://notepad-plus-plus.org/) | Windows | source/example compiling | DONE [Notepad++](https://notepad-plus-plus.org/) | Windows | source/example compiling | DONE
[Sublime Text](https://www.sublimetext.com/) | Windows, Linux, macOS | source and example | DONE
[VS2015](https://www.visualstudio.com) | Windows | source/example compiling | DONE [VS2015](https://www.visualstudio.com) | Windows | source/example compiling | DONE
[VS2017](https://www.visualstudio.com) | Windows | source/example compiling | DONE [VS2017](https://www.visualstudio.com) | Windows | source/example compiling | DONE
[VSCode](https://code.visualstudio.com/) | Windows, macOS | example compiling | DONE [VSCode](https://code.visualstudio.com/) | Windows, macOS | example compiling | DONE
scripts | Windows, Linux, macOS | source and example | DONE
*New IDEs config files are welcome!* *New IDEs config files are welcome!*

View File

@ -148,27 +148,34 @@ endif
ifeq ($(PLATFORM),PLATFORM_WEB) ifeq ($(PLATFORM),PLATFORM_WEB)
# Emscripten required variables # Emscripten required variables
EMSDK_PATH ?= C:/emsdk EMSDK_PATH ?= C:/emsdk
EMSCRIPTEN_VERSION ?= 1.38.32 EMSCRIPTEN_PATH ?= $(EMSDK_PATH)/fastcomp/emscripten
CLANG_VERSION = e$(EMSCRIPTEN_VERSION)_64bit CLANG_PATH = $(EMSDK_PATH)/fastcomp/bin
PYTHON_VERSION = 2.7.13.1_64bit\python-2.7.13.amd64 PYTHON_PATH = $(EMSDK_PATH)/python/2.7.13.1_64bit/python-2.7.13.amd64
NODE_VERSION = 8.9.1_64bit NODE_PATH = $(EMSDK_PATH)/node/12.9.1_64bit/bin
export PATH = $(EMSDK_PATH);$(EMSDK_PATH)\clang\$(CLANG_VERSION);$(EMSDK_PATH)\node\$(NODE_VERSION)\bin;$(EMSDK_PATH)\python\$(PYTHON_VERSION);$(EMSDK_PATH)\emscripten\$(EMSCRIPTEN_VERSION);C:\raylib\MinGW\bin:$$(PATH) export PATH = $(EMSDK_PATH);$(EMSCRIPTEN_PATH);$(CLANG_PATH);$(NODE_PATH);$(PYTHON_PATH);C:\raylib\MinGW\bin:$$(PATH)
EMSCRIPTEN = $(EMSDK_PATH)\emscripten\$(EMSCRIPTEN_VERSION)
endif endif
ifeq ($(PLATFORM),PLATFORM_ANDROID) ifeq ($(PLATFORM),PLATFORM_ANDROID)
# Android architecture: ARM64 # Android architecture: ARM64
# Starting at 2019 using ARM64 is mandatory for published apps # Starting at 2019 using ARM64 is mandatory for published apps
ANDROID_ARCH ?= ARM ANDROID_ARCH ?= ARM
ANDROID_API_VERSION = 21 ANDROID_API_VERSION = 26
# Android required path variables # Android required path variables
# NOTE: Android NDK is just required to generate the standalone toolchain, # NOTE: Android NDK is just required to generate the standalone toolchain,
# in case is not already provided # in case is not already provided
ifeq ($(OS),Windows_NT)
ANDROID_NDK = C:/android-ndk ANDROID_NDK = C:/android-ndk
else
ANDROID_NDK = /usr/lib/android/ndk
endif
# Android standalone toolchain path # Android standalone toolchain path
ifeq ($(OS),Windows_NT)
ANDROID_TOOLCHAIN = C:/android_toolchain_$(ANDROID_ARCH)_API$(ANDROID_API_VERSION) ANDROID_TOOLCHAIN = C:/android_toolchain_$(ANDROID_ARCH)_API$(ANDROID_API_VERSION)
else
ANDROID_TOOLCHAIN = /usr/lib/android/toolchain_$(ANDROID_ARCH)_API$(ANDROID_API_VERSION)
endif
ifeq ($(ANDROID_ARCH),ARM) ifeq ($(ANDROID_ARCH),ARM)
ANDROID_ARCH_NAME = armeabi-v7a ANDROID_ARCH_NAME = armeabi-v7a
@ -176,6 +183,12 @@ ifeq ($(PLATFORM),PLATFORM_ANDROID)
ifeq ($(ANDROID_ARCH),ARM64) ifeq ($(ANDROID_ARCH),ARM64)
ANDROID_ARCH_NAME = arm64-v8a ANDROID_ARCH_NAME = arm64-v8a
endif endif
ifeq ($(ANDROID_ARCH),x86)
ANDROID_ARCH_NAME = i686
endif
ifeq ($(ANDROID_ARCH),x86_64)
ANDROID_ARCH_NAME = x86_64
endif
endif endif
# Define raylib source code path # Define raylib source code path
@ -242,6 +255,14 @@ ifeq ($(PLATFORM),PLATFORM_ANDROID)
CC = $(ANDROID_TOOLCHAIN)/bin/aarch64-linux-android-clang CC = $(ANDROID_TOOLCHAIN)/bin/aarch64-linux-android-clang
AR = $(ANDROID_TOOLCHAIN)/bin/aarch64-linux-android-ar AR = $(ANDROID_TOOLCHAIN)/bin/aarch64-linux-android-ar
endif endif
ifeq ($(ANDROID_ARCH),x86)
CC = $(ANDROID_TOOLCHAIN)/bin/i686-linux-android$(ANDROID_API_VERSION)-clang
AR = $(ANDROID_TOOLCHAIN)/bin/i686-linux-android-ar
endif
ifeq ($(ANDROID_ARCH),x86_64)
CC = $(ANDROID_TOOLCHAIN)/bin/x86_64-linux-android$(ANDROID_API_VERSION)-clang
AR = $(ANDROID_TOOLCHAIN)/bin/x86_64-linux-android-ar
endif
endif endif
@ -256,7 +277,13 @@ endif
# -D_DEFAULT_SOURCE use with -std=c99 on Linux and PLATFORM_WEB, required for timespec # -D_DEFAULT_SOURCE use with -std=c99 on Linux and PLATFORM_WEB, required for timespec
# -Werror=pointer-arith catch unportable code that does direct arithmetic on void pointers # -Werror=pointer-arith catch unportable code that does direct arithmetic on void pointers
# -fno-strict-aliasing jar_xm.h does shady stuff (breaks strict aliasing) # -fno-strict-aliasing jar_xm.h does shady stuff (breaks strict aliasing)
CFLAGS += -Wall -std=c99 -D_DEFAULT_SOURCE -Wno-missing-braces -Werror=pointer-arith -fno-strict-aliasing CFLAGS += -Wall -D_DEFAULT_SOURCE -Wno-missing-braces -Werror=pointer-arith -fno-strict-aliasing
ifeq ($(PLATFORM), PLATFORM_WEB)
CFLAGS += -std=gnu99
else
CFLAGS += -std=c99
endif
ifeq ($(PLATFORM_OS),LINUX) ifeq ($(PLATFORM_OS),LINUX)
CFLAGS += -fPIC CFLAGS += -fPIC
@ -305,6 +332,12 @@ ifeq ($(PLATFORM),PLATFORM_ANDROID)
ifeq ($(ANDROID_ARCH),ARM64) ifeq ($(ANDROID_ARCH),ARM64)
CFLAGS += -target aarch64 -mfix-cortex-a53-835769 CFLAGS += -target aarch64 -mfix-cortex-a53-835769
endif endif
ifeq ($(ANDROID_ARCH), x86)
CFLAGS += -march=i686
endif
ifeq ($(ANDROID_ARCH), x86_64)
CFLAGS += -march=x86-64
endif
# Compilation functions attributes options # Compilation functions attributes options
CFLAGS += -ffunction-sections -funwind-tables -fstack-protector-strong -fPIE -fPIC CFLAGS += -ffunction-sections -funwind-tables -fstack-protector-strong -fPIE -fPIC
# Compiler options for the linker # Compiler options for the linker
@ -356,11 +389,12 @@ ifeq ($(PLATFORM),PLATFORM_RPI)
INCLUDE_PATHS += -I$(RPI_TOOLCHAIN_SYSROOT)/opt/vc/include/interface/vcos/pthreads INCLUDE_PATHS += -I$(RPI_TOOLCHAIN_SYSROOT)/opt/vc/include/interface/vcos/pthreads
endif endif
ifeq ($(PLATFORM),PLATFORM_ANDROID) ifeq ($(PLATFORM),PLATFORM_ANDROID)
NATIVE_APP_GLUE = $(RAYLIB_RELEASE_PATH)/external/android/native_app_glue
#NATIVE_APP_GLUE = $(ANDROID_NDK)/sources/android/native_app_glue
# Android required libraries # Android required libraries
INCLUDE_PATHS += -I$(ANDROID_TOOLCHAIN)/sysroot/usr/include INCLUDE_PATHS += -I$(ANDROID_TOOLCHAIN)/sysroot/usr/include
# Include android_native_app_glue.h # Include android_native_app_glue.h
INCLUDE_PATHS += -Iexternal/android/native_app_glue INCLUDE_PATHS += -I$(NATIVE_APP_GLUE)
#INCLUDE_PATHS += -I$(ANDROID_NDK)/sources/android/native_app_glue
endif endif
# Define linker options # Define linker options
@ -635,6 +669,6 @@ else
rm -fv *.o $(RAYLIB_RELEASE_PATH)/libraylib.a $(RAYLIB_RELEASE_PATH)/libraylib.bc $(RAYLIB_RELEASE_PATH)/libraylib.so* rm -fv *.o $(RAYLIB_RELEASE_PATH)/libraylib.a $(RAYLIB_RELEASE_PATH)/libraylib.bc $(RAYLIB_RELEASE_PATH)/libraylib.so*
endif endif
ifeq ($(PLATFORM),PLATFORM_ANDROID) ifeq ($(PLATFORM),PLATFORM_ANDROID)
rm -rf $(ANDROID_TOOLCHAIN) rm -rf $(ANDROID_TOOLCHAIN) $(NATIVE_APP_GLUE)/android_native_app_glue.o
endif endif
@echo "removed all generated files!" @echo "removed all generated files!"

View File

@ -25,7 +25,7 @@
* *
**********************************************************************************************/ **********************************************************************************************/
#define RAYLIB_VERSION "2.5" #define RAYLIB_VERSION "2.6-dev"
// Edit to control what features Makefile'd raylib is compiled with // Edit to control what features Makefile'd raylib is compiled with
#if defined(RAYLIB_CMAKE) #if defined(RAYLIB_CMAKE)
@ -44,6 +44,8 @@
#define SUPPORT_MOUSE_GESTURES 1 #define SUPPORT_MOUSE_GESTURES 1
// Reconfigure standard input to receive key inputs, works with SSH connection. // Reconfigure standard input to receive key inputs, works with SSH connection.
#define SUPPORT_SSH_KEYBOARD_RPI 1 #define SUPPORT_SSH_KEYBOARD_RPI 1
// Draw a mouse reference on screen (square cursor box)
#define SUPPORT_MOUSE_CURSOR_RPI 1
// Use busy wait loop for timing sync, if not defined, a high-resolution timer is setup and used // Use busy wait loop for timing sync, if not defined, a high-resolution timer is setup and used
//#define SUPPORT_BUSY_WAIT_LOOP 1 //#define SUPPORT_BUSY_WAIT_LOOP 1
// Wait for events passively (sleeping while no events) instead of polling them actively every frame // Wait for events passively (sleeping while no events) instead of polling them actively every frame
@ -54,7 +56,8 @@
#define SUPPORT_GIF_RECORDING 1 #define SUPPORT_GIF_RECORDING 1
// Allow scale all the drawn content to match the high-DPI equivalent size (only PLATFORM_DESKTOP) // Allow scale all the drawn content to match the high-DPI equivalent size (only PLATFORM_DESKTOP)
//#define SUPPORT_HIGH_DPI 1 //#define SUPPORT_HIGH_DPI 1
// Support CompressData() and DecompressData() functions
#define SUPPORT_COMPRESSION_API 1
//------------------------------------------------------------------------------------ //------------------------------------------------------------------------------------
// Module: rlgl - Configuration Flags // Module: rlgl - Configuration Flags
@ -83,10 +86,10 @@
//#define SUPPORT_FILEFORMAT_JPG 1 //#define SUPPORT_FILEFORMAT_JPG 1
//#define SUPPORT_FILEFORMAT_GIF 1 //#define SUPPORT_FILEFORMAT_GIF 1
//#define SUPPORT_FILEFORMAT_PSD 1 //#define SUPPORT_FILEFORMAT_PSD 1
#define SUPPORT_FILEFORMAT_DDS 1 //#define SUPPORT_FILEFORMAT_DDS 1
#define SUPPORT_FILEFORMAT_HDR 1 #define SUPPORT_FILEFORMAT_HDR 1
#define SUPPORT_FILEFORMAT_KTX 1 //#define SUPPORT_FILEFORMAT_KTX 1
#define SUPPORT_FILEFORMAT_ASTC 1 //#define SUPPORT_FILEFORMAT_ASTC 1
//#define SUPPORT_FILEFORMAT_PKM 1 //#define SUPPORT_FILEFORMAT_PKM 1
//#define SUPPORT_FILEFORMAT_PVR 1 //#define SUPPORT_FILEFORMAT_PVR 1
@ -131,7 +134,7 @@
#define SUPPORT_FILEFORMAT_OGG 1 #define SUPPORT_FILEFORMAT_OGG 1
#define SUPPORT_FILEFORMAT_XM 1 #define SUPPORT_FILEFORMAT_XM 1
#define SUPPORT_FILEFORMAT_MOD 1 #define SUPPORT_FILEFORMAT_MOD 1
//#define SUPPORT_FILEFORMAT_FLAC 1 #define SUPPORT_FILEFORMAT_FLAC 1
#define SUPPORT_FILEFORMAT_MP3 1 #define SUPPORT_FILEFORMAT_MP3 1

View File

@ -19,6 +19,8 @@
#cmakedefine SUPPORT_GIF_RECORDING 1 #cmakedefine SUPPORT_GIF_RECORDING 1
// Support high DPI displays // Support high DPI displays
#cmakedefine SUPPORT_HIGH_DPI 1 #cmakedefine SUPPORT_HIGH_DPI 1
// Support CompressData() and DecompressData() functions
#cmakedefine SUPPORT_COMPRESSION_API 1
// rlgl.h // rlgl.h
// Support VR simulation functionality (stereo rendering) // Support VR simulation functionality (stereo rendering)

View File

@ -8,7 +8,7 @@
* - PLATFORM_DESKTOP: FreeBSD, OpenBSD, NetBSD, DragonFly (X11 desktop) * - PLATFORM_DESKTOP: FreeBSD, OpenBSD, NetBSD, DragonFly (X11 desktop)
* - PLATFORM_DESKTOP: OSX/macOS * - PLATFORM_DESKTOP: OSX/macOS
* - PLATFORM_ANDROID: Android 4.0 (ARM, ARM64) * - PLATFORM_ANDROID: Android 4.0 (ARM, ARM64)
* - PLATFORM_RPI: Raspberry Pi 0,1,2,3 (Raspbian) * - PLATFORM_RPI: Raspberry Pi 0,1,2,3,4 (Raspbian)
* - PLATFORM_WEB: HTML5 with asm.js (Chrome, Firefox) * - PLATFORM_WEB: HTML5 with asm.js (Chrome, Firefox)
* - PLATFORM_UWP: Windows 10 App, Windows Phone, Xbox One * - PLATFORM_UWP: Windows 10 App, Windows Phone, Xbox One
* *
@ -55,6 +55,9 @@
* WARNING: Reconfiguring standard input could lead to undesired effects, like breaking other running processes or * WARNING: Reconfiguring standard input could lead to undesired effects, like breaking other running processes or
* blocking the device is not restored properly. Use with care. * blocking the device is not restored properly. Use with care.
* *
* #define SUPPORT_MOUSE_CURSOR_RPI (Raspberry Pi only)
* Draw a mouse reference on screen (square cursor box)
*
* #define SUPPORT_BUSY_WAIT_LOOP * #define SUPPORT_BUSY_WAIT_LOOP
* Use busy wait loop for timing sync, if not defined, a high-resolution timer is setup and used * Use busy wait loop for timing sync, if not defined, a high-resolution timer is setup and used
* *
@ -71,6 +74,11 @@
* Allow scale all the drawn content to match the high-DPI equivalent size (only PLATFORM_DESKTOP) * Allow scale all the drawn content to match the high-DPI equivalent size (only PLATFORM_DESKTOP)
* NOTE: This flag is forced on macOS, since most displays are high-DPI * NOTE: This flag is forced on macOS, since most displays are high-DPI
* *
* #define SUPPORT_COMPRESSION_API
* Support CompressData() and DecompressData() functions, those functions use zlib implementation
* provided by stb_image and stb_image_write libraries, so, those libraries must be enabled on textures module
* for linkage
*
* DEPENDENCIES: * DEPENDENCIES:
* rglfw - Manage graphic device, OpenGL context and inputs on PLATFORM_DESKTOP (Windows, Linux, OSX. FreeBSD, OpenBSD, NetBSD, DragonFly) * rglfw - Manage graphic device, OpenGL context and inputs on PLATFORM_DESKTOP (Windows, Linux, OSX. FreeBSD, OpenBSD, NetBSD, DragonFly)
* raymath - 3D math functionality (Vector2, Vector3, Matrix, Quaternion) * raymath - 3D math functionality (Vector2, Vector3, Matrix, Quaternion)
@ -105,7 +113,7 @@
#if !defined(EXTERNAL_CONFIG_FLAGS) #if !defined(EXTERNAL_CONFIG_FLAGS)
#include "config.h" // Defines module configuration flags #include "config.h" // Defines module configuration flags
#else #else
#define RAYLIB_VERSION "2.5" #define RAYLIB_VERSION "2.6-dev"
#endif #endif
#if (defined(__linux__) || defined(PLATFORM_WEB)) && _POSIX_C_SOURCE < 199309L #if (defined(__linux__) || defined(PLATFORM_WEB)) && _POSIX_C_SOURCE < 199309L
@ -249,6 +257,12 @@
#include <emscripten/html5.h> // Emscripten HTML5 library #include <emscripten/html5.h> // Emscripten HTML5 library
#endif #endif
#if defined(SUPPORT_COMPRESSION_API)
// NOTE: Those declarations require stb_image and stb_image_write definitions, included in textures module
unsigned char *stbi_zlib_compress(unsigned char *data, int data_len, int *out_len, int quality);
char *stbi_zlib_decode_malloc(char const *buffer, int len, int *outlen);
#endif
//---------------------------------------------------------------------------------- //----------------------------------------------------------------------------------
// Defines and Macros // Defines and Macros
//---------------------------------------------------------------------------------- //----------------------------------------------------------------------------------
@ -423,7 +437,6 @@ static double targetTime = 0.0; // Desired time for one frame, if 0
// Config internal variables // Config internal variables
//----------------------------------------------------------------------------------- //-----------------------------------------------------------------------------------
static unsigned int configFlags = 0; // Configuration flags (bit based) static unsigned int configFlags = 0; // Configuration flags (bit based)
static bool showLogo = false; // Track if showing logo at init is enabled
static char **dropFilesPath; // Store dropped files paths as strings static char **dropFilesPath; // Store dropped files paths as strings
static int dropFilesCount = 0; // Count dropped files strings static int dropFilesCount = 0; // Count dropped files strings
@ -466,8 +479,6 @@ static int GetGamepadButton(int button); // Get gamepad button ge
static int GetGamepadAxis(int axis); // Get gamepad axis generic to all platforms static int GetGamepadAxis(int axis); // Get gamepad axis generic to all platforms
static void PollInputEvents(void); // Register user events static void PollInputEvents(void); // Register user events
static void LogoAnimation(void); // Plays raylib logo appearing animation
#if defined(PLATFORM_DESKTOP) || defined(PLATFORM_WEB) #if defined(PLATFORM_DESKTOP) || defined(PLATFORM_WEB)
static void ErrorCallback(int error, const char *description); // GLFW3 Error Callback, runs on GLFW3 error static void ErrorCallback(int error, const char *description); // GLFW3 Error Callback, runs on GLFW3 error
static void KeyCallback(GLFWwindow *window, int key, int scancode, int action, int mods); // GLFW3 Keyboard Callback, runs on key pressed static void KeyCallback(GLFWwindow *window, int key, int scancode, int action, int mods); // GLFW3 Keyboard Callback, runs on key pressed
@ -697,13 +708,6 @@ void InitWindow(int width, int height, const char *title)
mousePosition.x = (float)screenWidth/2.0f; mousePosition.x = (float)screenWidth/2.0f;
mousePosition.y = (float)screenHeight/2.0f; mousePosition.y = (float)screenHeight/2.0f;
// raylib logo appearing animation (if enabled)
if (showLogo)
{
SetTargetFPS(60);
LogoAnimation();
}
#endif // PLATFORM_ANDROID #endif // PLATFORM_ANDROID
} }
@ -1060,6 +1064,17 @@ int GetMonitorPhysicalHeight(int monitor)
return 0; return 0;
} }
// Get window position XY on monitor
Vector2 GetWindowPosition(void)
{
int x = 0;
int y = 0;
#if defined(PLATFORM_DESKTOP)
glfwGetWindowPos(window, &x, &y);
#endif
return (Vector2){ (float)x, (float)y };
}
// Get the human-readable, UTF-8 encoded name of the primary monitor // Get the human-readable, UTF-8 encoded name of the primary monitor
const char *GetMonitorName(int monitor) const char *GetMonitorName(int monitor)
{ {
@ -1187,6 +1202,12 @@ void BeginDrawing(void)
// End canvas drawing and swap buffers (double buffering) // End canvas drawing and swap buffers (double buffering)
void EndDrawing(void) void EndDrawing(void)
{ {
#if defined(PLATFORM_RPI) && defined(SUPPORT_MOUSE_CURSOR_RPI)
// On RPI native mode we have no system mouse cursor, so,
// we draw a small rectangle for user reference
DrawRectangle(mousePosition.x, mousePosition.y, 3, 3, MAROON);
#endif
rlglDraw(); // Draw Buffers (Only OpenGL 3+ and ES2) rlglDraw(); // Draw Buffers (Only OpenGL 3+ and ES2)
#if defined(SUPPORT_GIF_RECORDING) #if defined(SUPPORT_GIF_RECORDING)
@ -1249,17 +1270,12 @@ void BeginMode2D(Camera2D camera)
rlglDraw(); // Draw Buffers (Only OpenGL 3+ and ES2) rlglDraw(); // Draw Buffers (Only OpenGL 3+ and ES2)
rlLoadIdentity(); // Reset current matrix (MODELVIEW) rlLoadIdentity(); // Reset current matrix (MODELVIEW)
rlMultMatrixf(MatrixToFloat(screenScaling)); // Apply screen scaling if required
// Camera rotation and scaling is always relative to target // Apply screen scaling if required
Matrix matOrigin = MatrixTranslate(-camera.target.x, -camera.target.y, 0.0f); rlMultMatrixf(MatrixToFloat(screenScaling));
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.target.x, camera.offset.y + camera.target.y, 0.0f);
Matrix matTransform = MatrixMultiply(MatrixMultiply(matOrigin, MatrixMultiply(matScale, matRotation)), matTranslation); // Apply 2d camera transformation to modelview
rlMultMatrixf(MatrixToFloat(GetCameraMatrix2D(camera)));
rlMultMatrixf(MatrixToFloat(matTransform)); // Apply transformation to modelview
} }
// Ends 2D mode with custom camera // Ends 2D mode with custom camera
@ -1370,6 +1386,23 @@ void EndTextureMode(void)
currentHeight = GetScreenHeight(); currentHeight = GetScreenHeight();
} }
// Begin scissor mode (define screen area for following drawing)
// NOTE: Scissor rec refers to bottom-left corner, we change it to upper-left
void BeginScissorMode(int x, int y, int width, int height)
{
rlglDraw(); // Force drawing elements
rlEnableScissorTest();
rlScissor(x, GetScreenHeight() - (y + height), width, height);
}
// End scissor mode
void EndScissorMode(void)
{
rlglDraw(); // Force drawing elements
rlDisableScissorTest();
}
// Returns a ray trace from mouse position // Returns a ray trace from mouse position
Ray GetMouseRay(Vector2 mousePosition, Camera camera) Ray GetMouseRay(Vector2 mousePosition, Camera camera)
{ {
@ -1425,6 +1458,40 @@ Ray GetMouseRay(Vector2 mousePosition, Camera camera)
return ray; return ray;
} }
// Get transform matrix for camera
Matrix GetCameraMatrix(Camera camera)
{
return MatrixLookAt(camera.position, camera.target, camera.up);
}
// Returns camera 2d transform matrix
Matrix GetCameraMatrix2D(Camera2D camera)
{
Matrix matTransform = { 0 };
// The camera in world-space is set by
// 1. Move it to target
// 2. Rotate by -rotation and scale by (1/zoom)
// When setting higher scale, it's more intuitive for the world to become bigger (= camera become smaller),
// not for the camera getting bigger, hence the invert. Same deal with rotation.
// 3. Move it by (-offset);
// Offset defines target transform relative to screen, but since we're effectively "moving" screen (camera)
// we need to do it into opposite direction (inverse transform)
// Having camera transform in world-space, inverse of it gives the modelview transform.
// Since (A*B*C)' = C'*B'*A', the modelview is
// 1. Move to offset
// 2. Rotate and Scale
// 3. Move by -target
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;
}
// Returns the screen space position from a 3d world space position // Returns the screen space position from a 3d world space position
Vector2 GetWorldToScreen(Vector3 position, Camera camera) Vector2 GetWorldToScreen(Vector3 position, Camera camera)
{ {
@ -1467,10 +1534,22 @@ Vector2 GetWorldToScreen(Vector3 position, Camera camera)
return screenPosition; return screenPosition;
} }
// Get transform matrix for camera // Returns the screen space position for a 2d camera world space position
Matrix GetCameraMatrix(Camera camera) Vector2 GetWorldToScreen2D(Vector2 position, Camera2D camera)
{ {
return MatrixLookAt(camera.position, camera.target, camera.up); Matrix matCamera = GetCameraMatrix2D(camera);
Vector3 transform = Vector3Transform((Vector3){ position.x, position.y, 0 }, matCamera);
return (Vector2){ transform.x, transform.y };
}
// Returns the world space position for a 2d camera screen space position
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 };
} }
// Set target FPS (maximum) // Set target FPS (maximum)
@ -1664,7 +1743,6 @@ void SetConfigFlags(unsigned int flags)
{ {
configFlags = flags; configFlags = flags;
if (configFlags & FLAG_SHOW_LOGO) showLogo = true;
if (configFlags & FLAG_FULLSCREEN_MODE) fullscreen = true; if (configFlags & FLAG_FULLSCREEN_MODE) fullscreen = true;
if (configFlags & FLAG_WINDOW_ALWAYS_RUN) alwaysRun = true; if (configFlags & FLAG_WINDOW_ALWAYS_RUN) alwaysRun = true;
} }
@ -1718,29 +1796,36 @@ bool FileExists(const char *fileName)
bool IsFileExtension(const char *fileName, const char *ext) bool IsFileExtension(const char *fileName, const char *ext)
{ {
bool result = false; bool result = false;
const char *fileExt; const char *fileExt = GetExtension(fileName);
if ((fileExt = strrchr(fileName, '.')) != NULL) if (fileExt != NULL)
{
int extCount = 0;
const char **checkExts = TextSplit(ext, ';', &extCount);
for (int i = 0; i < extCount; i++)
{
if (strcmp(fileExt, checkExts[i] + 1) == 0)
{ {
#if defined(_WIN32)
result = true; result = true;
int extLen = strlen(ext);
if (strlen(fileExt) == extLen)
{
for (int i = 0; i < extLen; i++)
{
if (tolower(fileExt[i]) != tolower(ext[i]))
{
result = false;
break; break;
} }
} }
} }
else result = false;
#else return result;
if (strcmp(fileExt, ext) == 0) result = true; }
#endif
// Check if a directory path exists
bool DirectoryExists(const char *dirPath)
{
bool result = false;
DIR *dir = opendir(dirPath);
if (dir != NULL)
{
result = true;
closedir(dir);
} }
return result; return result;
@ -1767,22 +1852,23 @@ static const char *strprbrk(const char *s, const char *charset)
// Get pointer to filename for a path string // Get pointer to filename for a path string
const char *GetFileName(const char *filePath) const char *GetFileName(const char *filePath)
{ {
const char *fileName = strprbrk(filePath, "\\/"); const char *fileName = NULL;
if (filePath != NULL) fileName = strprbrk(filePath, "\\/");
if (!fileName || fileName == filePath) return filePath; if (!fileName || (fileName == filePath)) return filePath;
return fileName + 1; return fileName + 1;
} }
// Get filename string without extension (memory should be freed) // Get filename string without extension (uses static string)
const char *GetFileNameWithoutExt(const char *filePath) const char *GetFileNameWithoutExt(const char *filePath)
{ {
#define MAX_FILENAMEWITHOUTEXT_LENGTH 64 #define MAX_FILENAMEWITHOUTEXT_LENGTH 128
static char fileName[MAX_FILENAMEWITHOUTEXT_LENGTH]; static char fileName[MAX_FILENAMEWITHOUTEXT_LENGTH];
memset(fileName, 0, MAX_FILENAMEWITHOUTEXT_LENGTH); memset(fileName, 0, MAX_FILENAMEWITHOUTEXT_LENGTH);
strcpy(fileName, GetFileName(filePath)); // Get filename with extension if (filePath != NULL) strcpy(fileName, GetFileName(filePath)); // Get filename with extension
int len = strlen(fileName); int len = strlen(fileName);
@ -1799,21 +1885,43 @@ const char *GetFileNameWithoutExt(const char *filePath)
return fileName; return fileName;
} }
// Get directory for a given fileName (with path) // Get directory for a given filePath
const char *GetDirectoryPath(const char *fileName) const char *GetDirectoryPath(const char *filePath)
{ {
const char *lastSlash = NULL; const char *lastSlash = NULL;
static char filePath[MAX_FILEPATH_LENGTH]; static char dirPath[MAX_FILEPATH_LENGTH];
memset(filePath, 0, MAX_FILEPATH_LENGTH); memset(dirPath, 0, MAX_FILEPATH_LENGTH);
lastSlash = strprbrk(fileName, "\\/"); lastSlash = strprbrk(filePath, "\\/");
if (!lastSlash) return NULL; if (!lastSlash) return NULL;
// NOTE: Be careful, strncpy() is not safe, it does not care about '\0' // NOTE: Be careful, strncpy() is not safe, it does not care about '\0'
strncpy(filePath, fileName, strlen(fileName) - (strlen(lastSlash) - 1)); strncpy(dirPath, filePath, strlen(filePath) - (strlen(lastSlash) - 1));
filePath[strlen(fileName) - strlen(lastSlash)] = '\0'; // Add '\0' manually dirPath[strlen(filePath) - strlen(lastSlash)] = '\0'; // Add '\0' manually
return filePath; return dirPath;
}
// Get previous directory path for a given path
const char *GetPrevDirectoryPath(const char *dirPath)
{
static char prevDirPath[MAX_FILEPATH_LENGTH];
memset(prevDirPath, 0, MAX_FILEPATH_LENGTH);
int pathLen = 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) i++; // Check for root: "C:\"
strncpy(prevDirPath, dirPath, i);
break;
}
}
return prevDirPath;
} }
// Get current working directory // Get current working directory
@ -1870,11 +1978,12 @@ void ClearDirectoryFiles(void)
{ {
if (dirFilesCount > 0) if (dirFilesCount > 0)
{ {
for (int i = 0; i < dirFilesCount; i++) RL_FREE(dirFilesPath[i]); for (int i = 0; i < MAX_DIRECTORY_FILES; i++) RL_FREE(dirFilesPath[i]);
RL_FREE(dirFilesPath); RL_FREE(dirFilesPath);
dirFilesCount = 0;
} }
dirFilesCount = 0;
} }
// Change working directory, returns true if success // Change working directory, returns true if success
@ -1925,6 +2034,32 @@ long GetFileModTime(const char *fileName)
return 0; return 0;
} }
// Compress data (DEFLATE algorythm)
unsigned char *CompressData(unsigned char *data, int dataLength, int *compDataLength)
{
#define COMPRESSION_QUALITY_DEFLATE 8
unsigned char *compData = NULL;
#if defined(SUPPORT_COMPRESSION_API)
compData = stbi_zlib_compress(data, dataLength, compDataLength, COMPRESSION_QUALITY_DEFLATE);
#endif
return compData;
}
// Decompress data (DEFLATE algorythm)
unsigned char *DecompressData(unsigned char *compData, int compDataLength, int *dataLength)
{
char *data = NULL;
#if defined(SUPPORT_COMPRESSION_API)
data = stbi_zlib_decode_malloc((char *)compData, compDataLength, dataLength);
#endif
return (unsigned char *)data;
}
// Save integer value to storage file (to defined position) // Save integer value to storage file (to defined position)
// NOTE: Storage positions is directly related to file memory layout (4 bytes each integer) // NOTE: Storage positions is directly related to file memory layout (4 bytes each integer)
void StorageSaveValue(int position, int value) void StorageSaveValue(int position, int value)
@ -2287,7 +2422,7 @@ int GetMouseX(void)
int GetMouseY(void) int GetMouseY(void)
{ {
#if defined(PLATFORM_ANDROID) #if defined(PLATFORM_ANDROID)
return (int)touchPosition[0].x; return (int)touchPosition[0].y;
#else #else
return (int)((mousePosition.y + mouseOffset.y)*mouseScale.y); return (int)((mousePosition.y + mouseOffset.y)*mouseScale.y);
#endif #endif
@ -2457,9 +2592,6 @@ static bool InitGraphicsDevice(int width, int height)
if (screenHeight <= 0) screenHeight = displayHeight; if (screenHeight <= 0) screenHeight = displayHeight;
#endif // PLATFORM_DESKTOP #endif // PLATFORM_DESKTOP
currentWidth = screenWidth;
currentHeight = screenHeight;
#if defined(PLATFORM_WEB) #if defined(PLATFORM_WEB)
displayWidth = screenWidth; displayWidth = screenWidth;
displayHeight = screenHeight; displayHeight = screenHeight;
@ -2990,6 +3122,9 @@ static bool InitGraphicsDevice(int width, int height)
// Setup default viewport // Setup default viewport
SetupViewport(fbWidth, fbHeight); SetupViewport(fbWidth, fbHeight);
currentWidth = screenWidth;
currentHeight = screenHeight;
ClearBackground(RAYWHITE); // Default background color for raylib games :P ClearBackground(RAYWHITE); // Default background color for raylib games :P
#if defined(PLATFORM_ANDROID) #if defined(PLATFORM_ANDROID)
@ -3818,7 +3953,7 @@ static void WindowIconifyCallback(GLFWwindow *window, int iconified)
} }
// GLFW3 Window Drop Callback, runs when drop files into window // GLFW3 Window Drop Callback, runs when drop files into window
// NOTE: Paths are stored in dinamic memory for further retrieval // NOTE: Paths are stored in dynamic memory for further retrieval
// Everytime new files are dropped, old ones are discarded // Everytime new files are dropped, old ones are discarded
static void WindowDropCallback(GLFWwindow *window, int count, const char **paths) static void WindowDropCallback(GLFWwindow *window, int count, const char **paths)
{ {
@ -3898,13 +4033,6 @@ static void AndroidCommandCallback(struct android_app *app, int32_t cmd)
} }
} }
*/ */
// raylib logo appearing animation (if enabled)
if (showLogo)
{
SetTargetFPS(60); // Not required on Android
LogoAnimation();
}
} }
} }
} break; } break;
@ -4235,8 +4363,8 @@ static EM_BOOL EmscriptenGamepadCallback(int eventType, const EmscriptenGamepadE
eventType != 0? emscripten_event_type_to_string(eventType) : "Gamepad state", eventType != 0? emscripten_event_type_to_string(eventType) : "Gamepad state",
gamepadEvent->timestamp, gamepadEvent->connected, gamepadEvent->index, gamepadEvent->numAxes, gamepadEvent->numButtons, gamepadEvent->id, gamepadEvent->mapping); gamepadEvent->timestamp, gamepadEvent->connected, gamepadEvent->index, gamepadEvent->numAxes, gamepadEvent->numButtons, gamepadEvent->id, gamepadEvent->mapping);
for(int i = 0; i < gamepadEvent->numAxes; ++i) TraceLog(LOG_DEBUG, "Axis %d: %g", i, gamepadEvent->axis[i]); for (int i = 0; i < gamepadEvent->numAxes; ++i) TraceLog(LOG_DEBUG, "Axis %d: %g", i, gamepadEvent->axis[i]);
for(int i = 0; i < gamepadEvent->numButtons; ++i) TraceLog(LOG_DEBUG, "Button %d: Digital: %d, Analog: %g", i, gamepadEvent->digitalButton[i], gamepadEvent->analogButton[i]); for (int i = 0; i < gamepadEvent->numButtons; ++i) TraceLog(LOG_DEBUG, "Button %d: Digital: %d, Analog: %g", i, gamepadEvent->digitalButton[i], gamepadEvent->analogButton[i]);
*/ */
if ((gamepadEvent->connected) && (gamepadEvent->index < MAX_GAMEPADS)) gamepadReady[gamepadEvent->index] = true; if ((gamepadEvent->connected) && (gamepadEvent->index < MAX_GAMEPADS)) gamepadReady[gamepadEvent->index] = true;
@ -4952,117 +5080,3 @@ static void *GamepadThread(void *arg)
return NULL; return NULL;
} }
#endif // PLATFORM_RPI #endif // PLATFORM_RPI
// Plays raylib logo appearing animation
static void LogoAnimation(void)
{
#if !defined(PLATFORM_WEB) && !defined(PLATFORM_UWP)
int logoPositionX = screenWidth/2 - 128;
int logoPositionY = screenHeight/2 - 128;
int framesCounter = 0;
int lettersCount = 0;
int topSideRecWidth = 16;
int leftSideRecHeight = 16;
int bottomSideRecWidth = 16;
int rightSideRecHeight = 16;
int state = 0; // Tracking animation states (State Machine)
float alpha = 1.0f; // Useful for fading
while (!WindowShouldClose() && (state != 4)) // Detect window close button or ESC key
{
// Update
//----------------------------------------------------------------------------------
if (state == 0) // State 0: Small box blinking
{
framesCounter++;
if (framesCounter == 84)
{
state = 1;
framesCounter = 0; // Reset counter... will be used later...
}
}
else if (state == 1) // State 1: Top and left bars growing
{
topSideRecWidth += 4;
leftSideRecHeight += 4;
if (topSideRecWidth == 256) state = 2;
}
else if (state == 2) // State 2: Bottom and right bars growing
{
bottomSideRecWidth += 4;
rightSideRecHeight += 4;
if (bottomSideRecWidth == 256) state = 3;
}
else if (state == 3) // State 3: Letters appearing (one by one)
{
framesCounter++;
if (framesCounter/12) // Every 12 frames, one more letter!
{
lettersCount++;
framesCounter = 0;
}
if (lettersCount >= 10) // When all letters have appeared, just fade out everything
{
alpha -= 0.02f;
if (alpha <= 0.0f)
{
alpha = 0.0f;
state = 4;
}
}
}
//----------------------------------------------------------------------------------
// Draw
//----------------------------------------------------------------------------------
BeginDrawing();
ClearBackground(RAYWHITE);
if (state == 0)
{
if ((framesCounter/12)%2) DrawRectangle(logoPositionX, logoPositionY, 16, 16, BLACK);
}
else if (state == 1)
{
DrawRectangle(logoPositionX, logoPositionY, topSideRecWidth, 16, BLACK);
DrawRectangle(logoPositionX, logoPositionY, 16, leftSideRecHeight, BLACK);
}
else if (state == 2)
{
DrawRectangle(logoPositionX, logoPositionY, topSideRecWidth, 16, BLACK);
DrawRectangle(logoPositionX, logoPositionY, 16, leftSideRecHeight, BLACK);
DrawRectangle(logoPositionX + 240, logoPositionY, 16, rightSideRecHeight, BLACK);
DrawRectangle(logoPositionX, logoPositionY + 240, bottomSideRecWidth, 16, BLACK);
}
else if (state == 3)
{
DrawRectangle(logoPositionX, logoPositionY, topSideRecWidth, 16, Fade(BLACK, alpha));
DrawRectangle(logoPositionX, logoPositionY + 16, 16, leftSideRecHeight - 32, Fade(BLACK, alpha));
DrawRectangle(logoPositionX + 240, logoPositionY + 16, 16, rightSideRecHeight - 32, Fade(BLACK, alpha));
DrawRectangle(logoPositionX, logoPositionY + 240, bottomSideRecWidth, 16, Fade(BLACK, alpha));
DrawRectangle(screenWidth/2 - 112, screenHeight/2 - 112, 224, 224, Fade(RAYWHITE, alpha));
DrawText(TextSubtext("raylib", 0, lettersCount), screenWidth/2 - 44, screenHeight/2 + 48, 50, Fade(BLACK, alpha));
}
EndDrawing();
//----------------------------------------------------------------------------------
}
#endif
showLogo = false; // Prevent for repeating when reloading window (Android)
}

596
src/external/cgltf.h vendored

File diff suppressed because it is too large Load Diff

View File

@ -1,6 +1,6 @@
/* /*
FLAC audio decoder. Choice of public domain or MIT-0. See license statements at the end of this file. FLAC audio decoder. Choice of public domain or MIT-0. See license statements at the end of this file.
dr_flac - v0.11.7 - 2019-05-06 dr_flac - v0.11.10 - 2019-06-26
David Reid - mackron@gmail.com David Reid - mackron@gmail.com
*/ */
@ -149,7 +149,7 @@ typedef drflac_uint32 drflac_bool32;
#elif (defined(__GNUC__) && __GNUC__ >= 4) /* GCC 4 */ #elif (defined(__GNUC__) && __GNUC__ >= 4) /* GCC 4 */
#define DRFLAC_DEPRECATED __attribute__((deprecated)) #define DRFLAC_DEPRECATED __attribute__((deprecated))
#elif defined(__has_feature) /* Clang */ #elif defined(__has_feature) /* Clang */
#if defined(__has_feature(attribute_deprecated)) #if __has_feature(attribute_deprecated)
#define DRFLAC_DEPRECATED __attribute__((deprecated)) #define DRFLAC_DEPRECATED __attribute__((deprecated))
#else #else
#define DRFLAC_DEPRECATED #define DRFLAC_DEPRECATED
@ -1008,7 +1008,7 @@ static DRFLAC_INLINE drflac_bool32 drflac_has_sse2()
return DRFLAC_FALSE; return DRFLAC_FALSE;
#else #else
int info[4]; int info[4];
drflac_cpuid(info, 1); drflac__cpuid(info, 1);
return (info[3] & (1 << 26)) != 0; return (info[3] & (1 << 26)) != 0;
#endif #endif
#endif #endif
@ -1033,7 +1033,7 @@ static DRFLAC_INLINE drflac_bool32 drflac_has_sse41()
return DRFLAC_FALSE; return DRFLAC_FALSE;
#else #else
int info[4]; int info[4];
drflac_cpuid(info, 1); drflac__cpuid(info, 1);
return (info[2] & (1 << 19)) != 0; return (info[2] & (1 << 19)) != 0;
#endif #endif
#endif #endif
@ -1141,10 +1141,28 @@ reference excess prior samples.
/* CPU caps. */ /* CPU caps. */
static drflac_bool32 drflac__gIsLZCNTSupported = DRFLAC_FALSE; static drflac_bool32 drflac__gIsLZCNTSupported = DRFLAC_FALSE;
#ifndef DRFLAC_NO_CPUID #ifndef DRFLAC_NO_CPUID
/*
I've had a bug report that Clang's ThreadSanitizer presents a warning in this function. Having reviewed this, this does
actually make sense. However, since CPU caps should never differ for a running process, I don't think the trade off of
complicating internal API's by passing around CPU caps versus just disabling the warnings is worthwhile. I'm therefore
just going to disable these warnings.
*/
#if defined(__has_feature)
#if __has_feature(thread_sanitizer)
#define DRFLAC_NO_THREAD_SANITIZE __attribute__((no_sanitize("thread")))
#else
#define DRFLAC_NO_THREAD_SANITIZE
#endif
#else
#define DRFLAC_NO_THREAD_SANITIZE
#endif
static drflac_bool32 drflac__gIsSSE2Supported = DRFLAC_FALSE; static drflac_bool32 drflac__gIsSSE2Supported = DRFLAC_FALSE;
static drflac_bool32 drflac__gIsSSE41Supported = DRFLAC_FALSE; static drflac_bool32 drflac__gIsSSE41Supported = DRFLAC_FALSE;
static void drflac__init_cpu_caps() DRFLAC_NO_THREAD_SANITIZE static void drflac__init_cpu_caps()
{ {
static drflac_bool32 isCPUCapsInitialized = DRFLAC_FALSE;
if (!isCPUCapsInitialized) {
int info[4] = {0}; int info[4] = {0};
/* LZCNT */ /* LZCNT */
@ -1156,6 +1174,10 @@ static void drflac__init_cpu_caps()
/* SSE4.1 */ /* SSE4.1 */
drflac__gIsSSE41Supported = drflac_has_sse41(); drflac__gIsSSE41Supported = drflac_has_sse41();
/* Initialized. */
isCPUCapsInitialized = DRFLAC_TRUE;
}
} }
#endif #endif
@ -4897,9 +4919,9 @@ typedef struct
static DRFLAC_INLINE void drflac__decode_block_header(drflac_uint32 blockHeader, drflac_uint8* isLastBlock, drflac_uint8* blockType, drflac_uint32* blockSize) static DRFLAC_INLINE void drflac__decode_block_header(drflac_uint32 blockHeader, drflac_uint8* isLastBlock, drflac_uint8* blockType, drflac_uint32* blockSize)
{ {
blockHeader = drflac__be2host_32(blockHeader); blockHeader = drflac__be2host_32(blockHeader);
*isLastBlock = (blockHeader & (0x01 << 31)) >> 31; *isLastBlock = (blockHeader & 0x80000000UL) >> 31;
*blockType = (blockHeader & (0x7F << 24)) >> 24; *blockType = (blockHeader & 0x7F000000UL) >> 24;
*blockSize = (blockHeader & 0xFFFFFF); *blockSize = (blockHeader & 0x00FFFFFFUL);
} }
static DRFLAC_INLINE drflac_bool32 drflac__read_and_decode_block_header(drflac_read_proc onRead, void* pUserData, drflac_uint8* isLastBlock, drflac_uint8* blockType, drflac_uint32* blockSize) static DRFLAC_INLINE drflac_bool32 drflac__read_and_decode_block_header(drflac_read_proc onRead, void* pUserData, drflac_uint8* isLastBlock, drflac_uint8* blockType, drflac_uint32* blockSize)
@ -6759,10 +6781,10 @@ drflac_uint64 drflac__read_s32__misaligned(drflac* pFlac, drflac_uint64 samplesT
case DRFLAC_CHANNEL_ASSIGNMENT_LEFT_SIDE: case DRFLAC_CHANNEL_ASSIGNMENT_LEFT_SIDE:
{ {
if (channelIndex == 0) { if (channelIndex == 0) {
decodedSample = pFlac->currentFrame.subframes[channelIndex + 0].pDecodedSamples[nextSampleInFrame] << pFlac->currentFrame.subframes[channelIndex + 0].wastedBitsPerSample; decodedSample = (int)((drflac_uint32)pFlac->currentFrame.subframes[channelIndex + 0].pDecodedSamples[nextSampleInFrame] << pFlac->currentFrame.subframes[channelIndex + 0].wastedBitsPerSample);
} else { } else {
int side = pFlac->currentFrame.subframes[channelIndex + 0].pDecodedSamples[nextSampleInFrame] << pFlac->currentFrame.subframes[channelIndex + 0].wastedBitsPerSample; int side = (int)((drflac_uint32)pFlac->currentFrame.subframes[channelIndex + 0].pDecodedSamples[nextSampleInFrame] << pFlac->currentFrame.subframes[channelIndex + 0].wastedBitsPerSample);
int left = pFlac->currentFrame.subframes[channelIndex - 1].pDecodedSamples[nextSampleInFrame] << pFlac->currentFrame.subframes[channelIndex - 1].wastedBitsPerSample; int left = (int)((drflac_uint32)pFlac->currentFrame.subframes[channelIndex - 1].pDecodedSamples[nextSampleInFrame] << pFlac->currentFrame.subframes[channelIndex - 1].wastedBitsPerSample);
decodedSample = left - side; decodedSample = left - side;
} }
} break; } break;
@ -6770,11 +6792,11 @@ drflac_uint64 drflac__read_s32__misaligned(drflac* pFlac, drflac_uint64 samplesT
case DRFLAC_CHANNEL_ASSIGNMENT_RIGHT_SIDE: case DRFLAC_CHANNEL_ASSIGNMENT_RIGHT_SIDE:
{ {
if (channelIndex == 0) { if (channelIndex == 0) {
int side = pFlac->currentFrame.subframes[channelIndex + 0].pDecodedSamples[nextSampleInFrame] << pFlac->currentFrame.subframes[channelIndex + 0].wastedBitsPerSample; int side = (int)((drflac_uint32)pFlac->currentFrame.subframes[channelIndex + 0].pDecodedSamples[nextSampleInFrame] << pFlac->currentFrame.subframes[channelIndex + 0].wastedBitsPerSample);
int right = pFlac->currentFrame.subframes[channelIndex + 1].pDecodedSamples[nextSampleInFrame] << pFlac->currentFrame.subframes[channelIndex + 1].wastedBitsPerSample; int right = (int)((drflac_uint32)pFlac->currentFrame.subframes[channelIndex + 1].pDecodedSamples[nextSampleInFrame] << pFlac->currentFrame.subframes[channelIndex + 1].wastedBitsPerSample);
decodedSample = side + right; decodedSample = side + right;
} else { } else {
decodedSample = pFlac->currentFrame.subframes[channelIndex + 0].pDecodedSamples[nextSampleInFrame] << pFlac->currentFrame.subframes[channelIndex + 0].wastedBitsPerSample; decodedSample = (int)((drflac_uint32)pFlac->currentFrame.subframes[channelIndex + 0].pDecodedSamples[nextSampleInFrame] << pFlac->currentFrame.subframes[channelIndex + 0].wastedBitsPerSample);
} }
} break; } break;
@ -6783,14 +6805,14 @@ drflac_uint64 drflac__read_s32__misaligned(drflac* pFlac, drflac_uint64 samplesT
int mid; int mid;
int side; int side;
if (channelIndex == 0) { if (channelIndex == 0) {
mid = pFlac->currentFrame.subframes[channelIndex + 0].pDecodedSamples[nextSampleInFrame] << pFlac->currentFrame.subframes[channelIndex + 0].wastedBitsPerSample; mid = (int)((drflac_uint32)pFlac->currentFrame.subframes[channelIndex + 0].pDecodedSamples[nextSampleInFrame] << pFlac->currentFrame.subframes[channelIndex + 0].wastedBitsPerSample);
side = pFlac->currentFrame.subframes[channelIndex + 1].pDecodedSamples[nextSampleInFrame] << pFlac->currentFrame.subframes[channelIndex + 1].wastedBitsPerSample; side = (int)((drflac_uint32)pFlac->currentFrame.subframes[channelIndex + 1].pDecodedSamples[nextSampleInFrame] << pFlac->currentFrame.subframes[channelIndex + 1].wastedBitsPerSample);
mid = (((unsigned int)mid) << 1) | (side & 0x01); mid = (((unsigned int)mid) << 1) | (side & 0x01);
decodedSample = (mid + side) >> 1; decodedSample = (mid + side) >> 1;
} else { } else {
mid = pFlac->currentFrame.subframes[channelIndex - 1].pDecodedSamples[nextSampleInFrame] << pFlac->currentFrame.subframes[channelIndex - 1].wastedBitsPerSample; mid = (int)((drflac_uint32)pFlac->currentFrame.subframes[channelIndex - 1].pDecodedSamples[nextSampleInFrame] << pFlac->currentFrame.subframes[channelIndex - 1].wastedBitsPerSample);
side = pFlac->currentFrame.subframes[channelIndex + 0].pDecodedSamples[nextSampleInFrame] << pFlac->currentFrame.subframes[channelIndex + 0].wastedBitsPerSample; side = (int)((drflac_uint32)pFlac->currentFrame.subframes[channelIndex + 0].pDecodedSamples[nextSampleInFrame] << pFlac->currentFrame.subframes[channelIndex + 0].wastedBitsPerSample);
mid = (((unsigned int)mid) << 1) | (side & 0x01); mid = (((unsigned int)mid) << 1) | (side & 0x01);
decodedSample = (mid - side) >> 1; decodedSample = (mid - side) >> 1;
@ -6800,11 +6822,11 @@ drflac_uint64 drflac__read_s32__misaligned(drflac* pFlac, drflac_uint64 samplesT
case DRFLAC_CHANNEL_ASSIGNMENT_INDEPENDENT: case DRFLAC_CHANNEL_ASSIGNMENT_INDEPENDENT:
default: default:
{ {
decodedSample = pFlac->currentFrame.subframes[channelIndex + 0].pDecodedSamples[nextSampleInFrame] << pFlac->currentFrame.subframes[channelIndex + 0].wastedBitsPerSample; decodedSample = (int)((drflac_uint32)pFlac->currentFrame.subframes[channelIndex + 0].pDecodedSamples[nextSampleInFrame] << pFlac->currentFrame.subframes[channelIndex + 0].wastedBitsPerSample);
} break; } break;
} }
decodedSample <<= (32 - pFlac->bitsPerSample); decodedSample = (int)((drflac_uint32)decodedSample << (32 - pFlac->bitsPerSample));
if (bufferOut) { if (bufferOut) {
*bufferOut++ = decodedSample; *bufferOut++ = decodedSample;
@ -6876,8 +6898,8 @@ drflac_uint64 drflac_read_s32(drflac* pFlac, drflac_uint64 samplesToRead, drflac
const drflac_int32* pDecodedSamples1 = pFlac->currentFrame.subframes[1].pDecodedSamples + firstAlignedSampleInFrame; const drflac_int32* pDecodedSamples1 = pFlac->currentFrame.subframes[1].pDecodedSamples + firstAlignedSampleInFrame;
for (i = 0; i < alignedSampleCountPerChannel; ++i) { for (i = 0; i < alignedSampleCountPerChannel; ++i) {
int left = pDecodedSamples0[i] << (unusedBitsPerSample + pFlac->currentFrame.subframes[0].wastedBitsPerSample); int left = (int)((drflac_uint32)pDecodedSamples0[i] << (unusedBitsPerSample + pFlac->currentFrame.subframes[0].wastedBitsPerSample));
int side = pDecodedSamples1[i] << (unusedBitsPerSample + pFlac->currentFrame.subframes[1].wastedBitsPerSample); int side = (int)((drflac_uint32)pDecodedSamples1[i] << (unusedBitsPerSample + pFlac->currentFrame.subframes[1].wastedBitsPerSample));
int right = left - side; int right = left - side;
bufferOut[i*2+0] = left; bufferOut[i*2+0] = left;
@ -6892,8 +6914,8 @@ drflac_uint64 drflac_read_s32(drflac* pFlac, drflac_uint64 samplesToRead, drflac
const drflac_int32* pDecodedSamples1 = pFlac->currentFrame.subframes[1].pDecodedSamples + firstAlignedSampleInFrame; const drflac_int32* pDecodedSamples1 = pFlac->currentFrame.subframes[1].pDecodedSamples + firstAlignedSampleInFrame;
for (i = 0; i < alignedSampleCountPerChannel; ++i) { for (i = 0; i < alignedSampleCountPerChannel; ++i) {
int side = pDecodedSamples0[i] << (unusedBitsPerSample + pFlac->currentFrame.subframes[0].wastedBitsPerSample); int side = (int)((drflac_uint32)pDecodedSamples0[i] << (unusedBitsPerSample + pFlac->currentFrame.subframes[0].wastedBitsPerSample));
int right = pDecodedSamples1[i] << (unusedBitsPerSample + pFlac->currentFrame.subframes[1].wastedBitsPerSample); int right = (int)((drflac_uint32)pDecodedSamples1[i] << (unusedBitsPerSample + pFlac->currentFrame.subframes[1].wastedBitsPerSample));
int left = right + side; int left = right + side;
bufferOut[i*2+0] = left; bufferOut[i*2+0] = left;
@ -6908,13 +6930,13 @@ drflac_uint64 drflac_read_s32(drflac* pFlac, drflac_uint64 samplesToRead, drflac
const drflac_int32* pDecodedSamples1 = pFlac->currentFrame.subframes[1].pDecodedSamples + firstAlignedSampleInFrame; const drflac_int32* pDecodedSamples1 = pFlac->currentFrame.subframes[1].pDecodedSamples + firstAlignedSampleInFrame;
for (i = 0; i < alignedSampleCountPerChannel; ++i) { for (i = 0; i < alignedSampleCountPerChannel; ++i) {
int mid = pDecodedSamples0[i] << pFlac->currentFrame.subframes[0].wastedBitsPerSample; int mid = (int)((drflac_uint32)pDecodedSamples0[i] << pFlac->currentFrame.subframes[0].wastedBitsPerSample);
int side = pDecodedSamples1[i] << pFlac->currentFrame.subframes[1].wastedBitsPerSample; int side = (int)((drflac_uint32)pDecodedSamples1[i] << pFlac->currentFrame.subframes[1].wastedBitsPerSample);
mid = (((drflac_uint32)mid) << 1) | (side & 0x01); mid = (((drflac_uint32)mid) << 1) | (side & 0x01);
bufferOut[i*2+0] = ((mid + side) >> 1) << (unusedBitsPerSample); bufferOut[i*2+0] = (drflac_int32)((drflac_uint32)((mid + side) >> 1) << (unusedBitsPerSample));
bufferOut[i*2+1] = ((mid - side) >> 1) << (unusedBitsPerSample); bufferOut[i*2+1] = (drflac_int32)((drflac_uint32)((mid - side) >> 1) << (unusedBitsPerSample));
} }
} break; } break;
@ -6929,8 +6951,8 @@ drflac_uint64 drflac_read_s32(drflac* pFlac, drflac_uint64 samplesToRead, drflac
const drflac_int32* pDecodedSamples1 = pFlac->currentFrame.subframes[1].pDecodedSamples + firstAlignedSampleInFrame; const drflac_int32* pDecodedSamples1 = pFlac->currentFrame.subframes[1].pDecodedSamples + firstAlignedSampleInFrame;
for (i = 0; i < alignedSampleCountPerChannel; ++i) { for (i = 0; i < alignedSampleCountPerChannel; ++i) {
bufferOut[i*2+0] = pDecodedSamples0[i] << (unusedBitsPerSample + pFlac->currentFrame.subframes[0].wastedBitsPerSample); bufferOut[i*2+0] = (drflac_int32)((drflac_uint32)pDecodedSamples0[i] << (unusedBitsPerSample + pFlac->currentFrame.subframes[0].wastedBitsPerSample));
bufferOut[i*2+1] = pDecodedSamples1[i] << (unusedBitsPerSample + pFlac->currentFrame.subframes[1].wastedBitsPerSample); bufferOut[i*2+1] = (drflac_int32)((drflac_uint32)pDecodedSamples1[i] << (unusedBitsPerSample + pFlac->currentFrame.subframes[1].wastedBitsPerSample));
} }
} }
else else
@ -6940,7 +6962,7 @@ drflac_uint64 drflac_read_s32(drflac* pFlac, drflac_uint64 samplesToRead, drflac
for (i = 0; i < alignedSampleCountPerChannel; ++i) { for (i = 0; i < alignedSampleCountPerChannel; ++i) {
unsigned int j; unsigned int j;
for (j = 0; j < channelCount; ++j) { for (j = 0; j < channelCount; ++j) {
bufferOut[(i*channelCount)+j] = (pFlac->currentFrame.subframes[j].pDecodedSamples[firstAlignedSampleInFrame + i]) << (unusedBitsPerSample + pFlac->currentFrame.subframes[j].wastedBitsPerSample); bufferOut[(i*channelCount)+j] = (drflac_int32)((drflac_uint32)(pFlac->currentFrame.subframes[j].pDecodedSamples[firstAlignedSampleInFrame + i]) << (unusedBitsPerSample + pFlac->currentFrame.subframes[j].wastedBitsPerSample));
} }
} }
} }
@ -8649,6 +8671,15 @@ drflac_bool32 drflac_next_cuesheet_track(drflac_cuesheet_track_iterator* pIter,
/* /*
REVISION HISTORY REVISION HISTORY
================ ================
v0.11.10 - 2019-06-26
- Fix a compiler error.
v0.11.9 - 2019-06-16
- Silence some ThreadSanitizer warnings.
v0.11.8 - 2019-05-21
- Fix warnings.
v0.11.7 - 2019-05-06 v0.11.7 - 2019-05-06
- C89 fixes. - C89 fixes.

58
src/external/dr_mp3.h vendored
View File

@ -1,6 +1,6 @@
/* /*
MP3 audio decoder. Choice of public domain or MIT-0. See license statements at the end of this file. MP3 audio decoder. Choice of public domain or MIT-0. See license statements at the end of this file.
dr_mp3 - v0.4.4 - 2019-05-06 dr_mp3 - v0.4.7 - 2019-07-28
David Reid - mackron@gmail.com David Reid - mackron@gmail.com
@ -1143,6 +1143,8 @@ static void drmp3_L3_huffman(float *dst, drmp3_bs *bs, const drmp3_L3_gr_info *g
int sfb_cnt = gr_info->region_count[ireg++]; int sfb_cnt = gr_info->region_count[ireg++];
const drmp3_int16 *codebook = tabs + tabindex[tab_num]; const drmp3_int16 *codebook = tabs + tabindex[tab_num];
int linbits = g_linbits[tab_num]; int linbits = g_linbits[tab_num];
if (linbits)
{
do do
{ {
np = *sfb++ / 2; np = *sfb++ / 2;
@ -1163,7 +1165,7 @@ static void drmp3_L3_huffman(float *dst, drmp3_bs *bs, const drmp3_L3_gr_info *g
for (j = 0; j < 2; j++, dst++, leaf >>= 4) for (j = 0; j < 2; j++, dst++, leaf >>= 4)
{ {
int lsb = leaf & 0x0F; int lsb = leaf & 0x0F;
if (lsb == 15 && linbits) if (lsb == 15)
{ {
lsb += DRMP3_PEEK_BITS(linbits); lsb += DRMP3_PEEK_BITS(linbits);
DRMP3_FLUSH_BITS(linbits); DRMP3_FLUSH_BITS(linbits);
@ -1178,6 +1180,35 @@ static void drmp3_L3_huffman(float *dst, drmp3_bs *bs, const drmp3_L3_gr_info *g
DRMP3_CHECK_BITS; DRMP3_CHECK_BITS;
} while (--pairs_to_decode); } while (--pairs_to_decode);
} while ((big_val_cnt -= np) > 0 && --sfb_cnt >= 0); } while ((big_val_cnt -= np) > 0 && --sfb_cnt >= 0);
} else
{
do
{
np = *sfb++ / 2;
pairs_to_decode = DRMP3_MIN(big_val_cnt, np);
one = *scf++;
do
{
int j, w = 5;
int leaf = codebook[DRMP3_PEEK_BITS(w)];
while (leaf < 0)
{
DRMP3_FLUSH_BITS(w);
w = leaf & 7;
leaf = codebook[DRMP3_PEEK_BITS(w) - (leaf >> 3)];
}
DRMP3_FLUSH_BITS(leaf >> 8);
for (j = 0; j < 2; j++, dst++, leaf >>= 4)
{
int lsb = leaf & 0x0F;
*dst = g_drmp3_pow43[16 + lsb - 16*(bs_cache >> 31)]*one;
DRMP3_FLUSH_BITS(lsb ? 1 : 0);
}
DRMP3_CHECK_BITS;
} while (--pairs_to_decode);
} while ((big_val_cnt -= np) > 0 && --sfb_cnt >= 0);
}
} }
for (np = 1 - big_val_cnt;; dst += 4) for (np = 1 - big_val_cnt;; dst += 4)
@ -2133,14 +2164,14 @@ void drmp3dec_f32_to_s16(const float *in, drmp3_int16 *out, int num_samples)
int aligned_count = num_samples & ~7; int aligned_count = num_samples & ~7;
for(; i < aligned_count; i+=8) for(; i < aligned_count; i+=8)
{ {
static const drmp3_f4 g_scale = { 32768.0f, 32768.0f, 32768.0f, 32768.0f }; drmp3_f4 scale = DRMP3_VSET(32768.0f);
drmp3_f4 a = DRMP3_VMUL(DRMP3_VLD(&in[i ]), g_scale); drmp3_f4 a = DRMP3_VMUL(DRMP3_VLD(&in[i ]), scale);
drmp3_f4 b = DRMP3_VMUL(DRMP3_VLD(&in[i+4]), g_scale); drmp3_f4 b = DRMP3_VMUL(DRMP3_VLD(&in[i+4]), scale);
#if DRMP3_HAVE_SSE #if DRMP3_HAVE_SSE
static const drmp3_f4 g_max = { 32767.0f, 32767.0f, 32767.0f, 32767.0f }; drmp3_f4 s16max = DRMP3_VSET( 32767.0f);
static const drmp3_f4 g_min = { -32768.0f, -32768.0f, -32768.0f, -32768.0f }; drmp3_f4 s16min = DRMP3_VSET(-32768.0f);
__m128i pcm8 = _mm_packs_epi32(_mm_cvtps_epi32(_mm_max_ps(_mm_min_ps(a, g_max), g_min)), __m128i pcm8 = _mm_packs_epi32(_mm_cvtps_epi32(_mm_max_ps(_mm_min_ps(a, s16max), s16min)),
_mm_cvtps_epi32(_mm_max_ps(_mm_min_ps(b, g_max), g_min))); _mm_cvtps_epi32(_mm_max_ps(_mm_min_ps(b, s16max), s16min)));
out[i ] = (drmp3_int16)_mm_extract_epi16(pcm8, 0); out[i ] = (drmp3_int16)_mm_extract_epi16(pcm8, 0);
out[i+1] = (drmp3_int16)_mm_extract_epi16(pcm8, 1); out[i+1] = (drmp3_int16)_mm_extract_epi16(pcm8, 1);
out[i+2] = (drmp3_int16)_mm_extract_epi16(pcm8, 2); out[i+2] = (drmp3_int16)_mm_extract_epi16(pcm8, 2);
@ -3779,6 +3810,15 @@ DIFFERENCES BETWEEN minimp3 AND dr_mp3
/* /*
REVISION HISTORY REVISION HISTORY
================ ================
v0.4.7 - 2019-07-28
- Fix a compiler error.
v0.4.6 - 2019-06-14
- Fix a compiler error.
v0.4.5 - 2019-06-06
- Bring up to date with minimp3.
v0.4.4 - 2019-05-06 v0.4.4 - 2019-05-06
- Fixes to the VC6 build. - Fixes to the VC6 build.

17
src/external/dr_wav.h vendored
View File

@ -1,6 +1,6 @@
/* /*
WAV audio loader and writer. Choice of public domain or MIT-0. See license statements at the end of this file. WAV audio loader and writer. Choice of public domain or MIT-0. See license statements at the end of this file.
dr_wav - v0.9.1 - 2019-05-05 dr_wav - v0.9.2 - 2019-05-21
David Reid - mackron@gmail.com David Reid - mackron@gmail.com
*/ */
@ -2040,7 +2040,7 @@ drwav_bool32 drwav_init_ex(drwav* pWav, drwav_read_proc onRead, drwav_seek_proc
drwav_uint32 drwav_riff_chunk_size_riff(drwav_uint64 dataChunkSize) drwav_uint32 drwav_riff_chunk_size_riff(drwav_uint64 dataChunkSize)
{ {
if (dataChunkSize <= (0xFFFFFFFF - 36)) { if (dataChunkSize <= (0xFFFFFFFFUL - 36)) {
return 36 + (drwav_uint32)dataChunkSize; return 36 + (drwav_uint32)dataChunkSize;
} else { } else {
return 0xFFFFFFFF; return 0xFFFFFFFF;
@ -2049,10 +2049,10 @@ drwav_uint32 drwav_riff_chunk_size_riff(drwav_uint64 dataChunkSize)
drwav_uint32 drwav_data_chunk_size_riff(drwav_uint64 dataChunkSize) drwav_uint32 drwav_data_chunk_size_riff(drwav_uint64 dataChunkSize)
{ {
if (dataChunkSize <= 0xFFFFFFFF) { if (dataChunkSize <= 0xFFFFFFFFUL) {
return (drwav_uint32)dataChunkSize; return (drwav_uint32)dataChunkSize;
} else { } else {
return 0xFFFFFFFF; return 0xFFFFFFFFUL;
} }
} }
@ -2121,7 +2121,7 @@ drwav_bool32 drwav_init_write__internal(drwav* pWav, const drwav_data_format* pF
so for the sake of simplicity I'm not doing any validation for that. so for the sake of simplicity I'm not doing any validation for that.
*/ */
if (pFormat->container == drwav_container_riff) { if (pFormat->container == drwav_container_riff) {
if (initialDataChunkSize > (0xFFFFFFFF - 36)) { if (initialDataChunkSize > (0xFFFFFFFFUL - 36)) {
return DRWAV_FALSE; /* Not enough room to store every sample. */ return DRWAV_FALSE; /* Not enough room to store every sample. */
} }
} }
@ -3195,8 +3195,8 @@ void drwav_u8_to_s16(drwav_int16* pOut, const drwav_uint8* pIn, size_t sampleCou
size_t i; size_t i;
for (i = 0; i < sampleCount; ++i) { for (i = 0; i < sampleCount; ++i) {
int x = pIn[i]; int x = pIn[i];
r = x - 128; r = x << 8;
r = r << 8; r = r - 32768;
pOut[i] = (short)r; pOut[i] = (short)r;
} }
} }
@ -4675,6 +4675,9 @@ void drwav_free(void* pDataReturnedByOpenAndRead)
/* /*
REVISION HISTORY REVISION HISTORY
================ ================
v0.9.2 - 2019-05-21
- Fix warnings.
v0.9.1 - 2019-05-05 v0.9.1 - 2019-05-05
- Add support for C89. - Add support for C89.
- Change license to choice of public domain or MIT-0. - Change license to choice of public domain or MIT-0.

1201
src/external/miniaudio.h vendored

File diff suppressed because it is too large Load Diff

View File

@ -1,4 +1,4 @@
/* stb_image - v2.22 - public domain image loader - http://nothings.org/stb /* stb_image - v2.23 - public domain image loader - http://nothings.org/stb
no warranty implied; use at your own risk no warranty implied; use at your own risk
Do this: Do this:
@ -48,6 +48,7 @@ LICENSE
RECENT REVISION HISTORY: RECENT REVISION HISTORY:
2.23 (2019-08-11) fix clang static analysis warning
2.22 (2019-03-04) gif fixes, fix warnings 2.22 (2019-03-04) gif fixes, fix warnings
2.21 (2019-02-25) fix typo in comment 2.21 (2019-02-25) fix typo in comment
2.20 (2019-02-07) support utf8 filenames in Windows; fix warnings and platform ifdefs 2.20 (2019-02-07) support utf8 filenames in Windows; fix warnings and platform ifdefs
@ -5079,7 +5080,7 @@ static int stbi__high_bit(unsigned int z)
if (z >= 0x00100) { n += 8; z >>= 8; } if (z >= 0x00100) { n += 8; z >>= 8; }
if (z >= 0x00010) { n += 4; z >>= 4; } if (z >= 0x00010) { n += 4; z >>= 4; }
if (z >= 0x00004) { n += 2; z >>= 2; } if (z >= 0x00004) { n += 2; z >>= 2; }
if (z >= 0x00002) { n += 1; z >>= 1; } if (z >= 0x00002) { n += 1;/* >>= 1;*/ }
return n; return n;
} }
@ -5237,6 +5238,9 @@ static void *stbi__bmp_load(stbi__context *s, int *x, int *y, int *comp, int req
psize = (info.offset - 14 - info.hsz) >> 2; psize = (info.offset - 14 - info.hsz) >> 2;
} }
if (info.bpp == 24 && ma == 0xff000000)
s->img_n = 3;
else
s->img_n = ma ? 4 : 3; s->img_n = ma ? 4 : 3;
if (req_comp && req_comp >= 3) // we can directly decode 3 or 4 if (req_comp && req_comp >= 3) // we can directly decode 3 or 4
target = req_comp; target = req_comp;
@ -5547,6 +5551,8 @@ static void *stbi__tga_load(stbi__context *s, int *x, int *y, int *comp, int req
int RLE_repeating = 0; int RLE_repeating = 0;
int read_next_pixel = 1; int read_next_pixel = 1;
STBI_NOTUSED(ri); STBI_NOTUSED(ri);
STBI_NOTUSED(tga_x_origin); // @TODO
STBI_NOTUSED(tga_y_origin); // @TODO
// do a tiny bit of precessing // do a tiny bit of precessing
if ( tga_image_type >= 8 ) if ( tga_image_type >= 8 )
@ -5710,6 +5716,7 @@ static void *stbi__tga_load(stbi__context *s, int *x, int *y, int *comp, int req
// Microsoft's C compilers happy... [8^( // Microsoft's C compilers happy... [8^(
tga_palette_start = tga_palette_len = tga_palette_bits = tga_palette_start = tga_palette_len = tga_palette_bits =
tga_x_origin = tga_y_origin = 0; tga_x_origin = tga_y_origin = 0;
STBI_NOTUSED(tga_palette_start);
// OK, done // OK, done
return tga_data; return tga_data;
} }
@ -6936,7 +6943,12 @@ static int stbi__bmp_info(stbi__context *s, int *x, int *y, int *comp)
return 0; return 0;
if (x) *x = s->img_x; if (x) *x = s->img_x;
if (y) *y = s->img_y; if (y) *y = s->img_y;
if (comp) *comp = info.ma ? 4 : 3; if (comp) {
if (info.bpp == 24 && info.ma == 0xff000000)
*comp = 3;
else
*comp = info.ma ? 4 : 3;
}
return 1; return 1;
} }
#endif #endif

View File

@ -1,4 +1,4 @@
/* stb_image_write - v1.13 - public domain - http://nothings.org/stb/stb_image_write.h /* stb_image_write - v1.13 - public domain - http://nothings.org/stb
writes out PNG/BMP/TGA/JPEG/HDR images to C stdio - Sean Barrett 2010-2015 writes out PNG/BMP/TGA/JPEG/HDR images to C stdio - Sean Barrett 2010-2015
no warranty implied; use at your own risk no warranty implied; use at your own risk
@ -10,11 +10,6 @@
Will probably not work correctly with strict-aliasing optimizations. Will probably not work correctly with strict-aliasing optimizations.
If using a modern Microsoft Compiler, non-safe versions of CRT calls may cause
compilation warnings or even errors. To avoid this, also before #including,
#define STBI_MSC_SECURE_CRT
ABOUT: ABOUT:
This header file is a library for writing images to C stdio or a callback. This header file is a library for writing images to C stdio or a callback.
@ -873,7 +868,7 @@ STBIWDEF unsigned char * stbi_zlib_compress(unsigned char *data, int data_len, i
unsigned int bitbuf=0; unsigned int bitbuf=0;
int i,j, bitcount=0; int i,j, bitcount=0;
unsigned char *out = NULL; unsigned char *out = NULL;
unsigned char ***hash_table = (unsigned char***) STBIW_MALLOC(stbiw__ZHASH * sizeof(char**)); unsigned char ***hash_table = (unsigned char***) STBIW_MALLOC(stbiw__ZHASH * sizeof(unsigned char**));
if (hash_table == NULL) if (hash_table == NULL)
return NULL; return NULL;
if (quality < 5) quality = 5; if (quality < 5) quality = 5;
@ -1535,6 +1530,8 @@ STBIWDEF int stbi_write_jpg(char const *filename, int x, int y, int comp, const
#endif // STB_IMAGE_WRITE_IMPLEMENTATION #endif // STB_IMAGE_WRITE_IMPLEMENTATION
/* Revision history /* Revision history
1.11 (2019-08-11)
1.10 (2019-02-07) 1.10 (2019-02-07)
support utf8 filenames in Windows; fix warnings and platform ifdefs support utf8 filenames in Windows; fix warnings and platform ifdefs
1.09 (2018-02-11) 1.09 (2018-02-11)

View File

@ -81,6 +81,7 @@ extern float stb_perlin_noise3(float x, float y, float z, int x_wrap, int y_wrap
extern float stb_perlin_ridge_noise3(float x, float y, float z, float lacunarity, float gain, float offset, int octaves); extern float stb_perlin_ridge_noise3(float x, float y, float z, float lacunarity, float gain, float offset, int octaves);
extern float stb_perlin_fbm_noise3(float x, float y, float z, float lacunarity, float gain, int octaves); extern float stb_perlin_fbm_noise3(float x, float y, float z, float lacunarity, float gain, int octaves);
extern float stb_perlin_turbulence_noise3(float x, float y, float z, float lacunarity, float gain, int octaves); extern float stb_perlin_turbulence_noise3(float x, float y, float z, float lacunarity, float gain, int octaves);
extern float stb_perlin_noise3_wrap_nonpow2(float x, float y, float z, int x_wrap, int y_wrap, int z_wrap, unsigned char seed);
#ifdef __cplusplus #ifdef __cplusplus
} }
#endif #endif
@ -321,6 +322,66 @@ float stb_perlin_turbulence_noise3(float x, float y, float z, float lacunarity,
return sum; return sum;
} }
float stb_perlin_noise3_wrap_nonpow2(float x, float y, float z, int x_wrap, int y_wrap, int z_wrap, unsigned char seed)
{
float u,v,w;
float n000,n001,n010,n011,n100,n101,n110,n111;
float n00,n01,n10,n11;
float n0,n1;
int px = stb__perlin_fastfloor(x);
int py = stb__perlin_fastfloor(y);
int pz = stb__perlin_fastfloor(z);
int x_wrap2 = (x_wrap ? x_wrap : 256);
int y_wrap2 = (y_wrap ? y_wrap : 256);
int z_wrap2 = (z_wrap ? z_wrap : 256);
int x0 = px % x_wrap2, x1;
int y0 = py % y_wrap2, y1;
int z0 = pz % z_wrap2, z1;
int r0,r1, r00,r01,r10,r11;
if (x0 < 0) x0 += x_wrap2;
if (y0 < 0) y0 += y_wrap2;
if (z0 < 0) z0 += z_wrap2;
x1 = (x0+1) % x_wrap2;
y1 = (y0+1) % y_wrap2;
z1 = (z0+1) % z_wrap2;
#define stb__perlin_ease(a) (((a*6-15)*a + 10) * a * a * a)
x -= px; u = stb__perlin_ease(x);
y -= py; v = stb__perlin_ease(y);
z -= pz; w = stb__perlin_ease(z);
r0 = stb__perlin_randtab[x0];
r0 = stb__perlin_randtab[r0+seed];
r1 = stb__perlin_randtab[x1];
r1 = stb__perlin_randtab[r1+seed];
r00 = stb__perlin_randtab[r0+y0];
r01 = stb__perlin_randtab[r0+y1];
r10 = stb__perlin_randtab[r1+y0];
r11 = stb__perlin_randtab[r1+y1];
n000 = stb__perlin_grad(stb__perlin_randtab_grad_idx[r00+z0], x , y , z );
n001 = stb__perlin_grad(stb__perlin_randtab_grad_idx[r00+z1], x , y , z-1 );
n010 = stb__perlin_grad(stb__perlin_randtab_grad_idx[r01+z0], x , y-1, z );
n011 = stb__perlin_grad(stb__perlin_randtab_grad_idx[r01+z1], x , y-1, z-1 );
n100 = stb__perlin_grad(stb__perlin_randtab_grad_idx[r10+z0], x-1, y , z );
n101 = stb__perlin_grad(stb__perlin_randtab_grad_idx[r10+z1], x-1, y , z-1 );
n110 = stb__perlin_grad(stb__perlin_randtab_grad_idx[r11+z0], x-1, y-1, z );
n111 = stb__perlin_grad(stb__perlin_randtab_grad_idx[r11+z1], x-1, y-1, z-1 );
n00 = stb__perlin_lerp(n000,n001,w);
n01 = stb__perlin_lerp(n010,n011,w);
n10 = stb__perlin_lerp(n100,n101,w);
n11 = stb__perlin_lerp(n110,n111,w);
n0 = stb__perlin_lerp(n00,n01,v);
n1 = stb__perlin_lerp(n10,n11,v);
return stb__perlin_lerp(n0,n1,u);
}
#endif // STB_PERLIN_IMPLEMENTATION #endif // STB_PERLIN_IMPLEMENTATION
/* /*

View File

@ -1,5 +1,5 @@
// stb_truetype.h - v1.21 - public domain // stb_truetype.h - v1.22 - public domain
// authored from 2009-2016 by Sean Barrett / RAD Game Tools // authored from 2009-2019 by Sean Barrett / RAD Game Tools
// //
// This library processes TrueType files: // This library processes TrueType files:
// parse files // parse files
@ -46,9 +46,11 @@
// Rob Loach Cort Stratton // Rob Loach Cort Stratton
// Kenney Phillis Jr. github:oyvindjam // Kenney Phillis Jr. github:oyvindjam
// Brian Costabile github:vassvik // Brian Costabile github:vassvik
// Ken Voskuil (kaesve) Ryan Griege
// //
// VERSION HISTORY // VERSION HISTORY
// //
// 1.22 (2019-08-11) minimize missing-glyph duplication; fix kerning if both 'GPOS' and 'kern' are defined
// 1.21 (2019-02-25) fix warning // 1.21 (2019-02-25) fix warning
// 1.20 (2019-02-07) PackFontRange skips missing codepoints; GetScaleFontVMetrics() // 1.20 (2019-02-07) PackFontRange skips missing codepoints; GetScaleFontVMetrics()
// 1.19 (2018-02-11) GPOS kerning, STBTT_fmod // 1.19 (2018-02-11) GPOS kerning, STBTT_fmod
@ -2540,8 +2542,7 @@ STBTT_DEF int stbtt_GetGlyphKernAdvance(const stbtt_fontinfo *info, int g1, int
if (info->gpos) if (info->gpos)
xAdvance += stbtt__GetGlyphGPOSInfoAdvance(info, g1, g2); xAdvance += stbtt__GetGlyphGPOSInfoAdvance(info, g1, g2);
else if (info->kern)
if (info->kern)
xAdvance += stbtt__GetGlyphKernInfoAdvance(info, g1, g2); xAdvance += stbtt__GetGlyphKernInfoAdvance(info, g1, g2);
return xAdvance; return xAdvance;
@ -3968,6 +3969,7 @@ static float stbtt__oversample_shift(int oversample)
STBTT_DEF int stbtt_PackFontRangesGatherRects(stbtt_pack_context *spc, const stbtt_fontinfo *info, stbtt_pack_range *ranges, int num_ranges, stbrp_rect *rects) STBTT_DEF int stbtt_PackFontRangesGatherRects(stbtt_pack_context *spc, const stbtt_fontinfo *info, stbtt_pack_range *ranges, int num_ranges, stbrp_rect *rects)
{ {
int i,j,k; int i,j,k;
int missing_glyph_added = 0;
k=0; k=0;
for (i=0; i < num_ranges; ++i) { for (i=0; i < num_ranges; ++i) {
@ -3979,7 +3981,7 @@ STBTT_DEF int stbtt_PackFontRangesGatherRects(stbtt_pack_context *spc, const stb
int x0,y0,x1,y1; int x0,y0,x1,y1;
int codepoint = ranges[i].array_of_unicode_codepoints == NULL ? ranges[i].first_unicode_codepoint_in_range + j : ranges[i].array_of_unicode_codepoints[j]; int codepoint = ranges[i].array_of_unicode_codepoints == NULL ? ranges[i].first_unicode_codepoint_in_range + j : ranges[i].array_of_unicode_codepoints[j];
int glyph = stbtt_FindGlyphIndex(info, codepoint); int glyph = stbtt_FindGlyphIndex(info, codepoint);
if (glyph == 0 && spc->skip_missing) { if (glyph == 0 && (spc->skip_missing || missing_glyph_added)) {
rects[k].w = rects[k].h = 0; rects[k].w = rects[k].h = 0;
} else { } else {
stbtt_GetGlyphBitmapBoxSubpixel(info,glyph, stbtt_GetGlyphBitmapBoxSubpixel(info,glyph,
@ -3989,6 +3991,8 @@ STBTT_DEF int stbtt_PackFontRangesGatherRects(stbtt_pack_context *spc, const stb
&x0,&y0,&x1,&y1); &x0,&y0,&x1,&y1);
rects[k].w = (stbrp_coord) (x1-x0 + spc->padding + spc->h_oversample-1); rects[k].w = (stbrp_coord) (x1-x0 + spc->padding + spc->h_oversample-1);
rects[k].h = (stbrp_coord) (y1-y0 + spc->padding + spc->v_oversample-1); rects[k].h = (stbrp_coord) (y1-y0 + spc->padding + spc->v_oversample-1);
if (glyph == 0)
missing_glyph_added = 1;
} }
++k; ++k;
} }
@ -4023,7 +4027,7 @@ STBTT_DEF void stbtt_MakeGlyphBitmapSubpixelPrefilter(const stbtt_fontinfo *info
// rects array must be big enough to accommodate all characters in the given ranges // rects array must be big enough to accommodate all characters in the given ranges
STBTT_DEF int stbtt_PackFontRangesRenderIntoRects(stbtt_pack_context *spc, const stbtt_fontinfo *info, stbtt_pack_range *ranges, int num_ranges, stbrp_rect *rects) STBTT_DEF int stbtt_PackFontRangesRenderIntoRects(stbtt_pack_context *spc, const stbtt_fontinfo *info, stbtt_pack_range *ranges, int num_ranges, stbrp_rect *rects)
{ {
int i,j,k, return_value = 1; int i,j,k, missing_glyph = -1, return_value = 1;
// save current values // save current values
int old_h_over = spc->h_oversample; int old_h_over = spc->h_oversample;
@ -4088,6 +4092,13 @@ STBTT_DEF int stbtt_PackFontRangesRenderIntoRects(stbtt_pack_context *spc, const
bc->yoff = (float) y0 * recip_v + sub_y; bc->yoff = (float) y0 * recip_v + sub_y;
bc->xoff2 = (x0 + r->w) * recip_h + sub_x; bc->xoff2 = (x0 + r->w) * recip_h + sub_x;
bc->yoff2 = (y0 + r->h) * recip_v + sub_y; bc->yoff2 = (y0 + r->h) * recip_v + sub_y;
if (glyph == 0)
missing_glyph = j;
} else if (spc->skip_missing) {
return_value = 0;
} else if (r->was_packed && r->w == 0 && r->h == 0 && missing_glyph >= 0) {
ranges[i].chardata_for_range[j] = ranges[i].chardata_for_range[missing_glyph];
} else { } else {
return_value = 0; // if any fail, report failure return_value = 0; // if any fail, report failure
} }
@ -4389,12 +4400,7 @@ STBTT_DEF unsigned char * stbtt_GetGlyphSDF(const stbtt_fontinfo *info, float sc
int w,h; int w,h;
unsigned char *data; unsigned char *data;
// if one scale is 0, use same scale for both if (scale == 0) return NULL;
if (scale_x == 0) scale_x = scale_y;
if (scale_y == 0) {
if (scale_x == 0) return NULL; // if both scales are 0, return NULL
scale_y = scale_x;
}
stbtt_GetGlyphBitmapBoxSubpixel(info, glyph, scale, scale, 0.0f,0.0f, &ix0,&iy0,&ix1,&iy1); stbtt_GetGlyphBitmapBoxSubpixel(info, glyph, scale, scale, 0.0f,0.0f, &ix0,&iy0,&ix1,&iy1);

View File

@ -453,6 +453,11 @@ static void parseFloat3(float *x, float *y, float *z, const char **token) {
(*z) = parseFloat(token); (*z) = parseFloat(token);
} }
static unsigned int my_strnlen(const char *s, unsigned int n) {
const char *p = memchr(s, 0, n);
return p ? (unsigned int)(p - s) : n;
}
static char *my_strdup(const char *s, unsigned int max_length) { static char *my_strdup(const char *s, unsigned int max_length) {
char *d; char *d;
unsigned int len; unsigned int len;
@ -478,15 +483,13 @@ static char *my_strndup(const char *s, unsigned int len) {
if (s == NULL) return NULL; if (s == NULL) return NULL;
if (len == 0) return NULL; if (len == 0) return NULL;
d = (char *)TINYOBJ_MALLOC(len + 1); /* + '\0' */ slen = my_strnlen(s, len);
slen = strlen(s); d = (char *)TINYOBJ_MALLOC(slen + 1); /* + '\0' */
if (slen < len) { if (!d) {
return NULL;
}
memcpy(d, s, slen); memcpy(d, s, slen);
d[slen] = '\0'; d[slen] = '\0';
} else {
memcpy(d, s, len);
d[len] = '\0';
}
return d; return d;
} }

File diff suppressed because it is too large Load Diff

View File

@ -189,6 +189,8 @@ void TraceLog(int msgType, const char *text, ...); // Show trace lo
#define DEVICE_CHANNELS 2 #define DEVICE_CHANNELS 2
#define DEVICE_SAMPLE_RATE 44100 #define DEVICE_SAMPLE_RATE 44100
#define MAX_AUDIO_BUFFER_POOL_CHANNELS 16
typedef enum { AUDIO_BUFFER_USAGE_STATIC = 0, AUDIO_BUFFER_USAGE_STREAM } AudioBufferUsage; typedef enum { AUDIO_BUFFER_USAGE_STATIC = 0, AUDIO_BUFFER_USAGE_STREAM } AudioBufferUsage;
// Audio buffer structure // Audio buffer structure
@ -205,17 +207,23 @@ struct rAudioBuffer {
bool looping; // Audio buffer looping, always true for AudioStreams bool looping; // Audio buffer looping, always true for AudioStreams
int usage; // Audio buffer usage mode: STATIC or STREAM int usage; // Audio buffer usage mode: STATIC or STREAM
bool isSubBufferProcessed[2]; bool isSubBufferProcessed[2]; // SubBuffer processed (virtual double buffer)
unsigned int frameCursorPos; unsigned int frameCursorPos; // Frame cursor position
unsigned int bufferSizeInFrames; unsigned int bufferSizeInFrames; // Total buffer size in frames
unsigned int totalFramesProcessed; // Total frames processed in this buffer (required for play timming)
rAudioBuffer *next; unsigned char *buffer; // Data buffer, on music stream keeps filling
rAudioBuffer *prev;
unsigned char *buffer; rAudioBuffer *next; // Next audio buffer on the list
rAudioBuffer *prev; // Previous audio buffer on the list
}; };
#define AudioBuffer rAudioBuffer // HACK: To avoid CoreAudio (macOS) symbol collision #define AudioBuffer rAudioBuffer // HACK: To avoid CoreAudio (macOS) symbol collision
// Audio buffers are tracked in a linked list
static AudioBuffer *firstAudioBuffer = NULL;
static AudioBuffer *lastAudioBuffer = NULL;
// miniaudio global variables // miniaudio global variables
static ma_context context; static ma_context context;
static ma_device device; static ma_device device;
@ -223,9 +231,10 @@ static ma_mutex audioLock;
static bool isAudioInitialized = false; static bool isAudioInitialized = false;
static float masterVolume = 1.0f; static float masterVolume = 1.0f;
// Audio buffers are tracked in a linked list // Multi channel playback global variables
static AudioBuffer *firstAudioBuffer = NULL; AudioBuffer *audioBufferPool[MAX_AUDIO_BUFFER_POOL_CHANNELS] = { 0 };
static AudioBuffer *lastAudioBuffer = NULL; unsigned int audioBufferPoolCounter = 0;
unsigned int audioBufferPoolChannels[MAX_AUDIO_BUFFER_POOL_CHANNELS] = { 0 };
// miniaudio functions declaration // miniaudio functions declaration
static void OnLog(ma_context *pContext, ma_device *pDevice, ma_uint32 logLevel, const char *message); static void OnLog(ma_context *pContext, ma_device *pDevice, ma_uint32 logLevel, const char *message);
@ -247,19 +256,9 @@ void SetAudioBufferPitch(AudioBuffer *buffer, float pitch);
void TrackAudioBuffer(AudioBuffer *buffer); void TrackAudioBuffer(AudioBuffer *buffer);
void UntrackAudioBuffer(AudioBuffer *buffer); void UntrackAudioBuffer(AudioBuffer *buffer);
//---------------------------------------------------------------------------------- //----------------------------------------------------------------------------------
// Multi channel playback globals // miniaudio functions definitions
//----------------------------------------------------------------------------------
// Number of channels in the audio pool
#define MAX_AUDIO_BUFFER_POOL_CHANNELS 16
// Audio buffer pool
AudioBuffer *audioBufferPool[MAX_AUDIO_BUFFER_POOL_CHANNELS] = { 0 };
// These are used to determine the oldest playing channel
unsigned long audioBufferPoolCounter = 0;
unsigned long audioBufferPoolChannels[MAX_AUDIO_BUFFER_POOL_CHANNELS] = { 0 };
//---------------------------------------------------------------------------------- //----------------------------------------------------------------------------------
// Log callback function // Log callback function
@ -319,6 +318,7 @@ static void OnSendAudioDataToDevice(ma_device *pDevice, void *pFramesOut, const
{ {
float *framesOut = (float *)pFramesOut + (framesRead*device.playback.channels); float *framesOut = (float *)pFramesOut + (framesRead*device.playback.channels);
float *framesIn = tempBuffer; float *framesIn = tempBuffer;
MixAudioFrames(framesOut, framesIn, framesJustRead, audioBuffer->volume); MixAudioFrames(framesOut, framesIn, framesJustRead, audioBuffer->volume);
framesToRead -= framesJustRead; framesToRead -= framesJustRead;
@ -402,7 +402,7 @@ static ma_uint32 OnAudioBufferDSPRead(ma_pcm_converter *pDSP, void *pFramesOut,
} }
else else
{ {
ma_uint32 firstFrameIndexOfThisSubBuffer = subBufferSizeInFrames * currentSubBufferIndex; ma_uint32 firstFrameIndexOfThisSubBuffer = subBufferSizeInFrames*currentSubBufferIndex;
framesRemainingInOutputBuffer = subBufferSizeInFrames - (audioBuffer->frameCursorPos - firstFrameIndexOfThisSubBuffer); framesRemainingInOutputBuffer = subBufferSizeInFrames - (audioBuffer->frameCursorPos - firstFrameIndexOfThisSubBuffer);
} }
@ -410,7 +410,7 @@ static ma_uint32 OnAudioBufferDSPRead(ma_pcm_converter *pDSP, void *pFramesOut,
if (framesToRead > framesRemainingInOutputBuffer) framesToRead = framesRemainingInOutputBuffer; if (framesToRead > framesRemainingInOutputBuffer) framesToRead = framesRemainingInOutputBuffer;
memcpy((unsigned char *)pFramesOut + (framesRead*frameSizeInBytes), audioBuffer->buffer + (audioBuffer->frameCursorPos*frameSizeInBytes), framesToRead*frameSizeInBytes); memcpy((unsigned char *)pFramesOut + (framesRead*frameSizeInBytes), audioBuffer->buffer + (audioBuffer->frameCursorPos*frameSizeInBytes), framesToRead*frameSizeInBytes);
audioBuffer->frameCursorPos = (audioBuffer->frameCursorPos + framesToRead) % audioBuffer->bufferSizeInFrames; audioBuffer->frameCursorPos = (audioBuffer->frameCursorPos + framesToRead)%audioBuffer->bufferSizeInFrames;
framesRead += framesToRead; framesRead += framesToRead;
// If we've read to the end of the buffer, mark it as processed // If we've read to the end of the buffer, mark it as processed
@ -474,7 +474,11 @@ static void InitAudioBufferPool()
// Close the audio buffers pool // Close the audio buffers pool
static void CloseAudioBufferPool() static void CloseAudioBufferPool()
{ {
for (int i = 0; i < MAX_AUDIO_BUFFER_POOL_CHANNELS; i++) RL_FREE(audioBufferPool[i]); for (int i = 0; i < MAX_AUDIO_BUFFER_POOL_CHANNELS; i++)
{
RL_FREE(audioBufferPool[i]->buffer);
RL_FREE(audioBufferPool[i]);
}
} }
//---------------------------------------------------------------------------------- //----------------------------------------------------------------------------------
@ -485,7 +489,6 @@ void InitAudioDevice(void)
{ {
// Init audio context // Init audio context
ma_context_config contextConfig = ma_context_config_init(); ma_context_config contextConfig = ma_context_config_init();
contextConfig.logCallback = OnLog; contextConfig.logCallback = OnLog;
ma_result result = ma_context_init(NULL, 0, &contextConfig, &context); ma_result result = ma_context_init(NULL, 0, &contextConfig, &context);
@ -553,11 +556,7 @@ void InitAudioDevice(void)
// Close the audio device for all contexts // Close the audio device for all contexts
void CloseAudioDevice(void) void CloseAudioDevice(void)
{ {
if (!isAudioInitialized) if (isAudioInitialized)
{
TraceLog(LOG_WARNING, "Could not close audio device because it is not currently initialized");
}
else
{ {
ma_mutex_uninit(&audioLock); ma_mutex_uninit(&audioLock);
ma_device_uninit(&device); ma_device_uninit(&device);
@ -567,6 +566,7 @@ void CloseAudioDevice(void)
TraceLog(LOG_INFO, "Audio device closed successfully"); TraceLog(LOG_INFO, "Audio device closed successfully");
} }
else TraceLog(LOG_WARNING, "Could not close audio device because it is not currently initialized");
} }
// Check if device has been initialized successfully // Check if device has been initialized successfully
@ -588,11 +588,11 @@ void SetMasterVolume(float volume)
// Module Functions Definition - Audio Buffer management // Module Functions Definition - Audio Buffer management
//---------------------------------------------------------------------------------- //----------------------------------------------------------------------------------
// Create a new audio buffer. Initially filled with silence // Initialize a new audio buffer (filled with silence)
AudioBuffer *InitAudioBuffer(ma_format format, ma_uint32 channels, ma_uint32 sampleRate, ma_uint32 bufferSizeInFrames, int usage) AudioBuffer *InitAudioBuffer(ma_format format, ma_uint32 channels, ma_uint32 sampleRate, ma_uint32 bufferSizeInFrames, int usage)
{ {
AudioBuffer *audioBuffer = (AudioBuffer *)RL_CALLOC(sizeof(*audioBuffer), 1); AudioBuffer *audioBuffer = (AudioBuffer *)RL_CALLOC(1, sizeof(AudioBuffer));
audioBuffer->buffer = RL_CALLOC((bufferSizeInFrames*channels*ma_get_bytes_per_sample(format)), 1); audioBuffer->buffer = RL_CALLOC(bufferSizeInFrames*channels*ma_get_bytes_per_sample(format), 1);
if (audioBuffer == NULL) if (audioBuffer == NULL)
{ {
@ -690,6 +690,7 @@ void StopAudioBuffer(AudioBuffer *buffer)
buffer->playing = false; buffer->playing = false;
buffer->paused = false; buffer->paused = false;
buffer->frameCursorPos = 0; buffer->frameCursorPos = 0;
buffer->totalFramesProcessed = 0;
buffer->isSubBufferProcessed[0] = true; buffer->isSubBufferProcessed[0] = true;
buffer->isSubBufferProcessed[1] = true; buffer->isSubBufferProcessed[1] = true;
} }
@ -725,8 +726,10 @@ void SetAudioBufferPitch(AudioBuffer *buffer, float pitch)
{ {
float pitchMul = pitch/buffer->pitch; float pitchMul = pitch/buffer->pitch;
// Pitching is just an adjustment of the sample rate. Note that this changes the duration of the sound - higher pitches // Pitching is just an adjustment of the sample rate.
// will make the sound faster; lower pitches make it slower. // Note that this changes the duration of the sound:
// - higher pitches will make the sound faster
// - lower pitches make it slower
ma_uint32 newOutputSampleRate = (ma_uint32)((float)buffer->dsp.src.config.sampleRateOut/pitchMul); ma_uint32 newOutputSampleRate = (ma_uint32)((float)buffer->dsp.src.config.sampleRateOut/pitchMul);
buffer->pitch *= (float)buffer->dsp.src.config.sampleRateOut/newOutputSampleRate; buffer->pitch *= (float)buffer->dsp.src.config.sampleRateOut/newOutputSampleRate;
@ -869,16 +872,14 @@ void UpdateSound(Sound sound, const void *data, int samplesCount)
{ {
AudioBuffer *audioBuffer = sound.stream.buffer; AudioBuffer *audioBuffer = sound.stream.buffer;
if (audioBuffer == NULL) if (audioBuffer != NULL)
{ {
TraceLog(LOG_ERROR, "UpdateSound() : Invalid sound - no audio buffer");
return;
}
StopAudioBuffer(audioBuffer); StopAudioBuffer(audioBuffer);
// TODO: May want to lock/unlock this since this data buffer is read at mixing time. // TODO: May want to lock/unlock this since this data buffer is read at mixing time
memcpy(audioBuffer->buffer, data, samplesCount*audioBuffer->dsp.formatConverterIn.config.channels*ma_get_bytes_per_sample(audioBuffer->dsp.formatConverterIn.config.formatIn)); memcpy(audioBuffer->buffer, data, samplesCount*audioBuffer->dsp.formatConverterIn.config.channels*ma_get_bytes_per_sample(audioBuffer->dsp.formatConverterIn.config.formatIn));
}
else TraceLog(LOG_ERROR, "UpdateSound() : Invalid sound - no audio buffer");
} }
// Export wave data to file // Export wave data to file
@ -913,6 +914,8 @@ void ExportWaveAsCode(Wave wave, const char *fileName)
FILE *txtFile = fopen(fileName, "wt"); FILE *txtFile = fopen(fileName, "wt");
if (txtFile != NULL)
{
fprintf(txtFile, "\n//////////////////////////////////////////////////////////////////////////////////\n"); fprintf(txtFile, "\n//////////////////////////////////////////////////////////////////////////////////\n");
fprintf(txtFile, "// //\n"); fprintf(txtFile, "// //\n");
fprintf(txtFile, "// WaveAsCode exporter v1.0 - Wave data exported as an array of bytes //\n"); fprintf(txtFile, "// WaveAsCode exporter v1.0 - Wave data exported as an array of bytes //\n");
@ -944,6 +947,7 @@ void ExportWaveAsCode(Wave wave, const char *fileName)
fprintf(txtFile, "0x%x };\n", ((unsigned char *)wave.data)[dataSize - 1]); fprintf(txtFile, "0x%x };\n", ((unsigned char *)wave.data)[dataSize - 1]);
fclose(txtFile); fclose(txtFile);
}
} }
// Play a sound // Play a sound
@ -956,7 +960,7 @@ void PlaySound(Sound sound)
void PlaySoundMulti(Sound sound) void PlaySoundMulti(Sound sound)
{ {
int index = -1; int index = -1;
unsigned long oldAge = 0; unsigned int oldAge = 0;
int oldIndex = -1; int oldIndex = -1;
// find the first non playing pool entry // find the first non playing pool entry
@ -1184,14 +1188,8 @@ Music LoadMusicStream(const char *fileName)
// OGG bit rate defaults to 16 bit, it's enough for compressed format // OGG bit rate defaults to 16 bit, it's enough for compressed format
music.stream = InitAudioStream(info.sample_rate, 16, info.channels); music.stream = InitAudioStream(info.sample_rate, 16, info.channels);
music.sampleCount = (unsigned int)stb_vorbis_stream_length_in_samples((stb_vorbis *)music.ctxData)*info.channels; music.sampleCount = (unsigned int)stb_vorbis_stream_length_in_samples((stb_vorbis *)music.ctxData)*info.channels;
music.sampleLeft = music.sampleCount;
music.loopCount = 0; // Infinite loop by default music.loopCount = 0; // Infinite loop by default
musicLoaded = true; musicLoaded = true;
TraceLog(LOG_DEBUG, "[%s] OGG total samples: %i", fileName, music.sampleCount);
TraceLog(LOG_DEBUG, "[%s] OGG sample rate: %i", fileName, info.sample_rate);
TraceLog(LOG_DEBUG, "[%s] OGG channels: %i", fileName, info.channels);
TraceLog(LOG_DEBUG, "[%s] OGG memory required: %i", fileName, info.temp_memory_required);
} }
} }
#endif #endif
@ -1207,14 +1205,8 @@ Music LoadMusicStream(const char *fileName)
music.stream = InitAudioStream(ctxFlac->sampleRate, ctxFlac->bitsPerSample, ctxFlac->channels); music.stream = InitAudioStream(ctxFlac->sampleRate, ctxFlac->bitsPerSample, ctxFlac->channels);
music.sampleCount = (unsigned int)ctxFlac->totalSampleCount; music.sampleCount = (unsigned int)ctxFlac->totalSampleCount;
music.sampleLeft = music.sampleCount;
music.loopCount = 0; // Infinite loop by default music.loopCount = 0; // Infinite loop by default
musicLoaded = true; musicLoaded = true;
TraceLog(LOG_DEBUG, "[%s] FLAC total samples: %i", fileName, music.sampleCount);
TraceLog(LOG_DEBUG, "[%s] FLAC sample rate: %i", fileName, ctxFlac->sampleRate);
TraceLog(LOG_DEBUG, "[%s] FLAC bits per sample: %i", fileName, ctxFlac->bitsPerSample);
TraceLog(LOG_DEBUG, "[%s] FLAC channels: %i", fileName, ctxFlac->channels);
} }
} }
#endif #endif
@ -1232,14 +1224,8 @@ Music LoadMusicStream(const char *fileName)
music.stream = InitAudioStream(ctxMp3->sampleRate, 32, ctxMp3->channels); music.stream = InitAudioStream(ctxMp3->sampleRate, 32, ctxMp3->channels);
music.sampleCount = drmp3_get_pcm_frame_count(ctxMp3)*ctxMp3->channels; music.sampleCount = drmp3_get_pcm_frame_count(ctxMp3)*ctxMp3->channels;
music.sampleLeft = music.sampleCount;
music.loopCount = 0; // Infinite loop by default music.loopCount = 0; // Infinite loop by default
musicLoaded = true; musicLoaded = true;
TraceLog(LOG_INFO, "[%s] MP3 sample rate: %i", fileName, ctxMp3->sampleRate);
TraceLog(LOG_INFO, "[%s] MP3 bits per sample: %i", fileName, 32);
TraceLog(LOG_INFO, "[%s] MP3 channels: %i", fileName, ctxMp3->channels);
TraceLog(LOG_INFO, "[%s] MP3 total samples: %i", fileName, music.sampleCount);
} }
} }
#endif #endif
@ -1250,7 +1236,7 @@ Music LoadMusicStream(const char *fileName)
int result = jar_xm_create_context_from_file(&ctxXm, 48000, fileName); int result = jar_xm_create_context_from_file(&ctxXm, 48000, fileName);
if (result > 0) // XM context created successfully if (result == 0) // XM context created successfully
{ {
music.ctxType = MUSIC_MODULE_XM; music.ctxType = MUSIC_MODULE_XM;
jar_xm_set_max_loop_count(ctxXm, 0); // Set infinite number of loops jar_xm_set_max_loop_count(ctxXm, 0); // Set infinite number of loops
@ -1258,14 +1244,10 @@ Music LoadMusicStream(const char *fileName)
// NOTE: Only stereo is supported for XM // NOTE: Only stereo is supported for XM
music.stream = InitAudioStream(48000, 16, 2); music.stream = InitAudioStream(48000, 16, 2);
music.sampleCount = (unsigned int)jar_xm_get_remaining_samples(ctxXm); music.sampleCount = (unsigned int)jar_xm_get_remaining_samples(ctxXm);
music.sampleLeft = music.sampleCount;
music.loopCount = 0; // Infinite loop by default music.loopCount = 0; // Infinite loop by default
musicLoaded = true; musicLoaded = true;
music.ctxData = ctxXm; music.ctxData = ctxXm;
TraceLog(LOG_INFO, "[%s] XM number of samples: %i", fileName, music.sampleCount);
TraceLog(LOG_INFO, "[%s] XM track length: %11.6f sec", fileName, (float)music.sampleCount/48000.0f);
} }
} }
#endif #endif
@ -1285,12 +1267,8 @@ Music LoadMusicStream(const char *fileName)
// NOTE: Only stereo is supported for MOD // NOTE: Only stereo is supported for MOD
music.stream = InitAudioStream(48000, 16, 2); music.stream = InitAudioStream(48000, 16, 2);
music.sampleCount = (unsigned int)jar_mod_max_samples(ctxMod); music.sampleCount = (unsigned int)jar_mod_max_samples(ctxMod);
music.sampleLeft = music.sampleCount;
music.loopCount = 0; // Infinite loop by default music.loopCount = 0; // Infinite loop by default
musicLoaded = true; musicLoaded = true;
TraceLog(LOG_INFO, "[%s] MOD number of samples: %i", fileName, music.sampleLeft);
TraceLog(LOG_INFO, "[%s] MOD track length: %11.6f sec", fileName, (float)music.sampleCount/48000.0f);
} }
} }
#endif #endif
@ -1316,6 +1294,15 @@ Music LoadMusicStream(const char *fileName)
TraceLog(LOG_WARNING, "[%s] Music file could not be opened", fileName); TraceLog(LOG_WARNING, "[%s] Music file could not be opened", fileName);
} }
else
{
// Show some music stream info
TraceLog(LOG_INFO, "[%s] Music file successfully loaded:", fileName);
TraceLog(LOG_INFO, " Total samples: %i", music.sampleCount);
TraceLog(LOG_INFO, " Sample rate: %i Hz", music.stream.sampleRate);
TraceLog(LOG_INFO, " Sample size: %i bits", music.stream.sampleSize);
TraceLog(LOG_INFO, " Channels: %i (%s)", music.stream.channels, (music.stream.channels == 1)? "Mono" : (music.stream.channels == 2)? "Stereo" : "Multi");
}
return music; return music;
} }
@ -1348,21 +1335,18 @@ void PlayMusicStream(Music music)
{ {
AudioBuffer *audioBuffer = music.stream.buffer; AudioBuffer *audioBuffer = music.stream.buffer;
if (audioBuffer == NULL) if (audioBuffer != NULL)
{ {
TraceLog(LOG_ERROR, "PlayMusicStream() : No audio buffer"); // For music streams, we need to make sure we maintain the frame cursor position
return; // This is a hack for this section of code in UpdateMusicStream()
} // NOTE: In case window is minimized, music stream is stopped, just make sure to
// play again on window restore: if (IsMusicPlaying(music)) PlayMusicStream(music);
// For music streams, we need to make sure we maintain the frame cursor position. This is hack for this section of code in UpdateMusicStream()
// // NOTE: In case window is minimized, music stream is stopped,
// // just make sure to play again on window restore
// if (IsMusicPlaying(music)) PlayMusicStream(music);
ma_uint32 frameCursorPos = audioBuffer->frameCursorPos; ma_uint32 frameCursorPos = audioBuffer->frameCursorPos;
PlayAudioStream(music.stream); // WARNING: This resets the cursor position.
PlayAudioStream(music.stream); // <-- This resets the cursor position.
audioBuffer->frameCursorPos = frameCursorPos; audioBuffer->frameCursorPos = frameCursorPos;
}
else TraceLog(LOG_ERROR, "PlayMusicStream() : No audio buffer");
} }
// Pause music playing // Pause music playing
@ -1389,7 +1373,7 @@ void StopMusicStream(Music music)
case MUSIC_AUDIO_OGG: stb_vorbis_seek_start((stb_vorbis *)music.ctxData); break; case MUSIC_AUDIO_OGG: stb_vorbis_seek_start((stb_vorbis *)music.ctxData); break;
#endif #endif
#if defined(SUPPORT_FILEFORMAT_FLAC) #if defined(SUPPORT_FILEFORMAT_FLAC)
case MUSIC_AUDIO_FLAC: /* TODO: Restart FLAC context */ break; case MUSIC_AUDIO_FLAC: drflac_seek_to_pcm_frame((drflac *)music.ctxData, 0); break;
#endif #endif
#if defined(SUPPORT_FILEFORMAT_MP3) #if defined(SUPPORT_FILEFORMAT_MP3)
case MUSIC_AUDIO_MP3: drmp3_seek_to_pcm_frame((drmp3 *)music.ctxData, 0); break; case MUSIC_AUDIO_MP3: drmp3_seek_to_pcm_frame((drmp3 *)music.ctxData, 0); break;
@ -1402,8 +1386,6 @@ void StopMusicStream(Music music)
#endif #endif
default: break; default: break;
} }
music.sampleLeft = music.sampleCount;
} }
// Update (re-fill) music buffers if data already processed // Update (re-fill) music buffers if data already processed
@ -1416,12 +1398,16 @@ void UpdateMusicStream(Music music)
// NOTE: Using dynamic allocation because it could require more than 16KB // NOTE: Using dynamic allocation because it could require more than 16KB
void *pcm = RL_CALLOC(subBufferSizeInFrames*music.stream.channels*music.stream.sampleSize/8, 1); void *pcm = RL_CALLOC(subBufferSizeInFrames*music.stream.channels*music.stream.sampleSize/8, 1);
int samplesCount = 0; // Total size of data steamed in L+R samples for xm floats, individual L or R for ogg shorts int samplesCount = 0; // Total size of data streamed in L+R samples for xm floats, individual L or R for ogg shorts
while (IsAudioBufferProcessed(music.stream)) // TODO: Get the sampleLeft using totalFramesProcessed... but first, get total frames processed correctly...
//ma_uint32 frameSizeInBytes = ma_get_bytes_per_sample(music.stream.buffer->dsp.formatConverterIn.config.formatIn)*music.stream.buffer->dsp.formatConverterIn.config.channels;
int sampleLeft = music.sampleCount - (music.stream.buffer->totalFramesProcessed*music.stream.channels);
while (IsAudioStreamProcessed(music.stream))
{ {
if ((music.sampleLeft/music.stream.channels) >= subBufferSizeInFrames) samplesCount = subBufferSizeInFrames*music.stream.channels; if ((sampleLeft/music.stream.channels) >= subBufferSizeInFrames) samplesCount = subBufferSizeInFrames*music.stream.channels;
else samplesCount = music.sampleLeft; else samplesCount = sampleLeft;
switch (music.ctxType) switch (music.ctxType)
{ {
@ -1437,7 +1423,7 @@ void UpdateMusicStream(Music music)
case MUSIC_AUDIO_FLAC: case MUSIC_AUDIO_FLAC:
{ {
// NOTE: Returns the number of samples to process (not required) // NOTE: Returns the number of samples to process (not required)
drflac_read_s16((drflac *)music.ctxData, samplesCount, (short *)pcm); drflac_read_pcm_frames_s16((drflac *)music.ctxData, samplesCount, (short *)pcm);
} break; } break;
#endif #endif
@ -1470,12 +1456,12 @@ void UpdateMusicStream(Music music)
if ((music.ctxType == MUSIC_MODULE_XM) || (music.ctxType == MUSIC_MODULE_MOD)) if ((music.ctxType == MUSIC_MODULE_XM) || (music.ctxType == MUSIC_MODULE_MOD))
{ {
if (samplesCount > 1) music.sampleLeft -= samplesCount/2; if (samplesCount > 1) sampleLeft -= samplesCount/2;
else music.sampleLeft -= samplesCount; else sampleLeft -= samplesCount;
} }
else music.sampleLeft -= samplesCount; else sampleLeft -= samplesCount;
if (music.sampleLeft <= 0) if (sampleLeft <= 0)
{ {
streamEnding = true; streamEnding = true;
break; break;
@ -1496,10 +1482,7 @@ void UpdateMusicStream(Music music)
music.loopCount--; // Decrease loop count music.loopCount--; // Decrease loop count
PlayMusicStream(music); // Play again PlayMusicStream(music); // Play again
} }
else else if (music.loopCount == 0) PlayMusicStream(music);
{
if (music.loopCount == 0) PlayMusicStream(music);
}
} }
else else
{ {
@ -1528,7 +1511,7 @@ void SetMusicPitch(Music music, float pitch)
} }
// Set music loop count (loop repeats) // Set music loop count (loop repeats)
// NOTE: If set to -1, means infinite loop // NOTE: If set to 0, means infinite loop
void SetMusicLoopCount(Music music, int count) void SetMusicLoopCount(Music music, int count)
{ {
music.loopCount = count; music.loopCount = count;
@ -1549,7 +1532,8 @@ float GetMusicTimePlayed(Music music)
{ {
float secondsPlayed = 0.0f; float secondsPlayed = 0.0f;
unsigned int samplesPlayed = music.sampleCount - music.sampleLeft; //ma_uint32 frameSizeInBytes = ma_get_bytes_per_sample(music.stream.buffer->dsp.formatConverterIn.config.formatIn)*music.stream.buffer->dsp.formatConverterIn.config.channels;
unsigned int samplesPlayed = music.stream.buffer->totalFramesProcessed*music.stream.channels;
secondsPlayed = (float)samplesPlayed/(music.stream.sampleRate*music.stream.channels); secondsPlayed = (float)samplesPlayed/(music.stream.sampleRate*music.stream.channels);
return secondsPlayed; return secondsPlayed;
@ -1562,14 +1546,7 @@ AudioStream InitAudioStream(unsigned int sampleRate, unsigned int sampleSize, un
stream.sampleRate = sampleRate; stream.sampleRate = sampleRate;
stream.sampleSize = sampleSize; stream.sampleSize = sampleSize;
stream.channels = channels;
// Only mono and stereo channels are supported
if ((channels > 0) && (channels < 3)) stream.channels = channels;
else
{
TraceLog(LOG_WARNING, "Init audio stream: Number of channels not supported: %i", channels);
stream.channels = 1; // Fallback to mono channel
}
ma_format formatIn = ((stream.sampleSize == 8)? ma_format_u8 : ((stream.sampleSize == 16)? ma_format_s16 : ma_format_f32)); ma_format formatIn = ((stream.sampleSize == 8)? ma_format_u8 : ((stream.sampleSize == 16)? ma_format_s16 : ma_format_f32));
@ -1579,18 +1556,14 @@ AudioStream InitAudioStream(unsigned int sampleRate, unsigned int sampleSize, un
if (subBufferSize < periodSize) subBufferSize = periodSize; if (subBufferSize < periodSize) subBufferSize = periodSize;
AudioBuffer *audioBuffer = InitAudioBuffer(formatIn, stream.channels, stream.sampleRate, subBufferSize*2, AUDIO_BUFFER_USAGE_STREAM); stream.buffer = InitAudioBuffer(formatIn, stream.channels, stream.sampleRate, subBufferSize*2, AUDIO_BUFFER_USAGE_STREAM);
if (audioBuffer == NULL) if (stream.buffer != NULL)
{ {
TraceLog(LOG_ERROR, "InitAudioStream() : Failed to create audio buffer"); stream.buffer->looping = true; // Always loop for streaming buffers
return stream;
}
audioBuffer->looping = true; // Always loop for streaming buffers
stream.buffer = audioBuffer;
TraceLog(LOG_INFO, "Audio stream loaded successfully (%i Hz, %i bit, %s)", stream.sampleRate, stream.sampleSize, (stream.channels == 1)? "Mono" : "Stereo"); TraceLog(LOG_INFO, "Audio stream loaded successfully (%i Hz, %i bit, %s)", stream.sampleRate, stream.sampleSize, (stream.channels == 1)? "Mono" : "Stereo");
}
else TraceLog(LOG_ERROR, "InitAudioStream() : Failed to create audio buffer");
return stream; return stream;
} }
@ -1605,24 +1578,21 @@ void CloseAudioStream(AudioStream stream)
// Update audio stream buffers with data // Update audio stream buffers with data
// NOTE 1: Only updates one buffer of the stream source: unqueue -> update -> queue // NOTE 1: Only updates one buffer of the stream source: unqueue -> update -> queue
// NOTE 2: To unqueue a buffer it needs to be processed: IsAudioBufferProcessed() // NOTE 2: To unqueue a buffer it needs to be processed: IsAudioStreamProcessed()
void UpdateAudioStream(AudioStream stream, const void *data, int samplesCount) void UpdateAudioStream(AudioStream stream, const void *data, int samplesCount)
{ {
AudioBuffer *audioBuffer = stream.buffer; AudioBuffer *audioBuffer = stream.buffer;
if (audioBuffer == NULL) if (audioBuffer != NULL)
{ {
TraceLog(LOG_ERROR, "UpdateAudioStream() : No audio buffer");
return;
}
if (audioBuffer->isSubBufferProcessed[0] || audioBuffer->isSubBufferProcessed[1]) if (audioBuffer->isSubBufferProcessed[0] || audioBuffer->isSubBufferProcessed[1])
{ {
ma_uint32 subBufferToUpdate = 0; ma_uint32 subBufferToUpdate = 0;
if (audioBuffer->isSubBufferProcessed[0] && audioBuffer->isSubBufferProcessed[1]) if (audioBuffer->isSubBufferProcessed[0] && audioBuffer->isSubBufferProcessed[1])
{ {
// Both buffers are available for updating. Update the first one and make sure the cursor is moved back to the front. // Both buffers are available for updating.
// Update the first one and make sure the cursor is moved back to the front.
subBufferToUpdate = 0; subBufferToUpdate = 0;
audioBuffer->frameCursorPos = 0; audioBuffer->frameCursorPos = 0;
} }
@ -1635,7 +1605,11 @@ void UpdateAudioStream(AudioStream stream, const void *data, int samplesCount)
ma_uint32 subBufferSizeInFrames = audioBuffer->bufferSizeInFrames/2; ma_uint32 subBufferSizeInFrames = audioBuffer->bufferSizeInFrames/2;
unsigned char *subBuffer = audioBuffer->buffer + ((subBufferSizeInFrames*stream.channels*(stream.sampleSize/8))*subBufferToUpdate); unsigned char *subBuffer = audioBuffer->buffer + ((subBufferSizeInFrames*stream.channels*(stream.sampleSize/8))*subBufferToUpdate);
// Does this API expect a whole buffer to be updated in one go? Assuming so, but if not will need to change this logic. // TODO: Get total frames processed on this buffer... DOES NOT WORK.
audioBuffer->totalFramesProcessed += subBufferSizeInFrames;
// Does this API expect a whole buffer to be updated in one go?
// Assuming so, but if not will need to change this logic.
if (subBufferSizeInFrames >= (ma_uint32)samplesCount/stream.channels) if (subBufferSizeInFrames >= (ma_uint32)samplesCount/stream.channels)
{ {
ma_uint32 framesToWrite = subBufferSizeInFrames; ma_uint32 framesToWrite = subBufferSizeInFrames;
@ -1648,24 +1622,23 @@ void UpdateAudioStream(AudioStream stream, const void *data, int samplesCount)
// Any leftover frames should be filled with zeros. // Any leftover frames should be filled with zeros.
ma_uint32 leftoverFrameCount = subBufferSizeInFrames - framesToWrite; ma_uint32 leftoverFrameCount = subBufferSizeInFrames - framesToWrite;
if (leftoverFrameCount > 0) if (leftoverFrameCount > 0) memset(subBuffer + bytesToWrite, 0, leftoverFrameCount*stream.channels*(stream.sampleSize/8));
{
memset(subBuffer + bytesToWrite, 0, leftoverFrameCount*stream.channels*(stream.sampleSize/8));
}
audioBuffer->isSubBufferProcessed[subBufferToUpdate] = false; audioBuffer->isSubBufferProcessed[subBufferToUpdate] = false;
} }
else TraceLog(LOG_ERROR, "UpdateAudioStream() : Attempting to write too many frames to buffer"); else TraceLog(LOG_ERROR, "UpdateAudioStream() : Attempting to write too many frames to buffer");
} }
else TraceLog(LOG_ERROR, "Audio buffer not available for updating"); else TraceLog(LOG_ERROR, "UpdateAudioStream() : Audio buffer not available for updating");
}
else TraceLog(LOG_ERROR, "UpdateAudioStream() : No audio buffer");
} }
// Check if any audio stream buffers requires refill // Check if any audio stream buffers requires refill
bool IsAudioBufferProcessed(AudioStream stream) bool IsAudioStreamProcessed(AudioStream stream)
{ {
if (stream.buffer == NULL) if (stream.buffer == NULL)
{ {
TraceLog(LOG_ERROR, "IsAudioBufferProcessed() : No audio buffer"); TraceLog(LOG_ERROR, "IsAudioStreamProcessed() : No audio buffer");
return false; return false;
} }
@ -1901,9 +1874,9 @@ static int SaveWAV(Wave wave, const char *fileName)
waveData.subChunkID[3] = 'a'; waveData.subChunkID[3] = 'a';
waveData.subChunkSize = dataSize; waveData.subChunkSize = dataSize;
success = fwrite(&riffHeader, sizeof(RiffHeader), 1, wavFile); fwrite(&riffHeader, sizeof(RiffHeader), 1, wavFile);
success = fwrite(&waveFormat, sizeof(WaveFormat), 1, wavFile); fwrite(&waveFormat, sizeof(WaveFormat), 1, wavFile);
success = fwrite(&waveData, sizeof(WaveData), 1, wavFile); fwrite(&waveData, sizeof(WaveData), 1, wavFile);
success = fwrite(wave.data, dataSize, 1, wavFile); success = fwrite(wave.data, dataSize, 1, wavFile);
@ -1962,7 +1935,7 @@ static Wave LoadFLAC(const char *fileName)
// Decode an entire FLAC file in one go // Decode an entire FLAC file in one go
uint64_t totalSampleCount; uint64_t totalSampleCount;
wave.data = drflac_open_and_decode_file_s16(fileName, &wave.channels, &wave.sampleRate, &totalSampleCount); wave.data = drflac_open_file_and_read_pcm_frames_s16(fileName, &wave.channels, &wave.sampleRate, &totalSampleCount);
wave.sampleCount = (unsigned int)totalSampleCount; wave.sampleCount = (unsigned int)totalSampleCount;
wave.sampleSize = 16; wave.sampleSize = 16;

View File

@ -1,6 +1,6 @@
/********************************************************************************************** /**********************************************************************************************
* *
* raudio - A simple and easy-to-use audio library based on mini_al * raudio - A simple and easy-to-use audio library based on miniaudio
* *
* FEATURES: * FEATURES:
* - Manage audio device (init/close) * - Manage audio device (init/close)
@ -20,7 +20,7 @@
* *
* CONTRIBUTORS: * CONTRIBUTORS:
* David Reid (github: @mackron) (Nov. 2017): * David Reid (github: @mackron) (Nov. 2017):
* - Complete port to mini_al library * - Complete port to miniaudio library
* *
* Joshua Reisenauer (github: @kd7tck) (2015) * Joshua Reisenauer (github: @kd7tck) (2015)
* - XM audio module support (jar_xm) * - XM audio module support (jar_xm)
@ -112,7 +112,6 @@ typedef struct Music {
void *ctxData; // Audio context data, depends on type void *ctxData; // Audio context data, depends on type
unsigned int sampleCount; // Total number of samples unsigned int sampleCount; // Total number of samples
unsigned int sampleLeft; // Number of samples left to end
unsigned int loopCount; // Loops count (times music will play), 0 means infinite loop unsigned int loopCount; // Loops count (times music will play), 0 means infinite loop
AudioStream stream; // Audio stream AudioStream stream; // Audio stream
@ -182,7 +181,7 @@ float GetMusicTimePlayed(Music music); // Get current m
AudioStream InitAudioStream(unsigned int sampleRate, unsigned int sampleSize, unsigned int channels); // Init audio stream (to stream raw audio pcm data) AudioStream InitAudioStream(unsigned int sampleRate, unsigned int sampleSize, unsigned int channels); // Init audio stream (to stream raw audio pcm data)
void UpdateAudioStream(AudioStream stream, const void *data, int samplesCount); // Update audio stream buffers with data void UpdateAudioStream(AudioStream stream, const void *data, int samplesCount); // Update audio stream buffers with data
void CloseAudioStream(AudioStream stream); // Close audio stream and free memory void CloseAudioStream(AudioStream stream); // Close audio stream and free memory
bool IsAudioBufferProcessed(AudioStream stream); // Check if any audio stream buffers requires refill bool IsAudioStreamProcessed(AudioStream stream); // Check if any audio stream buffers requires refill
void PlayAudioStream(AudioStream stream); // Play audio stream void PlayAudioStream(AudioStream stream); // Play audio stream
void PauseAudioStream(AudioStream stream); // Pause audio stream void PauseAudioStream(AudioStream stream); // Pause audio stream
void ResumeAudioStream(AudioStream stream); // Resume audio stream void ResumeAudioStream(AudioStream stream); // Resume audio stream

View File

@ -33,7 +33,7 @@
* [core] rgif (Charlie Tangora, Ramon Santamaria) for GIF recording * [core] rgif (Charlie Tangora, Ramon Santamaria) for GIF recording
* [textures] stb_image (Sean Barret) for images loading (BMP, TGA, PNG, JPEG, HDR...) * [textures] stb_image (Sean Barret) for images loading (BMP, TGA, PNG, JPEG, HDR...)
* [textures] stb_image_write (Sean Barret) for image writting (BMP, TGA, PNG, JPG) * [textures] stb_image_write (Sean Barret) for image writting (BMP, TGA, PNG, JPG)
* [textures] stb_image_resize (Sean Barret) for image resizing algorythms * [textures] stb_image_resize (Sean Barret) for image resizing algorithms
* [textures] stb_perlin (Sean Barret) for Perlin noise image generation * [textures] stb_perlin (Sean Barret) for Perlin noise image generation
* [text] stb_truetype (Sean Barret) for ttf fonts loading * [text] stb_truetype (Sean Barret) for ttf fonts loading
* [text] stb_rect_pack (Sean Barret) for rectangles packing * [text] stb_rect_pack (Sean Barret) for rectangles packing
@ -96,10 +96,6 @@
#define MAX_TOUCH_POINTS 10 // Maximum number of touch points supported #define MAX_TOUCH_POINTS 10 // Maximum number of touch points supported
// Shader and material limits
#define MAX_SHADER_LOCATIONS 32 // Maximum number of predefined locations stored in shader struct
#define MAX_MATERIAL_MAPS 12 // Maximum number of texture maps stored in shader struct
// Allow custom memory allocators // Allow custom memory allocators
#ifndef RL_MALLOC #ifndef RL_MALLOC
#define RL_MALLOC(sz) malloc(sz) #define RL_MALLOC(sz) malloc(sz)
@ -322,13 +318,13 @@ typedef struct Mesh {
// OpenGL identifiers // OpenGL identifiers
unsigned int vaoId; // OpenGL Vertex Array Object id unsigned int vaoId; // OpenGL Vertex Array Object id
unsigned int vboId[7]; // OpenGL Vertex Buffer Objects id (default vertex data) unsigned int *vboId; // OpenGL Vertex Buffer Objects id (default vertex data)
} Mesh; } Mesh;
// Shader type (generic) // Shader type (generic)
typedef struct Shader { typedef struct Shader {
unsigned int id; // Shader program id unsigned int id; // Shader program id
int locs[MAX_SHADER_LOCATIONS]; // Shader locations array int *locs; // Shader locations array (MAX_SHADER_LOCATIONS)
} Shader; } Shader;
// Material texture map // Material texture map
@ -341,7 +337,7 @@ typedef struct MaterialMap {
// Material type (generic) // Material type (generic)
typedef struct Material { typedef struct Material {
Shader shader; // Material shader Shader shader; // Material shader
MaterialMap maps[MAX_MATERIAL_MAPS]; // Material maps MaterialMap *maps; // Material maps array (MAX_MATERIAL_MAPS)
float *params; // Material generic parameters (if required) float *params; // Material generic parameters (if required)
} Material; } Material;
@ -438,7 +434,6 @@ typedef struct Music {
void *ctxData; // Audio context data, depends on type void *ctxData; // Audio context data, depends on type
unsigned int sampleCount; // Total number of samples unsigned int sampleCount; // Total number of samples
unsigned int sampleLeft; // Number of samples left to end
unsigned int loopCount; // Loops count (times music will play), 0 means infinite loop unsigned int loopCount; // Loops count (times music will play), 0 means infinite loop
AudioStream stream; // Audio stream AudioStream stream; // Audio stream
@ -464,7 +459,7 @@ typedef struct VrDeviceInfo {
// System config flags // System config flags
// NOTE: Used for bit masks // NOTE: Used for bit masks
typedef enum { typedef enum {
FLAG_SHOW_LOGO = 1, // Set to show raylib logo at startup FLAG_RESERVED = 1, // Reserved
FLAG_FULLSCREEN_MODE = 2, // Set to run program in fullscreen FLAG_FULLSCREEN_MODE = 2, // Set to run program in fullscreen
FLAG_WINDOW_RESIZABLE = 4, // Set to allow resizable window FLAG_WINDOW_RESIZABLE = 4, // Set to allow resizable window
FLAG_WINDOW_UNDECORATED = 8, // Set to disable window decoration (frame and buttons) FLAG_WINDOW_UNDECORATED = 8, // Set to disable window decoration (frame and buttons)
@ -887,6 +882,7 @@ RLAPI int GetMonitorWidth(int monitor); // Get primary
RLAPI int GetMonitorHeight(int monitor); // Get primary monitor height RLAPI int GetMonitorHeight(int monitor); // Get primary monitor height
RLAPI int GetMonitorPhysicalWidth(int monitor); // Get primary monitor physical width in millimetres RLAPI int GetMonitorPhysicalWidth(int monitor); // Get primary monitor physical width in millimetres
RLAPI int GetMonitorPhysicalHeight(int monitor); // Get primary monitor physical height in millimetres RLAPI int GetMonitorPhysicalHeight(int monitor); // Get primary monitor physical height in millimetres
RLAPI Vector2 GetWindowPosition(void); // Get window position XY on monitor
RLAPI const char *GetMonitorName(int monitor); // Get the human-readable, UTF-8 encoded name of the primary monitor RLAPI const char *GetMonitorName(int monitor); // Get the human-readable, UTF-8 encoded name of the primary monitor
RLAPI const char *GetClipboardText(void); // Get clipboard text content RLAPI const char *GetClipboardText(void); // Get clipboard text content
RLAPI void SetClipboardText(const char *text); // Set clipboard text content RLAPI void SetClipboardText(const char *text); // Set clipboard text content
@ -908,11 +904,16 @@ RLAPI void BeginMode3D(Camera3D camera); // Initializes
RLAPI void EndMode3D(void); // Ends 3D mode and returns to default 2D orthographic mode RLAPI void EndMode3D(void); // Ends 3D mode and returns to default 2D orthographic mode
RLAPI void BeginTextureMode(RenderTexture2D target); // Initializes render texture for drawing RLAPI void BeginTextureMode(RenderTexture2D target); // Initializes render texture for drawing
RLAPI void EndTextureMode(void); // Ends drawing to render texture RLAPI void EndTextureMode(void); // Ends drawing to render texture
RLAPI void BeginScissorMode(int x, int y, int width, int height); // Begin scissor mode (define screen area for following drawing)
RLAPI void EndScissorMode(void); // End scissor mode
// Screen-space-related functions // Screen-space-related functions
RLAPI Ray GetMouseRay(Vector2 mousePosition, Camera camera); // Returns a ray trace from mouse position RLAPI Ray GetMouseRay(Vector2 mousePosition, Camera camera); // Returns a ray trace from mouse position
RLAPI Vector2 GetWorldToScreen(Vector3 position, Camera camera); // Returns the screen space position for a 3d world space position
RLAPI Matrix GetCameraMatrix(Camera camera); // Returns camera transform matrix (view matrix) RLAPI Matrix GetCameraMatrix(Camera camera); // Returns camera transform matrix (view matrix)
RLAPI Matrix GetCameraMatrix2D(Camera2D camera); // Returns camera 2d transform matrix
RLAPI Vector2 GetWorldToScreen(Vector3 position, Camera camera); // Returns the screen space position for a 3d world space position
RLAPI Vector2 GetWorldToScreen2D(Vector2 position, Camera2D camera); // Returns the screen space position for a 2d camera world space position
RLAPI Vector2 GetScreenToWorld2D(Vector2 position, Camera2D camera); // Returns the world space position for a 2d camera screen space position
// Timing-related functions // Timing-related functions
RLAPI void SetTargetFPS(int fps); // Set target FPS (maximum) RLAPI void SetTargetFPS(int fps); // Set target FPS (maximum)
@ -940,10 +941,12 @@ RLAPI int GetRandomValue(int min, int max); // Returns a r
// Files management functions // Files management functions
RLAPI bool FileExists(const char *fileName); // Check if file exists RLAPI bool FileExists(const char *fileName); // Check if file exists
RLAPI bool IsFileExtension(const char *fileName, const char *ext);// Check file extension RLAPI bool IsFileExtension(const char *fileName, const char *ext);// Check file extension
RLAPI bool DirectoryExists(const char *dirPath); // Check if a directory path exists
RLAPI const char *GetExtension(const char *fileName); // Get pointer to extension for a filename string RLAPI const char *GetExtension(const char *fileName); // Get pointer to extension for a filename string
RLAPI const char *GetFileName(const char *filePath); // Get pointer to filename for a path string RLAPI const char *GetFileName(const char *filePath); // Get pointer to filename for a path string
RLAPI const char *GetFileNameWithoutExt(const char *filePath); // Get filename string without extension (memory should be freed) RLAPI const char *GetFileNameWithoutExt(const char *filePath); // Get filename string without extension (uses static string)
RLAPI const char *GetDirectoryPath(const char *fileName); // Get full path for a given fileName (uses static string) RLAPI const char *GetDirectoryPath(const char *filePath); // Get full path for a given fileName with path (uses static string)
RLAPI const char *GetPrevDirectoryPath(const char *dirPath); // Get previous directory path for a given path (uses static string)
RLAPI const char *GetWorkingDirectory(void); // Get current working directory (uses static string) RLAPI const char *GetWorkingDirectory(void); // Get current working directory (uses static string)
RLAPI char **GetDirectoryFiles(const char *dirPath, int *count); // Get filenames in a directory path (memory should be freed) RLAPI char **GetDirectoryFiles(const char *dirPath, int *count); // Get filenames in a directory path (memory should be freed)
RLAPI void ClearDirectoryFiles(void); // Clear directory files paths buffers (free memory) RLAPI void ClearDirectoryFiles(void); // Clear directory files paths buffers (free memory)
@ -953,6 +956,9 @@ RLAPI char **GetDroppedFiles(int *count); // Get dropped
RLAPI void ClearDroppedFiles(void); // Clear dropped files paths buffer (free memory) RLAPI void ClearDroppedFiles(void); // Clear dropped files paths buffer (free memory)
RLAPI long GetFileModTime(const char *fileName); // Get file modification time (last write time) RLAPI long GetFileModTime(const char *fileName); // Get file modification time (last write time)
RLAPI unsigned char *CompressData(unsigned char *data, int dataLength, int *compDataLength); // Compress data (DEFLATE algorythm)
RLAPI unsigned char *DecompressData(unsigned char *compData, int compDataLength, int *dataLength); // Decompress data (DEFLATE algorythm)
// Persistent storage management // Persistent storage management
RLAPI void StorageSaveValue(int position, int value); // Save integer value to storage file (to defined position) RLAPI void StorageSaveValue(int position, int value); // Save integer value to storage file (to defined position)
RLAPI int StorageLoadValue(int position); // Load integer value from storage file (from defined position) RLAPI int StorageLoadValue(int position); // Load integer value from storage file (from defined position)
@ -1056,9 +1062,9 @@ RLAPI void DrawRectangleLines(int posX, int posY, int width, int height, Color c
RLAPI void DrawRectangleLinesEx(Rectangle rec, int lineThick, Color color); // Draw rectangle outline with extended parameters RLAPI void DrawRectangleLinesEx(Rectangle rec, int lineThick, Color color); // Draw rectangle outline with extended parameters
RLAPI void DrawRectangleRounded(Rectangle rec, float roundness, int segments, Color color); // Draw rectangle with rounded edges RLAPI void DrawRectangleRounded(Rectangle rec, float roundness, int segments, Color color); // Draw rectangle with rounded edges
RLAPI void DrawRectangleRoundedLines(Rectangle rec, float roundness, int segments, int lineThick, Color color); // Draw rectangle with rounded edges outline RLAPI void DrawRectangleRoundedLines(Rectangle rec, float roundness, int segments, int lineThick, Color color); // Draw rectangle with rounded edges outline
RLAPI void DrawTriangle(Vector2 v1, Vector2 v2, Vector2 v3, Color color); // Draw a color-filled triangle RLAPI void DrawTriangle(Vector2 v1, Vector2 v2, Vector2 v3, Color color); // Draw a color-filled triangle (vertex in counter-clockwise order!)
RLAPI void DrawTriangleLines(Vector2 v1, Vector2 v2, Vector2 v3, Color color); // Draw triangle outline RLAPI void DrawTriangleLines(Vector2 v1, Vector2 v2, Vector2 v3, Color color); // Draw triangle outline (vertex in counter-clockwise order!)
RLAPI void DrawTriangleFan(Vector2 *points, int numPoints, Color color); // Draw a triangle fan defined by points RLAPI void DrawTriangleFan(Vector2 *points, int numPoints, Color color); // Draw a triangle fan defined by points (first vertex is the center)
RLAPI void DrawTriangleStrip(Vector2 *points, int pointsCount, Color color); // Draw a triangle strip defined by points RLAPI void DrawTriangleStrip(Vector2 *points, int pointsCount, Color color); // Draw a triangle strip defined by points
RLAPI void DrawPoly(Vector2 center, int sides, float radius, float rotation, Color color); // Draw a regular polygon (Vector version) RLAPI void DrawPoly(Vector2 center, int sides, float radius, float rotation, Color color); // Draw a regular polygon (Vector version)
@ -1093,6 +1099,7 @@ RLAPI void UnloadTexture(Texture2D texture);
RLAPI void UnloadRenderTexture(RenderTexture2D target); // Unload render texture from GPU memory (VRAM) RLAPI void UnloadRenderTexture(RenderTexture2D target); // Unload render texture from GPU memory (VRAM)
RLAPI Color *GetImageData(Image image); // Get pixel data from image as a Color struct array RLAPI Color *GetImageData(Image image); // Get pixel data from image as a Color struct array
RLAPI Vector4 *GetImageDataNormalized(Image image); // Get pixel data from image as Vector4 array (float normalized) RLAPI Vector4 *GetImageDataNormalized(Image image); // Get pixel data from image as Vector4 array (float normalized)
RLAPI Rectangle GetImageAlphaBorder(Image image, float threshold); // Get image alpha border rectangle
RLAPI int GetPixelDataSize(int width, int height, int format); // Get pixel data size in bytes (image or texture) RLAPI int GetPixelDataSize(int width, int height, int format); // Get pixel data size in bytes (image or texture)
RLAPI Image GetTextureData(Texture2D texture); // Get pixel data from GPU texture and return an Image RLAPI Image GetTextureData(Texture2D texture); // Get pixel data from GPU texture and return an Image
RLAPI Image GetScreenData(void); // Get pixel data from screen buffer and return an Image (screenshot) RLAPI Image GetScreenData(void); // Get pixel data from screen buffer and return an Image (screenshot)
@ -1181,18 +1188,15 @@ RLAPI void DrawTextRecEx(Font font, const char *text, Rectangle rec, float fontS
RLAPI int MeasureText(const char *text, int fontSize); // Measure string width for default font RLAPI int MeasureText(const char *text, int fontSize); // Measure string width for default font
RLAPI Vector2 MeasureTextEx(Font font, const char *text, float fontSize, float spacing); // Measure string size for Font RLAPI Vector2 MeasureTextEx(Font font, const char *text, float fontSize, float spacing); // Measure string size for Font
RLAPI int GetGlyphIndex(Font font, int character); // Get index position for a unicode character on font RLAPI int GetGlyphIndex(Font font, int character); // Get index position for a unicode character on font
RLAPI int GetNextCodepoint(const char *text, int *bytesProcessed); // Returns next codepoint in a UTF8 encoded string
// NOTE: 0x3f('?') is returned on failure
// Text strings management functions // Text strings management functions (no utf8 strings, only byte chars)
// NOTE: Some strings allocate memory internally for returned strings, just be careful! // NOTE: Some strings allocate memory internally for returned strings, just be careful!
RLAPI bool TextIsEqual(const char *text1, const char *text2); // Check if two text string are equal RLAPI bool TextIsEqual(const char *text1, const char *text2); // Check if two text string are equal
RLAPI unsigned int TextLength(const char *text); // Get text length, checks for '\0' ending RLAPI unsigned int TextLength(const char *text); // Get text length, checks for '\0' ending
RLAPI unsigned int TextCountCodepoints(const char *text); // Get total number of characters (codepoints) in a UTF8 encoded string
RLAPI const char *TextFormat(const char *text, ...); // Text formatting with variables (sprintf style) RLAPI const char *TextFormat(const char *text, ...); // Text formatting with variables (sprintf style)
RLAPI const char *TextSubtext(const char *text, int position, int length); // Get a piece of a text string RLAPI const char *TextSubtext(const char *text, int position, int length); // Get a piece of a text string
RLAPI char *TextReplace(char *text, const char *replace, const char *by); // Replace text string (memory should be freed!) RLAPI char *TextReplace(char *text, const char *replace, const char *by); // Replace text string (memory must be freed!)
RLAPI char *TextInsert(const char *text, const char *insert, int position); // Insert text in a position (memory should be freed!) RLAPI char *TextInsert(const char *text, const char *insert, int position); // Insert text in a position (memory must be freed!)
RLAPI const char *TextJoin(const char **textList, int count, const char *delimiter); // Join text strings with delimiter RLAPI const char *TextJoin(const char **textList, int count, const char *delimiter); // Join text strings with delimiter
RLAPI const char **TextSplit(const char *text, char delimiter, int *count); // Split text into multiple strings RLAPI const char **TextSplit(const char *text, char delimiter, int *count); // Split text into multiple strings
RLAPI void TextAppend(char *text, const char *append, int *position); // Append text at specific position and move cursor! RLAPI void TextAppend(char *text, const char *append, int *position); // Append text at specific position and move cursor!
@ -1201,6 +1205,13 @@ RLAPI const char *TextToUpper(const char *text); // Get upp
RLAPI const char *TextToLower(const char *text); // Get lower case version of provided string RLAPI const char *TextToLower(const char *text); // Get lower case version of provided string
RLAPI const char *TextToPascal(const char *text); // Get Pascal case notation version of provided string RLAPI const char *TextToPascal(const char *text); // Get Pascal case notation version of provided string
RLAPI int TextToInteger(const char *text); // Get integer value from text (negative values not supported) RLAPI int TextToInteger(const char *text); // Get integer value from text (negative values not supported)
RLAPI char *TextToUtf8(int *codepoints, int length); // Encode text codepoint into utf8 text (memory must be freed!)
// UTF8 text strings management functions
RLAPI int *GetCodepoints(const char *text, int *count); // Get all codepoints in a string, codepoints count returned by parameters
RLAPI int GetCodepointsCount(const char *text); // Get total number of characters (codepoints) in a UTF8 encoded string
RLAPI int GetNextCodepoint(const char *text, int *bytesProcessed); // Returns next codepoint in a UTF8 encoded string; 0x3f('?') is returned on failure
RLAPI const char *CodepointToUtf8(int codepoint, int *byteLength); // Encode codepoint into utf8 text (char array length returned as parameter)
//------------------------------------------------------------------------------------ //------------------------------------------------------------------------------------
// Basic 3d Shapes Drawing Functions (Module: models) // Basic 3d Shapes Drawing Functions (Module: models)
@ -1237,7 +1248,7 @@ RLAPI void UnloadModel(Model model);
// Mesh loading/unloading functions // Mesh loading/unloading functions
RLAPI Mesh *LoadMeshes(const char *fileName, int *meshCount); // Load meshes from model file RLAPI Mesh *LoadMeshes(const char *fileName, int *meshCount); // Load meshes from model file
RLAPI void ExportMesh(Mesh mesh, const char *fileName); // Export mesh data to file RLAPI void ExportMesh(Mesh mesh, const char *fileName); // Export mesh data to file
RLAPI void UnloadMesh(Mesh *mesh); // Unload mesh from memory (RAM and/or VRAM) RLAPI void UnloadMesh(Mesh mesh); // Unload mesh from memory (RAM and/or VRAM)
// Material loading/unloading functions // Material loading/unloading functions
RLAPI Material *LoadMaterials(const char *fileName, int *materialCount); // Load materials from model file RLAPI Material *LoadMaterials(const char *fileName, int *materialCount); // Load materials from model file
@ -1281,11 +1292,11 @@ RLAPI void DrawBillboardRec(Camera camera, Texture2D texture, Rectangle sourceRe
// Collision detection functions // Collision detection functions
RLAPI bool CheckCollisionSpheres(Vector3 centerA, float radiusA, Vector3 centerB, float radiusB); // Detect collision between two spheres RLAPI bool CheckCollisionSpheres(Vector3 centerA, float radiusA, Vector3 centerB, float radiusB); // Detect collision between two spheres
RLAPI bool CheckCollisionBoxes(BoundingBox box1, BoundingBox box2); // Detect collision between two bounding boxes RLAPI bool CheckCollisionBoxes(BoundingBox box1, BoundingBox box2); // Detect collision between two bounding boxes
RLAPI bool CheckCollisionBoxSphere(BoundingBox box, Vector3 centerSphere, float radiusSphere); // Detect collision between box and sphere RLAPI bool CheckCollisionBoxSphere(BoundingBox box, Vector3 center, float radius); // Detect collision between box and sphere
RLAPI bool CheckCollisionRaySphere(Ray ray, Vector3 spherePosition, float sphereRadius); // Detect collision between ray and sphere RLAPI bool CheckCollisionRaySphere(Ray ray, Vector3 center, float radius); // Detect collision between ray and sphere
RLAPI bool CheckCollisionRaySphereEx(Ray ray, Vector3 spherePosition, float sphereRadius, Vector3 *collisionPoint); // Detect collision between ray and sphere, returns collision point RLAPI bool CheckCollisionRaySphereEx(Ray ray, Vector3 center, float radius, Vector3 *collisionPoint); // Detect collision between ray and sphere, returns collision point
RLAPI bool CheckCollisionRayBox(Ray ray, BoundingBox box); // Detect collision between ray and box RLAPI bool CheckCollisionRayBox(Ray ray, BoundingBox box); // Detect collision between ray and box
RLAPI RayHitInfo GetCollisionRayModel(Ray ray, Model *model); // Get collision info between ray and model RLAPI RayHitInfo GetCollisionRayModel(Ray ray, Model model); // Get collision info between ray and model
RLAPI RayHitInfo GetCollisionRayTriangle(Ray ray, Vector3 p1, Vector3 p2, Vector3 p3); // Get collision info between ray and triangle RLAPI RayHitInfo GetCollisionRayTriangle(Ray ray, Vector3 p1, Vector3 p2, Vector3 p3); // Get collision info between ray and triangle
RLAPI RayHitInfo GetCollisionRayGround(Ray ray, float groundHeight); // Get collision info between ray and ground plane (Y-normal plane) RLAPI RayHitInfo GetCollisionRayGround(Ray ray, float groundHeight); // Get collision info between ray and ground plane (Y-normal plane)
@ -1297,7 +1308,7 @@ RLAPI RayHitInfo GetCollisionRayGround(Ray ray, float groundHeight);
// Shader loading/unloading functions // Shader loading/unloading functions
RLAPI char *LoadText(const char *fileName); // Load chars array from text file RLAPI char *LoadText(const char *fileName); // Load chars array from text file
RLAPI Shader LoadShader(const char *vsFileName, const char *fsFileName); // Load shader from files and bind default locations RLAPI Shader LoadShader(const char *vsFileName, const char *fsFileName); // Load shader from files and bind default locations
RLAPI Shader LoadShaderCode(char *vsCode, char *fsCode); // Load shader from code strings and bind default locations RLAPI Shader LoadShaderCode(const char *vsCode, const char *fsCode); // Load shader from code strings and bind default locations
RLAPI void UnloadShader(Shader shader); // Unload shader from GPU memory (VRAM) RLAPI void UnloadShader(Shader shader); // Unload shader from GPU memory (VRAM)
RLAPI Shader GetShaderDefault(void); // Get default shader RLAPI Shader GetShaderDefault(void); // Get default shader
@ -1312,6 +1323,7 @@ RLAPI void SetShaderValueTexture(Shader shader, int uniformLoc, Texture2D textur
RLAPI void SetMatrixProjection(Matrix proj); // Set a custom projection matrix (replaces internal projection matrix) RLAPI void SetMatrixProjection(Matrix proj); // Set a custom projection matrix (replaces internal projection matrix)
RLAPI void SetMatrixModelview(Matrix view); // Set a custom modelview matrix (replaces internal modelview matrix) RLAPI void SetMatrixModelview(Matrix view); // Set a custom modelview matrix (replaces internal modelview matrix)
RLAPI Matrix GetMatrixModelview(void); // Get internal modelview matrix RLAPI Matrix GetMatrixModelview(void); // Get internal modelview matrix
RLAPI Matrix GetMatrixProjection(void); // Get internal projection matrix
// Texture maps generation (PBR) // Texture maps generation (PBR)
// NOTE: Required shaders should be provided // NOTE: Required shaders should be provided
@ -1325,8 +1337,6 @@ RLAPI void BeginShaderMode(Shader shader); // Beg
RLAPI void EndShaderMode(void); // End custom shader drawing (use default shader) RLAPI void EndShaderMode(void); // End custom shader drawing (use default shader)
RLAPI void BeginBlendMode(int mode); // Begin blending mode (alpha, additive, multiplied) RLAPI void BeginBlendMode(int mode); // Begin blending mode (alpha, additive, multiplied)
RLAPI void EndBlendMode(void); // End blending mode (reset to default: alpha blending) RLAPI void EndBlendMode(void); // End blending mode (reset to default: alpha blending)
RLAPI void BeginScissorMode(int x, int y, int width, int height); // Begin scissor mode (define screen area for following drawing)
RLAPI void EndScissorMode(void); // End scissor mode
// VR control functions // VR control functions
RLAPI void InitVrSimulator(void); // Init VR simulator for selected device parameters RLAPI void InitVrSimulator(void); // Init VR simulator for selected device parameters
@ -1393,7 +1403,7 @@ RLAPI float GetMusicTimePlayed(Music music); // Get cur
RLAPI AudioStream InitAudioStream(unsigned int sampleRate, unsigned int sampleSize, unsigned int channels); // Init audio stream (to stream raw audio pcm data) RLAPI AudioStream InitAudioStream(unsigned int sampleRate, unsigned int sampleSize, unsigned int channels); // Init audio stream (to stream raw audio pcm data)
RLAPI void UpdateAudioStream(AudioStream stream, const void *data, int samplesCount); // Update audio stream buffers with data RLAPI void UpdateAudioStream(AudioStream stream, const void *data, int samplesCount); // Update audio stream buffers with data
RLAPI void CloseAudioStream(AudioStream stream); // Close audio stream and free memory RLAPI void CloseAudioStream(AudioStream stream); // Close audio stream and free memory
RLAPI bool IsAudioBufferProcessed(AudioStream stream); // Check if any audio stream buffers requires refill RLAPI bool IsAudioStreamProcessed(AudioStream stream); // Check if any audio stream buffers requires refill
RLAPI void PlayAudioStream(AudioStream stream); // Play audio stream RLAPI void PlayAudioStream(AudioStream stream); // Play audio stream
RLAPI void PauseAudioStream(AudioStream stream); // Pause audio stream RLAPI void PauseAudioStream(AudioStream stream); // Pause audio stream
RLAPI void ResumeAudioStream(AudioStream stream); // Resume audio stream RLAPI void ResumeAudioStream(AudioStream stream); // Resume audio stream

View File

@ -20,7 +20,7 @@
* *
* LICENSE: zlib/libpng * LICENSE: zlib/libpng
* *
* Copyright (c) 2015-2017 Ramon Santamaria (@raysan5) * Copyright (c) 2015-2019 Ramon Santamaria (@raysan5)
* *
* This software is provided "as-is", without any express or implied warranty. In no event * This software is provided "as-is", without any express or implied warranty. In no event
* will the authors be held liable for any damages arising from the use of this software. * will the authors be held liable for any damages arising from the use of this software.
@ -148,7 +148,7 @@ RMDEF float Clamp(float value, float min, float max)
return res > max ? max : res; return res > max ? max : res;
} }
// Calculate linear interpolation between two vectors // Calculate linear interpolation between two floats
RMDEF float Lerp(float start, float end, float amount) RMDEF float Lerp(float start, float end, float amount)
{ {
return start + amount*(end - start); return start + amount*(end - start);
@ -794,6 +794,33 @@ RMDEF Matrix MatrixRotate(Vector3 axis, float angle)
return result; return result;
} }
// Returns xyz-rotation matrix (angles in radians)
RMDEF Matrix MatrixRotateXYZ(Vector3 ang)
{
Matrix result = MatrixIdentity();
float cosz = cosf(-ang.z);
float sinz = sinf(-ang.z);
float cosy = cosf(-ang.y);
float siny = sinf(-ang.y);
float cosx = cosf(-ang.x);
float sinx = sinf(-ang.x);
result.m0 = cosz * cosy;
result.m4 = (cosz * siny * sinx) - (sinz * cosx);
result.m8 = (cosz * siny * cosx) + (sinz * sinx);
result.m1 = sinz * cosy;
result.m5 = (sinz * siny * sinx) + (cosz * cosx);
result.m9 = (sinz * siny * cosx) - (cosz * sinx);
result.m2 = -siny;
result.m6 = cosy * sinx;
result.m10= cosy * cosx;
return result;
}
// Returns x-rotation matrix (angle in radians) // Returns x-rotation matrix (angle in radians)
RMDEF Matrix MatrixRotateX(float angle) RMDEF Matrix MatrixRotateX(float angle)
{ {

View File

@ -131,6 +131,10 @@
#define MAX_MATRIX_STACK_SIZE 32 // Max size of Matrix stack #define MAX_MATRIX_STACK_SIZE 32 // Max size of Matrix stack
#define MAX_DRAWCALL_REGISTERED 256 // Max draws by state changes (mode, texture) #define MAX_DRAWCALL_REGISTERED 256 // Max draws by state changes (mode, texture)
// Shader and material limits
#define MAX_SHADER_LOCATIONS 32 // Maximum number of predefined locations stored in shader struct
#define MAX_MATERIAL_MAPS 12 // Maximum number of texture maps stored in shader struct
// Texture parameters (equivalent to OpenGL defines) // Texture parameters (equivalent to OpenGL defines)
#define RL_TEXTURE_WRAP_S 0x2802 // GL_TEXTURE_WRAP_S #define RL_TEXTURE_WRAP_S 0x2802 // GL_TEXTURE_WRAP_S
#define RL_TEXTURE_WRAP_T 0x2803 // GL_TEXTURE_WRAP_T #define RL_TEXTURE_WRAP_T 0x2803 // GL_TEXTURE_WRAP_T
@ -228,7 +232,7 @@ typedef unsigned char byte;
// OpenGL identifiers // OpenGL identifiers
unsigned int vaoId; // OpenGL Vertex Array Object id unsigned int vaoId; // OpenGL Vertex Array Object id
unsigned int vboId[7]; // OpenGL Vertex Buffer Objects id (7 types of vertex data) unsigned int *vboId; // OpenGL Vertex Buffer Objects id (7 types of vertex data)
} Mesh; } Mesh;
// Shader and material limits // Shader and material limits
@ -238,7 +242,7 @@ typedef unsigned char byte;
// Shader type (generic) // Shader type (generic)
typedef struct Shader { typedef struct Shader {
unsigned int id; // Shader program id unsigned int id; // Shader program id
int locs[MAX_SHADER_LOCATIONS]; // Shader locations array int *locs; // Shader locations array (MAX_SHADER_LOCATIONS)
} Shader; } Shader;
// Material texture map // Material texture map
@ -251,7 +255,7 @@ typedef unsigned char byte;
// Material type (generic) // Material type (generic)
typedef struct Material { typedef struct Material {
Shader shader; // Material shader Shader shader; // Material shader
MaterialMap maps[MAX_MATERIAL_MAPS]; // Material maps MaterialMap *maps; // Material maps (MAX_MATERIAL_MAPS)
float *params; // Material generic parameters (if required) float *params; // Material generic parameters (if required)
} Material; } Material;
@ -453,6 +457,9 @@ RLAPI void rlEnableDepthTest(void); // Enable depth te
RLAPI void rlDisableDepthTest(void); // Disable depth test RLAPI void rlDisableDepthTest(void); // Disable depth test
RLAPI void rlEnableBackfaceCulling(void); // Enable backface culling RLAPI void rlEnableBackfaceCulling(void); // Enable backface culling
RLAPI void rlDisableBackfaceCulling(void); // Disable backface culling RLAPI void rlDisableBackfaceCulling(void); // Disable backface culling
RLAPI void rlEnableScissorTest(void); // Enable scissor test
RLAPI void rlDisableScissorTest(void); // Disable scissor test
RLAPI void rlScissor(int x, int y, int width, int height); // Scissor test
RLAPI void rlEnableWireMode(void); // Enable wire mode RLAPI void rlEnableWireMode(void); // Enable wire mode
RLAPI void rlDisableWireMode(void); // Disable wire mode RLAPI void rlDisableWireMode(void); // Disable wire mode
RLAPI void rlDeleteTextures(unsigned int id); // Delete OpenGL texture from GPU RLAPI void rlDeleteTextures(unsigned int id); // Delete OpenGL texture from GPU
@ -499,7 +506,7 @@ RLAPI bool rlRenderTextureComplete(RenderTexture target); // Ver
RLAPI void rlLoadMesh(Mesh *mesh, bool dynamic); // Upload vertex data into GPU and provided VAO/VBO ids RLAPI void rlLoadMesh(Mesh *mesh, bool dynamic); // Upload vertex data into GPU and provided VAO/VBO ids
RLAPI void rlUpdateMesh(Mesh mesh, int buffer, int numVertex); // Update vertex data on GPU (upload new data to one buffer) RLAPI void rlUpdateMesh(Mesh mesh, int buffer, int numVertex); // Update vertex data on GPU (upload new data to one buffer)
RLAPI void rlDrawMesh(Mesh mesh, Material material, Matrix transform); // Draw a 3d mesh with material and transform RLAPI void rlDrawMesh(Mesh mesh, Material material, Matrix transform); // Draw a 3d mesh with material and transform
RLAPI void rlUnloadMesh(Mesh *mesh); // Unload mesh data from CPU and GPU RLAPI void rlUnloadMesh(Mesh mesh); // Unload mesh data from CPU and GPU
// NOTE: There is a set of shader related functions that are available to end user, // NOTE: There is a set of shader related functions that are available to end user,
// to avoid creating function wrappers through core module, they have been directly declared in raylib.h // to avoid creating function wrappers through core module, they have been directly declared in raylib.h
@ -512,7 +519,7 @@ RLAPI void rlUnloadMesh(Mesh *mesh); // Unl
// Shader loading/unloading functions // Shader loading/unloading functions
RLAPI char *LoadText(const char *fileName); // Load chars array from text file RLAPI char *LoadText(const char *fileName); // Load chars array from text file
RLAPI Shader LoadShader(const char *vsFileName, const char *fsFileName); // Load shader from files and bind default locations RLAPI Shader LoadShader(const char *vsFileName, const char *fsFileName); // Load shader from files and bind default locations
RLAPI Shader LoadShaderCode(char *vsCode, char *fsCode); // Load shader from code strings and bind default locations RLAPI Shader LoadShaderCode(const char *vsCode, const char *fsCode); // Load shader from code strings and bind default locations
RLAPI void UnloadShader(Shader shader); // Unload shader from GPU memory (VRAM) RLAPI void UnloadShader(Shader shader); // Unload shader from GPU memory (VRAM)
RLAPI Shader GetShaderDefault(void); // Get default shader RLAPI Shader GetShaderDefault(void); // Get default shader
@ -1340,28 +1347,25 @@ void rlDisableRenderTexture(void)
} }
// Enable depth test // Enable depth test
void rlEnableDepthTest(void) void rlEnableDepthTest(void) { glEnable(GL_DEPTH_TEST); }
{
glEnable(GL_DEPTH_TEST);
}
// Disable depth test // Disable depth test
void rlDisableDepthTest(void) void rlDisableDepthTest(void) { glDisable(GL_DEPTH_TEST); }
{
glDisable(GL_DEPTH_TEST);
}
// Enable backface culling // Enable backface culling
void rlEnableBackfaceCulling(void) void rlEnableBackfaceCulling(void) { glEnable(GL_CULL_FACE); }
{
glEnable(GL_CULL_FACE);
}
// Disable backface culling // Disable backface culling
void rlDisableBackfaceCulling(void) void rlDisableBackfaceCulling(void) { glDisable(GL_CULL_FACE); }
{
glDisable(GL_CULL_FACE); // Enable scissor test
} RLAPI void rlEnableScissorTest(void) { glEnable(GL_SCISSOR_TEST); }
// Disable scissor test
RLAPI void rlDisableScissorTest(void) { glDisable(GL_SCISSOR_TEST); }
// Scissor test
RLAPI void rlScissor(int x, int y, int width, int height) { glScissor(x, y, width, height); }
// Enable wire mode // Enable wire mode
void rlEnableWireMode(void) void rlEnableWireMode(void)
@ -1525,24 +1529,33 @@ void rlglInit(int width, int height)
const char **extList = RL_MALLOC(sizeof(const char *)*numExt); const char **extList = RL_MALLOC(sizeof(const char *)*numExt);
// Get extensions strings // Get extensions strings
for (int i = 0; i < numExt; i++) extList[i] = (char *)glGetStringi(GL_EXTENSIONS, i); for (int i = 0; i < numExt; i++) extList[i] = (const char *)glGetStringi(GL_EXTENSIONS, i);
#elif defined(GRAPHICS_API_OPENGL_ES2) #elif defined(GRAPHICS_API_OPENGL_ES2)
// Allocate 512 strings pointers (2 KB) // Allocate 512 strings pointers (2 KB)
const char **extList = RL_MALLOC(sizeof(const char *)*512); const char **extList = RL_MALLOC(sizeof(const char *)*512);
// Get extensions strings const char *extensions = (const char *)glGetString(GL_EXTENSIONS); // One big const string
char *extensions = (char *)glGetString(GL_EXTENSIONS); // One big static const string returned
int len = strlen(extensions); // NOTE: We have to duplicate string because glGetString() returns a const string
int len = strlen(extensions) + 1;
char *extensionsDup = (char *)RL_CALLOC(len, sizeof(char));
strcpy(extensionsDup, extensions);
extList[numExt] = extensionsDup;
for (int i = 0; i < len; i++) for (int i = 0; i < len; i++)
{ {
if (i == ' ') if (extensionsDup[i] == ' ')
{ {
extList[numExt] = &extensions[i + 1]; extensionsDup[i] = '\0';
numExt++; numExt++;
extList[numExt] = &extensionsDup[i + 1];
} }
} }
// NOTE: Duplicated string (extensionsDup) must be deallocated
#endif #endif
TraceLog(LOG_INFO, "Number of supported extensions: %i", numExt); TraceLog(LOG_INFO, "Number of supported extensions: %i", numExt);
@ -1618,6 +1631,8 @@ void rlglInit(int width, int height)
RL_FREE(extList); RL_FREE(extList);
#if defined(GRAPHICS_API_OPENGL_ES2) #if defined(GRAPHICS_API_OPENGL_ES2)
RL_FREE(extensionsDup); // Duplicated string must be deallocated
if (vaoSupported) TraceLog(LOG_INFO, "[EXTENSION] VAO extension detected, VAO functions initialized successfully"); if (vaoSupported) TraceLog(LOG_INFO, "[EXTENSION] VAO extension detected, VAO functions initialized successfully");
else TraceLog(LOG_WARNING, "[EXTENSION] VAO extension not found, VAO usage not supported"); else TraceLog(LOG_WARNING, "[EXTENSION] VAO extension not found, VAO usage not supported");
@ -1683,7 +1698,6 @@ void rlglInit(int width, int height)
// Initialize OpenGL default states // Initialize OpenGL default states
//---------------------------------------------------------- //----------------------------------------------------------
// Init state: Depth test // Init state: Depth test
glDepthFunc(GL_LEQUAL); // Type of depth testing to apply glDepthFunc(GL_LEQUAL); // Type of depth testing to apply
glDisable(GL_DEPTH_TEST); // Disable depth testing for 2D (only used for 3D) glDisable(GL_DEPTH_TEST); // Disable depth testing for 2D (only used for 3D)
@ -2757,30 +2771,30 @@ void rlDrawMesh(Mesh mesh, Material material, Matrix transform)
} }
// Unload mesh data from CPU and GPU // Unload mesh data from CPU and GPU
void rlUnloadMesh(Mesh *mesh) void rlUnloadMesh(Mesh mesh)
{ {
RL_FREE(mesh->vertices); RL_FREE(mesh.vertices);
RL_FREE(mesh->texcoords); RL_FREE(mesh.texcoords);
RL_FREE(mesh->normals); RL_FREE(mesh.normals);
RL_FREE(mesh->colors); RL_FREE(mesh.colors);
RL_FREE(mesh->tangents); RL_FREE(mesh.tangents);
RL_FREE(mesh->texcoords2); RL_FREE(mesh.texcoords2);
RL_FREE(mesh->indices); RL_FREE(mesh.indices);
RL_FREE(mesh->animVertices); RL_FREE(mesh.animVertices);
RL_FREE(mesh->animNormals); RL_FREE(mesh.animNormals);
RL_FREE(mesh->boneWeights); RL_FREE(mesh.boneWeights);
RL_FREE(mesh->boneIds); RL_FREE(mesh.boneIds);
rlDeleteBuffers(mesh->vboId[0]); // vertex rlDeleteBuffers(mesh.vboId[0]); // vertex
rlDeleteBuffers(mesh->vboId[1]); // texcoords rlDeleteBuffers(mesh.vboId[1]); // texcoords
rlDeleteBuffers(mesh->vboId[2]); // normals rlDeleteBuffers(mesh.vboId[2]); // normals
rlDeleteBuffers(mesh->vboId[3]); // colors rlDeleteBuffers(mesh.vboId[3]); // colors
rlDeleteBuffers(mesh->vboId[4]); // tangents rlDeleteBuffers(mesh.vboId[4]); // tangents
rlDeleteBuffers(mesh->vboId[5]); // texcoords2 rlDeleteBuffers(mesh.vboId[5]); // texcoords2
rlDeleteBuffers(mesh->vboId[6]); // indices rlDeleteBuffers(mesh.vboId[6]); // indices
rlDeleteVertexArrays(mesh->vaoId); rlDeleteVertexArrays(mesh.vaoId);
} }
// Read screen pixel data (color buffer) // Read screen pixel data (color buffer)
@ -2954,6 +2968,8 @@ Shader LoadShader(const char *vsFileName, const char *fsFileName)
{ {
Shader shader = { 0 }; Shader shader = { 0 };
// NOTE: Shader.locs is allocated by LoadShaderCode()
char *vShaderStr = NULL; char *vShaderStr = NULL;
char *fShaderStr = NULL; char *fShaderStr = NULL;
@ -2970,9 +2986,10 @@ Shader LoadShader(const char *vsFileName, const char *fsFileName)
// Load shader from code strings // Load shader from code strings
// NOTE: If shader string is NULL, using default vertex/fragment shaders // NOTE: If shader string is NULL, using default vertex/fragment shaders
Shader LoadShaderCode(char *vsCode, char *fsCode) Shader LoadShaderCode(const char *vsCode, const char *fsCode)
{ {
Shader shader = { 0 }; Shader shader = { 0 };
shader.locs = (int *)RL_CALLOC(MAX_SHADER_LOCATIONS, sizeof(int));
// NOTE: All locations must be reseted to -1 (no location) // NOTE: All locations must be reseted to -1 (no location)
for (int i = 0; i < MAX_SHADER_LOCATIONS; i++) shader.locs[i] = -1; for (int i = 0; i < MAX_SHADER_LOCATIONS; i++) shader.locs[i] = -1;
@ -3008,7 +3025,7 @@ Shader LoadShaderCode(char *vsCode, char *fsCode)
glGetProgramiv(shader.id, GL_ACTIVE_UNIFORMS, &uniformCount); glGetProgramiv(shader.id, GL_ACTIVE_UNIFORMS, &uniformCount);
for(int i = 0; i < uniformCount; i++) for (int i = 0; i < uniformCount; i++)
{ {
int namelen = -1; int namelen = -1;
int num = -1; int num = -1;
@ -3038,6 +3055,8 @@ void UnloadShader(Shader shader)
rlDeleteShader(shader.id); rlDeleteShader(shader.id);
TraceLog(LOG_INFO, "[SHDR ID %i] Unloaded shader program data", shader.id); TraceLog(LOG_INFO, "[SHDR ID %i] Unloaded shader program data", shader.id);
} }
RL_FREE(shader.locs);
} }
// Begin custom shader mode // Begin custom shader mode
@ -3136,6 +3155,23 @@ void SetMatrixProjection(Matrix proj)
#endif #endif
} }
// Return internal projection matrix
Matrix GetMatrixProjection(void) {
#if defined(GRAPHICS_API_OPENGL_11)
float mat[16];
glGetFloatv(GL_PROJECTION_MATRIX,mat);
Matrix m;
m.m0 = mat[0]; m.m1 = mat[1]; m.m2 = mat[2]; m.m3 = mat[3];
m.m4 = mat[4]; m.m5 = mat[5]; m.m6 = mat[6]; m.m7 = mat[7];
m.m8 = mat[8]; m.m9 = mat[9]; m.m10 = mat[10]; m.m11 = mat[11];
m.m12 = mat[12]; m.m13 = mat[13]; m.m14 = mat[14]; m.m15 = mat[15];
return m;
#else
return projection;
#endif
#
}
// Set a custom modelview matrix (replaces internal modelview matrix) // Set a custom modelview matrix (replaces internal modelview matrix)
void SetMatrixModelview(Matrix view) void SetMatrixModelview(Matrix view)
{ {
@ -3151,6 +3187,10 @@ Matrix GetMatrixModelview(void)
#if defined(GRAPHICS_API_OPENGL_11) #if defined(GRAPHICS_API_OPENGL_11)
float mat[16]; float mat[16];
glGetFloatv(GL_MODELVIEW_MATRIX, mat); glGetFloatv(GL_MODELVIEW_MATRIX, mat);
matrix.m0 = mat[0]; matrix.m1 = mat[1]; matrix.m2 = mat[2]; matrix.m3 = mat[3];
matrix.m4 = mat[4]; matrix.m5 = mat[5]; matrix.m6 = mat[6]; matrix.m7 = mat[7];
matrix.m8 = mat[8]; matrix.m9 = mat[9]; matrix.m10 = mat[10]; matrix.m11 = mat[11];
matrix.m12 = mat[12]; matrix.m13 = mat[13]; matrix.m14 = mat[14]; matrix.m15 = mat[15];
#else #else
matrix = modelview; matrix = modelview;
#endif #endif
@ -3505,24 +3545,6 @@ void EndBlendMode(void)
BeginBlendMode(BLEND_ALPHA); BeginBlendMode(BLEND_ALPHA);
} }
// Begin scissor mode (define screen area for following drawing)
// NOTE: Scissor rec refers to bottom-left corner, we change it to upper-left
void BeginScissorMode(int x, int y, int width, int height)
{
rlglDraw(); // Force drawing elements
glEnable(GL_SCISSOR_TEST);
glScissor(x, framebufferHeight - (y + height), width, height);
}
// End scissor mode
void EndScissorMode(void)
{
rlglDraw(); // Force drawing elements
glDisable(GL_SCISSOR_TEST);
}
#if defined(SUPPORT_VR_SIMULATOR) #if defined(SUPPORT_VR_SIMULATOR)
// Init VR simulator for selected device parameters // Init VR simulator for selected device parameters
// NOTE: It modifies the global variable: stereoFbo // NOTE: It modifies the global variable: stereoFbo
@ -3861,12 +3883,13 @@ static unsigned int LoadShaderProgram(unsigned int vShaderId, unsigned int fShad
static Shader LoadShaderDefault(void) static Shader LoadShaderDefault(void)
{ {
Shader shader = { 0 }; Shader shader = { 0 };
shader.locs = (int *)RL_CALLOC(MAX_SHADER_LOCATIONS, sizeof(int));
// NOTE: All locations must be reseted to -1 (no location) // NOTE: All locations must be reseted to -1 (no location)
for (int i = 0; i < MAX_SHADER_LOCATIONS; i++) shader.locs[i] = -1; for (int i = 0; i < MAX_SHADER_LOCATIONS; i++) shader.locs[i] = -1;
// Vertex shader directly defined, no external file required // Vertex shader directly defined, no external file required
char defaultVShaderStr[] = const char *defaultVShaderStr =
#if defined(GRAPHICS_API_OPENGL_21) #if defined(GRAPHICS_API_OPENGL_21)
"#version 120 \n" "#version 120 \n"
#elif defined(GRAPHICS_API_OPENGL_ES2) #elif defined(GRAPHICS_API_OPENGL_ES2)
@ -3895,7 +3918,7 @@ static Shader LoadShaderDefault(void)
"} \n"; "} \n";
// Fragment shader directly defined, no external file required // Fragment shader directly defined, no external file required
char defaultFShaderStr[] = const char *defaultFShaderStr =
#if defined(GRAPHICS_API_OPENGL_21) #if defined(GRAPHICS_API_OPENGL_21)
"#version 120 \n" "#version 120 \n"
#elif defined(GRAPHICS_API_OPENGL_ES2) #elif defined(GRAPHICS_API_OPENGL_ES2)
@ -4615,6 +4638,14 @@ int GetPixelDataSize(int width, int height, int format)
dataSize = width*height*bpp/8; // Total data size in bytes dataSize = width*height*bpp/8; // Total data size in bytes
// Most compressed formats works on 4x4 blocks,
// if texture is smaller, minimum dataSize is 8 or 16
if ((width < 4) && (height < 4))
{
if ((format >= COMPRESSED_DXT1_RGB) && (format < COMPRESSED_DXT3_RGBA)) dataSize = 8;
else if ((format >= COMPRESSED_DXT3_RGBA) && (format < COMPRESSED_ASTC_8x8_RGBA)) dataSize = 16;
}
return dataSize; return dataSize;
} }
#endif // RLGL_STANDALONE #endif // RLGL_STANDALONE

View File

@ -5,7 +5,7 @@
* A quick, efficient, and minimal free list and stack-based allocator * A quick, efficient, and minimal free list and stack-based allocator
* *
* PURPOSE: * PURPOSE:
* - Aquicker, efficient memory allocator alternative to 'malloc' and friends. * - A quicker, efficient memory allocator alternative to 'malloc' and friends.
* - Reduce the possibilities of memory leaks for beginner developers using Raylib. * - Reduce the possibilities of memory leaks for beginner developers using Raylib.
* - Being able to flexibly range check memory if necessary. * - Being able to flexibly range check memory if necessary.
* *
@ -168,21 +168,6 @@ static inline size_t __AlignSize(const size_t size, const size_t align)
return (size + (align - 1)) & -align; return (size + (align - 1)) & -align;
} }
static void __RemoveNode(MemPool *const mempool, MemNode **const node)
{
if ((*node)->next != NULL) (*node)->next->prev = (*node)->prev;
else {
mempool->freeList.tail = (*node)->prev;
if (mempool->freeList.tail != NULL) mempool->freeList.tail->next = NULL;
}
if ((*node)->prev != NULL) (*node)->prev->next = (*node)->next;
else {
mempool->freeList.head = (*node)->next;
if (mempool->freeList.head != NULL) mempool->freeList.head->prev = NULL;
}
}
//---------------------------------------------------------------------------------- //----------------------------------------------------------------------------------
// Module Functions Definition - Memory Pool // Module Functions Definition - Memory Pool
//---------------------------------------------------------------------------------- //----------------------------------------------------------------------------------
@ -244,6 +229,7 @@ void *MemPoolAlloc(MemPool *const mempool, const size_t size)
const size_t ALLOC_SIZE = __AlignSize(size + sizeof *new_mem, sizeof(intptr_t)); const size_t ALLOC_SIZE = __AlignSize(size + sizeof *new_mem, sizeof(intptr_t));
const size_t BUCKET_INDEX = (ALLOC_SIZE >> MEMPOOL_BUCKET_BITS) - 1; const size_t BUCKET_INDEX = (ALLOC_SIZE >> MEMPOOL_BUCKET_BITS) - 1;
// If the size is small enough, let's check if our buckets has a fitting memory block.
if (BUCKET_INDEX < MEMPOOL_BUCKET_SIZE && mempool->buckets[BUCKET_INDEX] != NULL && mempool->buckets[BUCKET_INDEX]->size >= ALLOC_SIZE) if (BUCKET_INDEX < MEMPOOL_BUCKET_SIZE && mempool->buckets[BUCKET_INDEX] != NULL && mempool->buckets[BUCKET_INDEX]->size >= ALLOC_SIZE)
{ {
new_mem = mempool->buckets[BUCKET_INDEX]; new_mem = mempool->buckets[BUCKET_INDEX];
@ -256,22 +242,28 @@ void *MemPoolAlloc(MemPool *const mempool, const size_t size)
const size_t MEM_SPLIT_THRESHOLD = 16; const size_t MEM_SPLIT_THRESHOLD = 16;
// If the freelist is valid, let's allocate FROM the freelist then! // If the freelist is valid, let's allocate FROM the freelist then!
for (MemNode **inode = &mempool->freeList.head; *inode != NULL; inode = &(*inode)->next) for (MemNode *inode = mempool->freeList.head; inode != NULL; inode = inode->next)
{ {
if ((*inode)->size < ALLOC_SIZE) continue; if (inode->size < ALLOC_SIZE) continue;
else if ((*inode)->size <= (ALLOC_SIZE + MEM_SPLIT_THRESHOLD)) else if (inode->size <= (ALLOC_SIZE + MEM_SPLIT_THRESHOLD))
{ {
// Close in size - reduce fragmentation by not splitting. // Close in size - reduce fragmentation by not splitting.
new_mem = *inode; new_mem = inode;
__RemoveNode(mempool, inode); (inode->prev != NULL)? (inode->prev->next = inode->next) : (mempool->freeList.head = inode->next);
(inode->next != NULL)? (inode->next->prev = inode->prev) : (mempool->freeList.tail = inode->prev);
if (mempool->freeList.head != NULL) mempool->freeList.head->prev = NULL;
else mempool->freeList.tail = NULL;
if (mempool->freeList.tail != NULL) mempool->freeList.tail->next = NULL;
mempool->freeList.len--; mempool->freeList.len--;
break; break;
} }
else else
{ {
// Split the memory chunk. // Split the memory chunk.
new_mem = (MemNode *)((uint8_t *)*inode + ((*inode)->size - ALLOC_SIZE)); new_mem = (MemNode *)((uint8_t *)inode + (inode->size - ALLOC_SIZE));
(*inode)->size -= ALLOC_SIZE; inode->size -= ALLOC_SIZE;
new_mem->size = ALLOC_SIZE; new_mem->size = ALLOC_SIZE;
break; break;
} }
@ -356,13 +348,13 @@ void MemPoolFree(MemPool *const restrict mempool, void *ptr)
// attempted stack merge failed, try to place it into the memnode buckets // attempted stack merge failed, try to place it into the memnode buckets
else if (BUCKET_INDEX < MEMPOOL_BUCKET_SIZE) else if (BUCKET_INDEX < MEMPOOL_BUCKET_SIZE)
{ {
if (mempool->buckets[index] == NULL) mempool->buckets[index] = node; if (mempool->buckets[BUCKET_INDEX] == NULL) mempool->buckets[BUCKET_INDEX] = mem_node;
else else
{ {
for (MemNode *n = mempool->buckets[index]; n != NULL; n = n->next) if( n==node ) return; for (MemNode *n = mempool->buckets[BUCKET_INDEX]; n != NULL; n = n->next) if( n==mem_node ) return;
mempool->buckets[index]->prev = node; mempool->buckets[BUCKET_INDEX]->prev = mem_node;
node->next = mempool->buckets[index]; mem_node->next = mempool->buckets[BUCKET_INDEX];
mempool->buckets[index] = node; mempool->buckets[BUCKET_INDEX] = mem_node;
} }
} }
// Otherwise, we add it to the free list. // Otherwise, we add it to the free list.
@ -459,7 +451,13 @@ bool MemPoolDefrag(MemPool *const mempool)
// If node is right at the stack, merge it back into the stack. // If node is right at the stack, merge it back into the stack.
mempool->stack.base += (*node)->size; mempool->stack.base += (*node)->size;
(*node)->size = 0UL; (*node)->size = 0UL;
__RemoveNode(mempool, node); ((*node)->prev != NULL)? ((*node)->prev->next = (*node)->next) : (mempool->freeList.head = (*node)->next);
((*node)->next != NULL)? ((*node)->next->prev = (*node)->prev) : (mempool->freeList.tail = (*node)->prev);
if (mempool->freeList.head != NULL) mempool->freeList.head->prev = NULL;
else mempool->freeList.tail = NULL;
if (mempool->freeList.tail != NULL) mempool->freeList.tail->next = NULL;
mempool->freeList.len--; mempool->freeList.len--;
node = &mempool->freeList.head; node = &mempool->freeList.head;
} }

View File

@ -1179,6 +1179,7 @@ void DrawRectangleRoundedLines(Rectangle rec, float roundness, int segments, int
} }
// Draw a triangle // Draw a triangle
// NOTE: Vertex must be provided in counter-clockwise order
void DrawTriangle(Vector2 v1, Vector2 v2, Vector2 v3, Color color) void DrawTriangle(Vector2 v1, Vector2 v2, Vector2 v3, Color color)
{ {
if (rlCheckBufferLimit(4)) rlglDraw(); if (rlCheckBufferLimit(4)) rlglDraw();
@ -1214,6 +1215,7 @@ void DrawTriangle(Vector2 v1, Vector2 v2, Vector2 v3, Color color)
} }
// Draw a triangle using lines // Draw a triangle using lines
// NOTE: Vertex must be provided in counter-clockwise order
void DrawTriangleLines(Vector2 v1, Vector2 v2, Vector2 v3, Color color) void DrawTriangleLines(Vector2 v1, Vector2 v2, Vector2 v3, Color color)
{ {
if (rlCheckBufferLimit(6)) rlglDraw(); if (rlCheckBufferLimit(6)) rlglDraw();
@ -1232,7 +1234,7 @@ void DrawTriangleLines(Vector2 v1, Vector2 v2, Vector2 v3, Color color)
} }
// Draw a triangle fan defined by points // Draw a triangle fan defined by points
// NOTE: First point provided is shared by all triangles // NOTE: First vertex provided is the center, shared by all triangles
void DrawTriangleFan(Vector2 *points, int pointsCount, Color color) void DrawTriangleFan(Vector2 *points, int pointsCount, Color color)
{ {
if (pointsCount >= 3) if (pointsCount >= 3)
@ -1263,7 +1265,7 @@ void DrawTriangleFan(Vector2 *points, int pointsCount, Color color)
} }
// Draw a triangle strip defined by points // Draw a triangle strip defined by points
// NOTE: Every new point connects with previous two // NOTE: Every new vertex connects with previous two
void DrawTriangleStrip(Vector2 *points, int pointsCount, Color color) void DrawTriangleStrip(Vector2 *points, int pointsCount, Color color)
{ {
if (pointsCount >= 3) if (pointsCount >= 3)
@ -1296,6 +1298,7 @@ void DrawTriangleStrip(Vector2 *points, int pointsCount, Color color)
void DrawPoly(Vector2 center, int sides, float radius, float rotation, Color color) void DrawPoly(Vector2 center, int sides, float radius, float rotation, Color color)
{ {
if (sides < 3) sides = 3; if (sides < 3) sides = 3;
float centralAngle = 0.0f;
if (rlCheckBufferLimit(4*(360/sides))) rlglDraw(); if (rlCheckBufferLimit(4*(360/sides))) rlglDraw();
@ -1307,7 +1310,7 @@ void DrawPoly(Vector2 center, int sides, float radius, float rotation, Color col
rlEnableTexture(GetShapesTexture().id); rlEnableTexture(GetShapesTexture().id);
rlBegin(RL_QUADS); rlBegin(RL_QUADS);
for (int i = 0; i < 360; i += 360/sides) for (int i = 0; i < sides; i++)
{ {
rlColor4ub(color.r, color.g, color.b, color.a); rlColor4ub(color.r, color.g, color.b, color.a);
@ -1315,25 +1318,28 @@ void DrawPoly(Vector2 center, int sides, float radius, float rotation, Color col
rlVertex2f(0, 0); rlVertex2f(0, 0);
rlTexCoord2f(recTexShapes.x/texShapes.width, (recTexShapes.y + recTexShapes.height)/texShapes.height); rlTexCoord2f(recTexShapes.x/texShapes.width, (recTexShapes.y + recTexShapes.height)/texShapes.height);
rlVertex2f(sinf(DEG2RAD*i)*radius, cosf(DEG2RAD*i)*radius); rlVertex2f(sinf(DEG2RAD*centralAngle)*radius, cosf(DEG2RAD*centralAngle)*radius);
rlTexCoord2f((recTexShapes.x + recTexShapes.width)/texShapes.width, (recTexShapes.y + recTexShapes.height)/texShapes.height); rlTexCoord2f((recTexShapes.x + recTexShapes.width)/texShapes.width, (recTexShapes.y + recTexShapes.height)/texShapes.height);
rlVertex2f(sinf(DEG2RAD*i)*radius, cosf(DEG2RAD*i)*radius); rlVertex2f(sinf(DEG2RAD*centralAngle)*radius, cosf(DEG2RAD*centralAngle)*radius);
centralAngle += 360.0f/(float)sides;
rlTexCoord2f((recTexShapes.x + recTexShapes.width)/texShapes.width, recTexShapes.y/texShapes.height); rlTexCoord2f((recTexShapes.x + recTexShapes.width)/texShapes.width, recTexShapes.y/texShapes.height);
rlVertex2f(sinf(DEG2RAD*(i + 360/sides))*radius, cosf(DEG2RAD*(i + 360/sides))*radius); rlVertex2f(sinf(DEG2RAD*centralAngle)*radius, cosf(DEG2RAD*centralAngle)*radius);
} }
rlEnd(); rlEnd();
rlDisableTexture(); rlDisableTexture();
#else #else
rlBegin(RL_TRIANGLES); rlBegin(RL_TRIANGLES);
for (int i = 0; i < 360; i += 360/sides) for (int i = 0; i < sides; i++)
{ {
rlColor4ub(color.r, color.g, color.b, color.a); rlColor4ub(color.r, color.g, color.b, color.a);
rlVertex2f(0, 0); rlVertex2f(0, 0);
rlVertex2f(sinf(DEG2RAD*i)*radius, cosf(DEG2RAD*i)*radius); rlVertex2f(sinf(DEG2RAD*centralAngle)*radius, cosf(DEG2RAD*centralAngle)*radius);
rlVertex2f(sinf(DEG2RAD*(i + 360/sides))*radius, cosf(DEG2RAD*(i + 360/sides))*radius);
centralAngle += 360.0f/(float)sides;
rlVertex2f(sinf(DEG2RAD*centralAngle)*radius, cosf(DEG2RAD*centralAngle)*radius);
} }
rlEnd(); rlEnd();
#endif #endif
@ -1390,8 +1396,8 @@ bool CheckCollisionRecs(Rectangle rec1, Rectangle rec2)
{ {
bool collision = false; bool collision = false;
if ((rec1.x <= (rec2.x + rec2.width) && (rec1.x + rec1.width) >= rec2.x) && if ((rec1.x < (rec2.x + rec2.width) && (rec1.x + rec1.width) > rec2.x) &&
(rec1.y <= (rec2.y + rec2.height) && (rec1.y + rec1.height) >= rec2.y)) collision = true; (rec1.y < (rec2.y + rec2.height) && (rec1.y + rec1.height) > rec2.y)) collision = true;
return collision; return collision;
} }

View File

@ -10,9 +10,19 @@
* supported by default, to remove support, just comment unrequired #define in this module * supported by default, to remove support, just comment unrequired #define in this module
* *
* #define SUPPORT_DEFAULT_FONT * #define SUPPORT_DEFAULT_FONT
* Load default raylib font on initialization to be used by DrawText() and MeasureText().
* If no default font loaded, DrawTextEx() and MeasureTextEx() are required.
*
* #define TEXTSPLIT_MAX_TEXT_BUFFER_LENGTH
* TextSplit() function static buffer max size
*
* #define TEXTSPLIT_MAX_SUBSTRINGS_COUNT
* TextSplit() function static substrings pointers array (pointing to static buffer)
*
* *
* DEPENDENCIES: * DEPENDENCIES:
* stb_truetype - Load TTF file and rasterize characters data * stb_truetype - Load TTF file and rasterize characters data
* stb_rect_pack - Rectangles packing algorythms, required for font atlas generation
* *
* *
* LICENSE: zlib/libpng * LICENSE: zlib/libpng
@ -63,7 +73,18 @@
//---------------------------------------------------------------------------------- //----------------------------------------------------------------------------------
// Defines and Macros // Defines and Macros
//---------------------------------------------------------------------------------- //----------------------------------------------------------------------------------
#define MAX_TEXT_BUFFER_LENGTH 1024 // Size of internal static buffers of some Text*() functions #define MAX_TEXT_BUFFER_LENGTH 1024 // Size of internal static buffers used on some functions:
// TextFormat(), TextSubtext(), TextToUpper(), TextToLower(), TextToPascal()
#define MAX_TEXT_UNICODE_CHARS 512 // Maximum number of unicode codepoints
#if !defined(TEXTSPLIT_MAX_TEXT_BUFFER_LENGTH)
#define TEXTSPLIT_MAX_TEXT_BUFFER_LENGTH 1024 // Size of static buffer: TextSplit()
#endif
#if !defined(TEXTSPLIT_MAX_SUBSTRINGS_COUNT)
#define TEXTSPLIT_MAX_SUBSTRINGS_COUNT 128 // Size of static pointers array: TextSplit()
#endif
//---------------------------------------------------------------------------------- //----------------------------------------------------------------------------------
// Types and Structures Definition // Types and Structures Definition
@ -282,7 +303,7 @@ Font LoadFont(const char *fileName)
Font font = { 0 }; Font font = { 0 };
#if defined(SUPPORT_FILEFORMAT_TTF) #if defined(SUPPORT_FILEFORMAT_TTF)
if (IsFileExtension(fileName, ".ttf") || IsFileExtension(fileName, ".otf")) font = LoadFontEx(fileName, DEFAULT_TTF_FONTSIZE, NULL, DEFAULT_TTF_NUMCHARS); if (IsFileExtension(fileName, ".ttf;.otf")) font = LoadFontEx(fileName, DEFAULT_TTF_FONTSIZE, NULL, DEFAULT_TTF_NUMCHARS);
else else
#endif #endif
#if defined(SUPPORT_FILEFORMAT_FNT) #if defined(SUPPORT_FILEFORMAT_FNT)
@ -586,7 +607,7 @@ Image GenImageFontAtlas(const CharInfo *chars, Rectangle **charRecs, int charsCo
*charRecs = NULL; *charRecs = NULL;
// In case no chars count provided we suppose default of 95 // In case no chars count provided we suppose default of 95
charsCount = (charsCount > 0) ? charsCount : 95; charsCount = (charsCount > 0)? charsCount : 95;
// NOTE: Rectangles memory is loaded here! // NOTE: Rectangles memory is loaded here!
Rectangle *recs = (Rectangle *)RL_MALLOC(charsCount*sizeof(Rectangle)); Rectangle *recs = (Rectangle *)RL_MALLOC(charsCount*sizeof(Rectangle));
@ -597,7 +618,7 @@ Image GenImageFontAtlas(const CharInfo *chars, Rectangle **charRecs, int charsCo
// so image size would result bigger than default font type // so image size would result bigger than default font type
float requiredArea = 0; float requiredArea = 0;
for (int i = 0; i < charsCount; i++) requiredArea += ((chars[i].image.width + 2*padding)*(chars[i].image.height + 2*padding)); for (int i = 0; i < charsCount; i++) requiredArea += ((chars[i].image.width + 2*padding)*(chars[i].image.height + 2*padding));
float guessSize = sqrtf(requiredArea)*1.25f; float guessSize = sqrtf(requiredArea)*1.3f;
int imageSize = (int)powf(2, ceilf(logf((float)guessSize)/logf(2))); // Calculate next POT int imageSize = (int)powf(2, ceilf(logf((float)guessSize)/logf(2))); // Calculate next POT
atlas.width = imageSize; // Atlas bitmap width atlas.width = imageSize; // Atlas bitmap width
@ -756,120 +777,6 @@ void DrawFPS(int posX, int posY)
DrawText(TextFormat("%2i FPS", fps), posX, posY, 20, LIME); DrawText(TextFormat("%2i FPS", fps), posX, posY, 20, LIME);
} }
// Returns next codepoint in a UTF8 encoded text, scanning until '\0' is found
// When a invalid UTF8 byte is encountered we exit as soon as possible and a '?'(0x3f) codepoint is returned
// Total number of bytes processed are returned as a parameter
// NOTE: the standard says U+FFFD should be returned in case of errors
// but that character is not supported by the default font in raylib
// TODO: optimize this code for speed!!
int GetNextCodepoint(const char *text, int *bytesProcessed)
{
/*
UTF8 specs from https://www.ietf.org/rfc/rfc3629.txt
Char. number range | UTF-8 octet sequence
(hexadecimal) | (binary)
--------------------+---------------------------------------------
0000 0000-0000 007F | 0xxxxxxx
0000 0080-0000 07FF | 110xxxxx 10xxxxxx
0000 0800-0000 FFFF | 1110xxxx 10xxxxxx 10xxxxxx
0001 0000-0010 FFFF | 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
*/
// NOTE: on decode errors we return as soon as possible
int code = 0x3f; // Codepoint (defaults to '?')
int octet = (unsigned char)(text[0]); // The first UTF8 octet
*bytesProcessed = 1;
if (octet <= 0x7f)
{
// Only one octet (ASCII range x00-7F)
code = text[0];
}
else if ((octet & 0xe0) == 0xc0)
{
// Two octets
// [0]xC2-DF [1]UTF8-tail(x80-BF)
unsigned char octet1 = text[1];
if ((octet1 == '\0') || ((octet1 >> 6) != 2)) { *bytesProcessed = 2; return code; } // Unexpected sequence
if ((octet >= 0xc2) && (octet <= 0xdf))
{
code = ((octet & 0x1f) << 6) | (octet1 & 0x3f);
*bytesProcessed = 2;
}
}
else if ((octet & 0xf0) == 0xe0)
{
// Three octets
unsigned char octet1 = text[1];
unsigned char octet2 = '\0';
if ((octet1 == '\0') || ((octet1 >> 6) != 2)) { *bytesProcessed = 2; return code; } // Unexpected sequence
octet2 = text[2];
if ((octet2 == '\0') || ((octet2 >> 6) != 2)) { *bytesProcessed = 3; return code; } // Unexpected sequence
/*
[0]xE0 [1]xA0-BF [2]UTF8-tail(x80-BF)
[0]xE1-EC [1]UTF8-tail [2]UTF8-tail(x80-BF)
[0]xED [1]x80-9F [2]UTF8-tail(x80-BF)
[0]xEE-EF [1]UTF8-tail [2]UTF8-tail(x80-BF)
*/
if (((octet == 0xe0) && !((octet1 >= 0xa0) && (octet1 <= 0xbf))) ||
((octet == 0xed) && !((octet1 >= 0x80) && (octet1 <= 0x9f)))) { *bytesProcessed = 2; return code; }
if ((octet >= 0xe0) && (0 <= 0xef))
{
code = ((octet & 0xf) << 12) | ((octet1 & 0x3f) << 6) | (octet2 & 0x3f);
*bytesProcessed = 3;
}
}
else if ((octet & 0xf8) == 0xf0)
{
// Four octets
if (octet > 0xf4) return code;
unsigned char octet1 = text[1];
unsigned char octet2 = '\0';
unsigned char octet3 = '\0';
if ((octet1 == '\0') || ((octet1 >> 6) != 2)) { *bytesProcessed = 2; return code; } // Unexpected sequence
octet2 = text[2];
if ((octet2 == '\0') || ((octet2 >> 6) != 2)) { *bytesProcessed = 3; return code; } // Unexpected sequence
octet3 = text[3];
if ((octet3 == '\0') || ((octet3 >> 6) != 2)) { *bytesProcessed = 4; return code; } // Unexpected sequence
/*
[0]xF0 [1]x90-BF [2]UTF8-tail [3]UTF8-tail
[0]xF1-F3 [1]UTF8-tail [2]UTF8-tail [3]UTF8-tail
[0]xF4 [1]x80-8F [2]UTF8-tail [3]UTF8-tail
*/
if (((octet == 0xf0) && !((octet1 >= 0x90) && (octet1 <= 0xbf))) ||
((octet == 0xf4) && !((octet1 >= 0x80) && (octet1 <= 0x8f)))) { *bytesProcessed = 2; return code; } // Unexpected sequence
if (octet >= 0xf0)
{
code = ((octet & 0x7) << 18) | ((octet1 & 0x3f) << 12) | ((octet2 & 0x3f) << 6) | (octet3 & 0x3f);
*bytesProcessed = 4;
}
}
if (code > 0x10ffff) code = 0x3f; // Codepoints after U+10ffff are invalid
return code;
}
// Draw text (using default font) // Draw text (using default font)
// NOTE: fontSize work like in any drawing program but if fontSize is lower than font-base-size, then font-base-size is used // NOTE: fontSize work like in any drawing program but if fontSize is lower than font-base-size, then font-base-size is used
// NOTE: chars spacing is proportional to fontSize // NOTE: chars spacing is proportional to fontSize
@ -1194,27 +1101,6 @@ unsigned int TextLength(const char *text)
return length; return length;
} }
// Returns total number of characters(codepoints) in a UTF8 encoded text, until '\0' is found
// NOTE: If an invalid UTF8 sequence is encountered a '?'(0x3f) codepoint is counted instead
unsigned int TextCountCodepoints(const char *text)
{
unsigned int len = 0;
char *ptr = (char *)&text[0];
while (*ptr != '\0')
{
int next = 0;
int letter = GetNextCodepoint(ptr, &next);
if (letter == 0x3f) ptr += 1;
else ptr += next;
len++;
}
return len;
}
// Formatting of text with variables to 'embed' // Formatting of text with variables to 'embed'
const char *TextFormat(const char *text, ...) const char *TextFormat(const char *text, ...)
{ {
@ -1362,17 +1248,19 @@ const char **TextSplit(const char *text, char delimiter, int *count)
// NOTE: Current implementation returns a copy of the provided string with '\0' (string end delimiter) // NOTE: Current implementation returns a copy of the provided string with '\0' (string end delimiter)
// inserted between strings defined by "delimiter" parameter. No memory is dynamically allocated, // inserted between strings defined by "delimiter" parameter. No memory is dynamically allocated,
// all used memory is static... it has some limitations: // all used memory is static... it has some limitations:
// 1. Maximum number of possible split strings is set by MAX_SUBSTRINGS_COUNT // 1. Maximum number of possible split strings is set by TEXTSPLIT_MAX_SUBSTRINGS_COUNT
// 2. Maximum size of text to split is MAX_TEXT_BUFFER_LENGTH // 2. Maximum size of text to split is TEXTSPLIT_MAX_TEXT_BUFFER_LENGTH
#define MAX_SUBSTRINGS_COUNT 64 static const char *result[TEXTSPLIT_MAX_SUBSTRINGS_COUNT] = { NULL };
static char buffer[TEXTSPLIT_MAX_TEXT_BUFFER_LENGTH] = { 0 };
static const char *result[MAX_SUBSTRINGS_COUNT] = { NULL }; memset(buffer, 0, TEXTSPLIT_MAX_TEXT_BUFFER_LENGTH);
static char buffer[MAX_TEXT_BUFFER_LENGTH] = { 0 };
memset(buffer, 0, MAX_TEXT_BUFFER_LENGTH);
result[0] = buffer; result[0] = buffer;
int counter = 1; int counter = 0;
if (text != NULL)
{
counter = 1;
// Count how many substrings we have on text and point to every one // Count how many substrings we have on text and point to every one
for (int i = 0; i < MAX_TEXT_BUFFER_LENGTH; i++) for (int i = 0; i < MAX_TEXT_BUFFER_LENGTH; i++)
@ -1385,7 +1273,8 @@ const char **TextSplit(const char *text, char delimiter, int *count)
result[counter] = buffer + i + 1; result[counter] = buffer + i + 1;
counter++; counter++;
if (counter == MAX_SUBSTRINGS_COUNT) break; if (counter == TEXTSPLIT_MAX_SUBSTRINGS_COUNT) break;
}
} }
} }
@ -1487,6 +1376,221 @@ int TextToInteger(const char *text)
return result; return result;
} }
// Encode text codepoint into utf8 text (memory must be freed!)
char *TextToUtf8(int *codepoints, int length)
{
// We allocate enough memory fo fit all possible codepoints
// NOTE: 5 bytes for every codepoint should be enough
char *text = (char *)calloc(length*5, 1);
const char *utf8 = NULL;
int size = 0;
for (int i = 0, bytes = 0; i < length; i++)
{
utf8 = CodepointToUtf8(codepoints[i], &bytes);
strncpy(text + size, utf8, bytes);
size += bytes;
}
// Resize memory to text length + string NULL terminator
realloc(text, size + 1);
return text;
}
// Get all codepoints in a string, codepoints count returned by parameters
int *GetCodepoints(const char *text, int *count)
{
static int codepoints[MAX_TEXT_UNICODE_CHARS] = { 0 };
memset(codepoints, 0, MAX_TEXT_UNICODE_CHARS*sizeof(int));
int bytesProcessed = 0;
int textLength = strlen(text);
int codepointsCount = 0;
for (int i = 0; i < textLength; codepointsCount++)
{
codepoints[codepointsCount] = GetNextCodepoint(text + i, &bytesProcessed);
i += bytesProcessed;
}
*count = codepointsCount;
return codepoints;
}
// Returns total number of characters(codepoints) in a UTF8 encoded text, until '\0' is found
// NOTE: If an invalid UTF8 sequence is encountered a '?'(0x3f) codepoint is counted instead
int GetCodepointsCount(const char *text)
{
unsigned int len = 0;
char *ptr = (char *)&text[0];
while (*ptr != '\0')
{
int next = 0;
int letter = GetNextCodepoint(ptr, &next);
if (letter == 0x3f) ptr += 1;
else ptr += next;
len++;
}
return len;
}
// Returns next codepoint in a UTF8 encoded text, scanning until '\0' is found
// When a invalid UTF8 byte is encountered we exit as soon as possible and a '?'(0x3f) codepoint is returned
// Total number of bytes processed are returned as a parameter
// NOTE: the standard says U+FFFD should be returned in case of errors
// but that character is not supported by the default font in raylib
// TODO: optimize this code for speed!!
int GetNextCodepoint(const char *text, int *bytesProcessed)
{
/*
UTF8 specs from https://www.ietf.org/rfc/rfc3629.txt
Char. number range | UTF-8 octet sequence
(hexadecimal) | (binary)
--------------------+---------------------------------------------
0000 0000-0000 007F | 0xxxxxxx
0000 0080-0000 07FF | 110xxxxx 10xxxxxx
0000 0800-0000 FFFF | 1110xxxx 10xxxxxx 10xxxxxx
0001 0000-0010 FFFF | 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
*/
// NOTE: on decode errors we return as soon as possible
int code = 0x3f; // Codepoint (defaults to '?')
int octet = (unsigned char)(text[0]); // The first UTF8 octet
*bytesProcessed = 1;
if (octet <= 0x7f)
{
// Only one octet (ASCII range x00-7F)
code = text[0];
}
else if ((octet & 0xe0) == 0xc0)
{
// Two octets
// [0]xC2-DF [1]UTF8-tail(x80-BF)
unsigned char octet1 = text[1];
if ((octet1 == '\0') || ((octet1 >> 6) != 2)) { *bytesProcessed = 2; return code; } // Unexpected sequence
if ((octet >= 0xc2) && (octet <= 0xdf))
{
code = ((octet & 0x1f) << 6) | (octet1 & 0x3f);
*bytesProcessed = 2;
}
}
else if ((octet & 0xf0) == 0xe0)
{
// Three octets
unsigned char octet1 = text[1];
unsigned char octet2 = '\0';
if ((octet1 == '\0') || ((octet1 >> 6) != 2)) { *bytesProcessed = 2; return code; } // Unexpected sequence
octet2 = text[2];
if ((octet2 == '\0') || ((octet2 >> 6) != 2)) { *bytesProcessed = 3; return code; } // Unexpected sequence
/*
[0]xE0 [1]xA0-BF [2]UTF8-tail(x80-BF)
[0]xE1-EC [1]UTF8-tail [2]UTF8-tail(x80-BF)
[0]xED [1]x80-9F [2]UTF8-tail(x80-BF)
[0]xEE-EF [1]UTF8-tail [2]UTF8-tail(x80-BF)
*/
if (((octet == 0xe0) && !((octet1 >= 0xa0) && (octet1 <= 0xbf))) ||
((octet == 0xed) && !((octet1 >= 0x80) && (octet1 <= 0x9f)))) { *bytesProcessed = 2; return code; }
if ((octet >= 0xe0) && (0 <= 0xef))
{
code = ((octet & 0xf) << 12) | ((octet1 & 0x3f) << 6) | (octet2 & 0x3f);
*bytesProcessed = 3;
}
}
else if ((octet & 0xf8) == 0xf0)
{
// Four octets
if (octet > 0xf4) return code;
unsigned char octet1 = text[1];
unsigned char octet2 = '\0';
unsigned char octet3 = '\0';
if ((octet1 == '\0') || ((octet1 >> 6) != 2)) { *bytesProcessed = 2; return code; } // Unexpected sequence
octet2 = text[2];
if ((octet2 == '\0') || ((octet2 >> 6) != 2)) { *bytesProcessed = 3; return code; } // Unexpected sequence
octet3 = text[3];
if ((octet3 == '\0') || ((octet3 >> 6) != 2)) { *bytesProcessed = 4; return code; } // Unexpected sequence
/*
[0]xF0 [1]x90-BF [2]UTF8-tail [3]UTF8-tail
[0]xF1-F3 [1]UTF8-tail [2]UTF8-tail [3]UTF8-tail
[0]xF4 [1]x80-8F [2]UTF8-tail [3]UTF8-tail
*/
if (((octet == 0xf0) && !((octet1 >= 0x90) && (octet1 <= 0xbf))) ||
((octet == 0xf4) && !((octet1 >= 0x80) && (octet1 <= 0x8f)))) { *bytesProcessed = 2; return code; } // Unexpected sequence
if (octet >= 0xf0)
{
code = ((octet & 0x7) << 18) | ((octet1 & 0x3f) << 12) | ((octet2 & 0x3f) << 6) | (octet3 & 0x3f);
*bytesProcessed = 4;
}
}
if (code > 0x10ffff) code = 0x3f; // Codepoints after U+10ffff are invalid
return code;
}
// Encode codepoint into utf8 text (char array length returned as parameter)
RLAPI const char *CodepointToUtf8(int codepoint, int *byteLength)
{
static char utf8[6] = { 0 };
int length = 0;
if (codepoint <= 0x7f)
{
utf8[0] = (char)codepoint;
length = 1;
}
else if (codepoint <= 0x7ff)
{
utf8[0] = (char)(((codepoint >> 6) & 0x1f) | 0xc0);
utf8[1] = (char)((codepoint & 0x3f) | 0x80);
length = 2;
}
else if (codepoint <= 0xffff)
{
utf8[0] = (char)(((codepoint >> 12) & 0x0f) | 0xe0);
utf8[1] = (char)(((codepoint >> 6) & 0x3f) | 0x80);
utf8[2] = (char)((codepoint & 0x3f) | 0x80);
length = 3;
}
else if (codepoint <= 0x10ffff)
{
utf8[0] = (char)(((codepoint >> 18) & 0x07) | 0xf0);
utf8[1] = (char)(((codepoint >> 12) & 0x3f) | 0x80);
utf8[2] = (char)(((codepoint >> 6) & 0x3f) | 0x80);
utf8[3] = (char)((codepoint & 0x3f) | 0x80);
length = 4;
}
*byteLength = length;
return utf8;
}
//---------------------------------------------------------------------------------- //----------------------------------------------------------------------------------
//---------------------------------------------------------------------------------- //----------------------------------------------------------------------------------
@ -1567,18 +1671,15 @@ static Font LoadBMFont(const char *fileName)
TraceLog(LOG_DEBUG, "[%s] Font texture loading path: %s", fileName, texPath); TraceLog(LOG_DEBUG, "[%s] Font texture loading path: %s", fileName, texPath);
Image imFont = LoadImage(texPath); Image imFont = LoadImage(texPath);
Image imFontAlpha = ImageCopy(imFont);
if (imFont.format == UNCOMPRESSED_GRAYSCALE) if (imFont.format == UNCOMPRESSED_GRAYSCALE)
{ {
for (int i = 0; i < imFontAlpha.width*imFontAlpha.height; i++) ((unsigned char *)imFontAlpha.data)[i] = 0xff; // Convert image to GRAYSCALE + ALPHA, using the mask as the alpha channel
ImageAlphaMask(&imFont, imFont);
ImageAlphaMask(&imFontAlpha, imFont); for (int p = 0; p < (imFont.width*imFont.height*2); p += 2) ((unsigned char *)(imFont.data))[p] = 0xff;
font.texture = LoadTextureFromImage(imFontAlpha);
} }
else font.texture = LoadTextureFromImage(imFont);
UnloadImage(imFont); font.texture = LoadTextureFromImage(imFont);
RL_FREE(texPath); RL_FREE(texPath);
@ -1606,10 +1707,10 @@ static Font LoadBMFont(const char *fileName)
font.chars[i].advanceX = charAdvanceX; font.chars[i].advanceX = charAdvanceX;
// Fill character image data from imFont data // Fill character image data from imFont data
font.chars[i].image = ImageFromImage(imFontAlpha, font.recs[i]); font.chars[i].image = ImageFromImage(imFont, font.recs[i]);
} }
UnloadImage(imFontAlpha); UnloadImage(imFont);
fclose(fntFile); fclose(fntFile);

View File

@ -161,6 +161,9 @@
//---------------------------------------------------------------------------------- //----------------------------------------------------------------------------------
// Module specific Functions Declaration // Module specific Functions Declaration
//---------------------------------------------------------------------------------- //----------------------------------------------------------------------------------
#if defined(SUPPORT_FILEFORMAT_GIF)
static Image LoadAnimatedGIF(const char *fileName, int *frames, int **delays); // Load animated GIF file
#endif
#if defined(SUPPORT_FILEFORMAT_DDS) #if defined(SUPPORT_FILEFORMAT_DDS)
static Image LoadDDS(const char *fileName); // Load DDS file static Image LoadDDS(const char *fileName); // Load DDS file
#endif #endif
@ -253,13 +256,10 @@ Image LoadImage(const char *fileName)
FILE *imFile = fopen(fileName, "rb"); FILE *imFile = fopen(fileName, "rb");
stbi_set_flip_vertically_on_load(true);
// Load 32 bit per channel floats data // Load 32 bit per channel floats data
//stbi_set_flip_vertically_on_load(true);
image.data = stbi_loadf_from_file(imFile, &image.width, &image.height, &imgBpp, 0); image.data = stbi_loadf_from_file(imFile, &image.width, &image.height, &imgBpp, 0);
stbi_set_flip_vertically_on_load(false);
fclose(imFile); fclose(imFile);
image.mipmaps = 1; image.mipmaps = 1;
@ -551,7 +551,7 @@ Color *GetImageData(Image image)
pixels[i].a = 255; pixels[i].a = 255;
k += 3; k += 3;
} } break;
case UNCOMPRESSED_R32G32B32A32: case UNCOMPRESSED_R32G32B32A32:
{ {
pixels[i].r = (unsigned char)(((float *)image.data)[k]*255.0f); pixels[i].r = (unsigned char)(((float *)image.data)[k]*255.0f);
@ -560,7 +560,7 @@ Color *GetImageData(Image image)
pixels[i].a = (unsigned char)(((float *)image.data)[k]*255.0f); pixels[i].a = (unsigned char)(((float *)image.data)[k]*255.0f);
k += 4; k += 4;
} } break;
default: break; default: break;
} }
} }
@ -680,6 +680,37 @@ Vector4 *GetImageDataNormalized(Image image)
return pixels; return pixels;
} }
// Get image alpha border rectangle
Rectangle GetImageAlphaBorder(Image image, float threshold)
{
Color *pixels = GetImageData(image);
int xMin = 65536; // Define a big enough number
int xMax = 0;
int yMin = 65536;
int yMax = 0;
for (int y = 0; y < image.height; y++)
{
for (int x = 0; x < image.width; x++)
{
if (pixels[y*image.width + x].a > (unsigned char)(threshold*255.0f))
{
if (x < xMin) xMin = x;
if (x > xMax) xMax = x;
if (y < yMin) yMin = y;
if (y > yMax) yMax = y;
}
}
}
Rectangle crop = { xMin, yMin, (xMax + 1) - xMin, (yMax + 1) - yMin };
RL_FREE(pixels);
return crop;
}
// Get pixel data size in bytes (image or texture) // Get pixel data size in bytes (image or texture)
// NOTE: Size depends on pixel format // NOTE: Size depends on pixel format
int GetPixelDataSize(int width, int height, int format) int GetPixelDataSize(int width, int height, int format)
@ -818,19 +849,21 @@ void ExportImageAsCode(Image image, const char *fileName)
{ {
#define BYTES_TEXT_PER_LINE 20 #define BYTES_TEXT_PER_LINE 20
FILE *txtFile = fopen(fileName, "wt");
if (txtFile != NULL)
{
char varFileName[256] = { 0 }; char varFileName[256] = { 0 };
int dataSize = GetPixelDataSize(image.width, image.height, image.format); int dataSize = GetPixelDataSize(image.width, image.height, image.format);
FILE *txtFile = fopen(fileName, "wt"); fprintf(txtFile, "////////////////////////////////////////////////////////////////////////////////////////\n");
fprintf(txtFile, "\n//////////////////////////////////////////////////////////////////////////////////////\n");
fprintf(txtFile, "// //\n"); fprintf(txtFile, "// //\n");
fprintf(txtFile, "// ImageAsCode exporter v1.0 - Image pixel data exported as an array of bytes //\n"); fprintf(txtFile, "// ImageAsCode exporter v1.0 - Image pixel data exported as an array of bytes //\n");
fprintf(txtFile, "// //\n"); fprintf(txtFile, "// //\n");
fprintf(txtFile, "// more info and bugs-report: github.com/raysan5/raylib //\n"); fprintf(txtFile, "// more info and bugs-report: github.com/raysan5/raylib //\n");
fprintf(txtFile, "// feedback and support: ray[at]raylib.com //\n"); fprintf(txtFile, "// feedback and support: ray[at]raylib.com //\n");
fprintf(txtFile, "// //\n"); fprintf(txtFile, "// //\n");
fprintf(txtFile, "// Copyright (c) 2018 Ramon Santamaria (@raysan5) //\n"); fprintf(txtFile, "// Copyright (c) 2019 Ramon Santamaria (@raysan5) //\n");
fprintf(txtFile, "// //\n"); fprintf(txtFile, "// //\n");
fprintf(txtFile, "////////////////////////////////////////////////////////////////////////////////////////\n\n"); fprintf(txtFile, "////////////////////////////////////////////////////////////////////////////////////////\n\n");
@ -849,6 +882,7 @@ void ExportImageAsCode(Image image, const char *fileName)
fprintf(txtFile, "0x%x };\n", ((unsigned char *)image.data)[dataSize - 1]); fprintf(txtFile, "0x%x };\n", ((unsigned char *)image.data)[dataSize - 1]);
fclose(txtFile); fclose(txtFile);
}
} }
// Copy an image to a new image // Copy an image to a new image
@ -893,7 +927,9 @@ Image ImageFromImage(Image image, Rectangle rec)
{ {
Image result = ImageCopy(image); Image result = ImageCopy(image);
#if defined(SUPPORT_IMAGE_MANIPULATION)
ImageCrop(&result, rec); ImageCrop(&result, rec);
#endif
return result; return result;
} }
@ -1145,13 +1181,18 @@ void ImageAlphaMask(Image *image, Image alphaMask)
// In case image is only grayscale, we just add alpha channel // In case image is only grayscale, we just add alpha channel
if (image->format == UNCOMPRESSED_GRAYSCALE) if (image->format == UNCOMPRESSED_GRAYSCALE)
{ {
ImageFormat(image, UNCOMPRESSED_GRAY_ALPHA); unsigned char *data = (unsigned char *)RL_MALLOC(image->width*image->height*2);
// Apply alpha mask to alpha channel // Apply alpha mask to alpha channel
for (int i = 0, k = 1; (i < mask.width*mask.height) || (i < image->width*image->height); i++, k += 2) for (int i = 0, k = 0; (i < mask.width*mask.height) || (i < image->width*image->height); i++, k += 2)
{ {
((unsigned char *)image->data)[k] = ((unsigned char *)mask.data)[i]; data[k] = ((unsigned char *)image->data)[i];
data[k + 1] = ((unsigned char *)mask.data)[i];
} }
RL_FREE(image->data);
image->data = data;
image->format = UNCOMPRESSED_GRAY_ALPHA;
} }
else else
{ {
@ -1303,18 +1344,11 @@ void ImageCrop(Image *image, Rectangle crop)
// Security check to avoid program crash // Security check to avoid program crash
if ((image->data == NULL) || (image->width == 0) || (image->height == 0)) return; if ((image->data == NULL) || (image->width == 0) || (image->height == 0)) return;
// Security checks to make sure cropping rectangle is inside margins // Security checks to validate crop rectangle
if ((crop.x + crop.width) > image->width) if (crop.x < 0) { crop.width += crop.x; crop.x = 0; }
{ if (crop.y < 0) { crop.height += crop.y; crop.y = 0; }
crop.width = image->width - crop.x; if ((crop.x + crop.width) > image->width) crop.width = image->width - crop.x;
TraceLog(LOG_WARNING, "Crop rectangle width out of bounds, rescaled crop width: %i", crop.width); if ((crop.y + crop.height) > image->height) crop.height = image->height - crop.y;
}
if ((crop.y + crop.height) > image->height)
{
crop.height = image->height - crop.y;
TraceLog(LOG_WARNING, "Crop rectangle height out of bounds, rescaled crop height: %i", crop.height);
}
if ((crop.x < image->width) && (crop.y < image->height)) if ((crop.x < image->width) && (crop.y < image->height))
{ {
@ -1343,10 +1377,7 @@ void ImageCrop(Image *image, Rectangle crop)
// Reformat 32bit RGBA image to original format // Reformat 32bit RGBA image to original format
ImageFormat(image, format); ImageFormat(image, format);
} }
else else TraceLog(LOG_WARNING, "Image can not be cropped, crop rectangle out of bounds");
{
TraceLog(LOG_WARNING, "Image can not be cropped, crop rectangle out of bounds");
}
} }
// Crop image depending on alpha value // Crop image depending on alpha value
@ -1792,7 +1823,9 @@ void ImageDraw(Image *dst, Image src, Rectangle srcRec, Rectangle dstRec, Color
} }
Image srcCopy = ImageCopy(src); // Make a copy of source image to work with it Image srcCopy = ImageCopy(src); // Make a copy of source image to work with it
ImageCrop(&srcCopy, srcRec); // Crop source image to desired source rectangle
// Crop source image to desired source rectangle (if required)
if ((src.width != (int)srcRec.width) && (src.height != (int)srcRec.height)) ImageCrop(&srcCopy, srcRec);
// Scale source image in case destination rec size is different than source rec size // Scale source image in case destination rec size is different than source rec size
if (((int)dstRec.width != (int)srcRec.width) || ((int)dstRec.height != (int)srcRec.height)) if (((int)dstRec.width != (int)srcRec.width) || ((int)dstRec.height != (int)srcRec.height))
@ -1822,7 +1855,7 @@ void ImageDraw(Image *dst, Image src, Rectangle srcRec, Rectangle dstRec, Color
dstRec.y = 0; dstRec.y = 0;
} }
if (dstRec.y > (dst->height - dstRec.height)) if ((dstRec.y + dstRec.height) > dst->height)
{ {
ImageCrop(&srcCopy, (Rectangle) { 0, 0, dstRec.width, dst->height - dstRec.y }); ImageCrop(&srcCopy, (Rectangle) { 0, 0, dstRec.width, dst->height - dstRec.y });
dstRec.height = dst->height - dstRec.y; dstRec.height = dst->height - dstRec.y;
@ -1969,7 +2002,7 @@ void ImageDrawRectangleLines(Image *dst, Rectangle rec, int thick, Color color)
ImageDrawRectangle(dst, (Rectangle){ rec.x, rec.y, rec.width, thick }, color); ImageDrawRectangle(dst, (Rectangle){ rec.x, rec.y, rec.width, thick }, color);
ImageDrawRectangle(dst, (Rectangle){ rec.x, rec.y + thick, thick, rec.height - thick*2 }, color); ImageDrawRectangle(dst, (Rectangle){ rec.x, rec.y + thick, thick, rec.height - thick*2 }, color);
ImageDrawRectangle(dst, (Rectangle){ rec.x + rec.width - thick, rec.y + thick, thick, rec.height - thick*2 }, color); ImageDrawRectangle(dst, (Rectangle){ rec.x + rec.width - thick, rec.y + thick, thick, rec.height - thick*2 }, color);
ImageDrawRectangle(dst, (Rectangle){ rec.x, rec.height - thick, rec.width, thick }, color); ImageDrawRectangle(dst, (Rectangle){ rec.x, rec.y + rec.height - thick, rec.width, thick }, color);
} }
// Draw text (default font) within an image (destination) // Draw text (default font) within an image (destination)
@ -2927,6 +2960,45 @@ void DrawTextureNPatch(Texture2D texture, NPatchInfo nPatchInfo, Rectangle destR
//---------------------------------------------------------------------------------- //----------------------------------------------------------------------------------
// Module specific Functions Definition // Module specific Functions Definition
//---------------------------------------------------------------------------------- //----------------------------------------------------------------------------------
#if defined(SUPPORT_FILEFORMAT_GIF)
// Load animated GIF data
// - Image.data buffer includes all frames: [image#0][image#1][image#2][...]
// - Number of frames is returned through 'frames' parameter
// - Frames delay is returned through 'delays' parameter (int array)
// - All frames are returned in RGBA format
static Image LoadAnimatedGIF(const char *fileName, int *frames, int **delays)
{
Image image = { 0 };
FILE *gifFile = fopen(fileName, "rb");
if (gifFile == NULL)
{
TraceLog(LOG_WARNING, "[%s] Animated GIF file could not be opened", fileName);
}
else
{
fseek(gifFile, 0L, SEEK_END);
int size = ftell(gifFile);
fseek(gifFile, 0L, SEEK_SET);
unsigned char *buffer = (unsigned char *)RL_CALLOC(size, sizeof(char));
fread(buffer, sizeof(char), size, gifFile);
fclose(gifFile); // Close file pointer
int comp = 0;
image.data = stbi_load_gif_from_memory(buffer, size, delays, &image.width, &image.height, frames, &comp, 4);
image.mipmaps = 1;
image.format = UNCOMPRESSED_R8G8B8A8;
free(buffer);
}
return image;
}
#endif
#if defined(SUPPORT_FILEFORMAT_DDS) #if defined(SUPPORT_FILEFORMAT_DDS)
// Loading DDS image data (compressed or uncompressed) // Loading DDS image data (compressed or uncompressed)