Review ALL examples

This commit is contained in:
Ray 2019-05-20 16:36:42 +02:00
parent a43a7980a3
commit b525039e0a
96 changed files with 1301 additions and 1317 deletions

View file

@ -23,25 +23,25 @@ typedef struct {
Color color; Color color;
} CircleWave; } CircleWave;
int main() int main(void)
{ {
// Initialization // Initialization
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
int screenWidth = 800; const int screenWidth = 800;
int screenHeight = 450; const int screenHeight = 450;
SetConfigFlags(FLAG_MSAA_4X_HINT); // NOTE: Try to enable MSAA 4X SetConfigFlags(FLAG_MSAA_4X_HINT); // NOTE: Try to enable MSAA 4X
InitWindow(screenWidth, screenHeight, "raylib [audio] example - module playing (streaming)"); InitWindow(screenWidth, screenHeight, "raylib [audio] example - module playing (streaming)");
InitAudioDevice(); // Initialize audio device InitAudioDevice(); // Initialize audio device
Color colors[14] = { ORANGE, RED, GOLD, LIME, BLUE, VIOLET, BROWN, LIGHTGRAY, PINK, Color colors[14] = { ORANGE, RED, GOLD, LIME, BLUE, VIOLET, BROWN, LIGHTGRAY, PINK,
YELLOW, GREEN, SKYBLUE, PURPLE, BEIGE }; YELLOW, GREEN, SKYBLUE, PURPLE, BEIGE };
// Creates ome circles for visual effect // Creates ome circles for visual effect
CircleWave circles[MAX_CIRCLES]; CircleWave circles[MAX_CIRCLES];
for (int i = MAX_CIRCLES - 1; i >= 0; i--) for (int i = MAX_CIRCLES - 1; i >= 0; i--)
{ {
circles[i].alpha = 0.0f; circles[i].alpha = 0.0f;
@ -53,7 +53,7 @@ int main()
} }
Music xm = LoadMusicStream("resources/chiptun1.mod"); Music xm = LoadMusicStream("resources/chiptun1.mod");
PlayMusicStream(xm); PlayMusicStream(xm);
float timePlayed = 0.0f; float timePlayed = 0.0f;
@ -68,34 +68,34 @@ int main()
// Update // Update
//---------------------------------------------------------------------------------- //----------------------------------------------------------------------------------
UpdateMusicStream(xm); // Update music buffer with new stream data UpdateMusicStream(xm); // 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(xm);
PlayMusicStream(xm); PlayMusicStream(xm);
} }
// Pause/Resume music playing // Pause/Resume music playing
if (IsKeyPressed(KEY_P)) if (IsKeyPressed(KEY_P))
{ {
pause = !pause; pause = !pause;
if (pause) PauseMusicStream(xm); if (pause) PauseMusicStream(xm);
else ResumeMusicStream(xm); else ResumeMusicStream(xm);
} }
// Get timePlayed scaled to bar dimensions // Get timePlayed scaled to bar dimensions
timePlayed = GetMusicTimePlayed(xm)/GetMusicTimeLength(xm)*(screenWidth - 40); timePlayed = GetMusicTimePlayed(xm)/GetMusicTimeLength(xm)*(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--)
{ {
circles[i].alpha += circles[i].speed; circles[i].alpha += circles[i].speed;
circles[i].radius += circles[i].speed*10.0f; circles[i].radius += circles[i].speed*10.0f;
if (circles[i].alpha > 1.0f) circles[i].speed *= -1; if (circles[i].alpha > 1.0f) circles[i].speed *= -1;
if (circles[i].alpha <= 0.0f) if (circles[i].alpha <= 0.0f)
{ {
circles[i].alpha = 0.0f; circles[i].alpha = 0.0f;
@ -113,12 +113,12 @@ int main()
BeginDrawing(); BeginDrawing();
ClearBackground(RAYWHITE); ClearBackground(RAYWHITE);
for (int i = MAX_CIRCLES - 1; i >= 0; i--) for (int i = MAX_CIRCLES - 1; i >= 0; i--)
{ {
DrawCircleV(circles[i].position, circles[i].radius, Fade(circles[i].color, circles[i].alpha)); DrawCircleV(circles[i].position, circles[i].radius, Fade(circles[i].color, circles[i].alpha));
} }
// Draw time bar // Draw time bar
DrawRectangle(20, screenHeight - 20 - 12, screenWidth - 40, 12, LIGHTGRAY); DrawRectangle(20, screenHeight - 20 - 12, screenWidth - 40, 12, LIGHTGRAY);
DrawRectangle(20, screenHeight - 20 - 12, (int)timePlayed, 12, MAROON); DrawRectangle(20, screenHeight - 20 - 12, (int)timePlayed, 12, MAROON);
@ -131,7 +131,7 @@ int main()
// De-Initialization // De-Initialization
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
UnloadMusicStream(xm); // Unload music stream buffers from RAM UnloadMusicStream(xm); // Unload music stream buffers from RAM
CloseAudioDevice(); // Close audio device (music streaming is automatically stopped) CloseAudioDevice(); // Close audio device (music streaming is automatically stopped)
CloseWindow(); // Close window and OpenGL context CloseWindow(); // Close window and OpenGL context

View file

@ -4,7 +4,7 @@
* *
* NOTE: This example requires OpenAL Soft library installed * NOTE: This example requires OpenAL Soft library installed
* *
* This example has been created using raylib 1.7 (www.raylib.com) * 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) * raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details)
* *
* Copyright (c) 2015 Ramon Santamaria (@raysan5) * Copyright (c) 2015 Ramon Santamaria (@raysan5)
@ -13,19 +13,19 @@
#include "raylib.h" #include "raylib.h"
int main() int main(void)
{ {
// Initialization // Initialization
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
int screenWidth = 800; const int screenWidth = 800;
int screenHeight = 450; const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [audio] example - music playing (streaming)"); InitWindow(screenWidth, screenHeight, "raylib [audio] example - music playing (streaming)");
InitAudioDevice(); // Initialize audio device InitAudioDevice(); // Initialize audio device
Music music = LoadMusicStream("resources/guitar_noodling.ogg"); Music music = LoadMusicStream("resources/guitar_noodling.ogg");
PlayMusicStream(music); PlayMusicStream(music);
float timePlayed = 0.0f; float timePlayed = 0.0f;
@ -39,27 +39,27 @@ int main()
{ {
// Update // Update
//---------------------------------------------------------------------------------- //----------------------------------------------------------------------------------
UpdateMusicStream(music); // 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(music); StopMusicStream(music);
PlayMusicStream(music); PlayMusicStream(music);
} }
// Pause/Resume music playing // Pause/Resume music playing
if (IsKeyPressed(KEY_P)) if (IsKeyPressed(KEY_P))
{ {
pause = !pause; pause = !pause;
if (pause) PauseMusicStream(music); if (pause) PauseMusicStream(music);
else ResumeMusicStream(music); else ResumeMusicStream(music);
} }
// Get timePlayed scaled to bar dimensions (400 pixels) // Get timePlayed scaled to bar dimensions (400 pixels)
timePlayed = GetMusicTimePlayed(music)/GetMusicTimeLength(music)*400; timePlayed = GetMusicTimePlayed(music)/GetMusicTimeLength(music)*400;
if (timePlayed > 400) StopMusicStream(music); if (timePlayed > 400) StopMusicStream(music);
//---------------------------------------------------------------------------------- //----------------------------------------------------------------------------------
@ -74,7 +74,7 @@ int main()
DrawRectangle(200, 200, 400, 12, LIGHTGRAY); DrawRectangle(200, 200, 400, 12, LIGHTGRAY);
DrawRectangle(200, 200, (int)timePlayed, 12, MAROON); DrawRectangle(200, 200, (int)timePlayed, 12, MAROON);
DrawRectangleLines(200, 200, 400, 12, GRAY); DrawRectangleLines(200, 200, 400, 12, GRAY);
DrawText("PRESS SPACE TO RESTART MUSIC", 215, 250, 20, LIGHTGRAY); DrawText("PRESS SPACE TO RESTART MUSIC", 215, 250, 20, LIGHTGRAY);
DrawText("PRESS P TO PAUSE/RESUME MUSIC", 208, 280, 20, LIGHTGRAY); DrawText("PRESS P TO PAUSE/RESUME MUSIC", 208, 280, 20, LIGHTGRAY);

View file

@ -20,12 +20,12 @@
#define MAX_SAMPLES 512 #define MAX_SAMPLES 512
#define MAX_SAMPLES_PER_UPDATE 4096 #define MAX_SAMPLES_PER_UPDATE 4096
int main() int main(void)
{ {
// Initialization // Initialization
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
int screenWidth = 800; const int screenWidth = 800;
int screenHeight = 450; const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [audio] example - raw audio streaming"); InitWindow(screenWidth, screenHeight, "raylib [audio] example - raw audio streaming");
@ -33,30 +33,30 @@ int main()
// Init raw audio stream (sample rate: 22050, sample size: 16bit-short, channels: 1-mono) // Init raw audio stream (sample rate: 22050, sample size: 16bit-short, channels: 1-mono)
AudioStream stream = InitAudioStream(22050, 16, 1); AudioStream stream = InitAudioStream(22050, 16, 1);
// Buffer for the single cycle waveform we are synthesizing // Buffer for the single cycle waveform we are synthesizing
short *data = (short *)malloc(sizeof(short)*MAX_SAMPLES); short *data = (short *)malloc(sizeof(short)*MAX_SAMPLES);
// Frame buffer, describing the waveform when repeated over the course of a frame // Frame buffer, describing the waveform when repeated over the course of a frame
short *writeBuf = (short *)malloc(sizeof(short)*MAX_SAMPLES_PER_UPDATE); short *writeBuf = (short *)malloc(sizeof(short)*MAX_SAMPLES_PER_UPDATE);
PlayAudioStream(stream); // Start processing stream buffer (no data loaded currently) PlayAudioStream(stream); // Start processing stream buffer (no data loaded currently)
// Position read in to determine next frequency // Position read in to determine next frequency
Vector2 mousePosition = { -100.0f, -100.0f }; Vector2 mousePosition = { -100.0f, -100.0f };
// Cycles per second (hz) // Cycles per second (hz)
float frequency = 440.0f; float frequency = 440.0f;
// Previous value, used to test if sine needs to be rewritten, and to smoothly modulate frequency // Previous value, used to test if sine needs to be rewritten, and to smoothly modulate frequency
float oldFrequency = 1.0f; float oldFrequency = 1.0f;
// Cursor to read and copy the samples of the sine wave buffer // Cursor to read and copy the samples of the sine wave buffer
int readCursor = 0; int readCursor = 0;
// Computed size in samples of the sine wave // Computed size in samples of the sine wave
int waveLength = 1; int waveLength = 1;
Vector2 position = { 0, 0 }; Vector2 position = { 0, 0 };
SetTargetFPS(30); // Set our game to run at 30 frames-per-second SetTargetFPS(30); // Set our game to run at 30 frames-per-second
@ -67,62 +67,62 @@ int main()
{ {
// Update // Update
//---------------------------------------------------------------------------------- //----------------------------------------------------------------------------------
// Sample mouse input. // Sample mouse input.
mousePosition = GetMousePosition(); mousePosition = GetMousePosition();
if (IsMouseButtonDown(MOUSE_LEFT_BUTTON)) if (IsMouseButtonDown(MOUSE_LEFT_BUTTON))
{ {
float fp = (float)(mousePosition.y); float fp = (float)(mousePosition.y);
frequency = 40.0f + (float)(fp); frequency = 40.0f + (float)(fp);
} }
// Rewrite the sine wave. // Rewrite the sine wave.
// Compute two cycles to allow the buffer padding, simplifying any modulation, resampling, etc. // Compute two cycles to allow the buffer padding, simplifying any modulation, resampling, etc.
if (frequency != oldFrequency) if (frequency != oldFrequency)
{ {
// Compute wavelength. Limit size in both directions. // Compute wavelength. Limit size in both directions.
int oldWavelength = waveLength; int oldWavelength = waveLength;
waveLength = (int)(22050/frequency); waveLength = (int)(22050/frequency);
if (waveLength > MAX_SAMPLES/2) waveLength = MAX_SAMPLES/2; if (waveLength > MAX_SAMPLES/2) waveLength = MAX_SAMPLES/2;
if (waveLength < 1) waveLength = 1; if (waveLength < 1) waveLength = 1;
// Write sine wave. // Write sine wave.
for (int i = 0; i < waveLength*2; i++) for (int i = 0; i < waveLength*2; i++)
{ {
data[i] = (short)(sinf(((2*PI*(float)i/waveLength)))*32000); data[i] = (short)(sinf(((2*PI*(float)i/waveLength)))*32000);
} }
// Scale read cursor's position to minimize transition artifacts // Scale read cursor's position to minimize transition artifacts
readCursor = (int)(readCursor * ((float)waveLength / (float)oldWavelength)); readCursor = (int)(readCursor * ((float)waveLength / (float)oldWavelength));
oldFrequency = frequency; oldFrequency = frequency;
} }
// Refill audio stream if required // Refill audio stream if required
if (IsAudioBufferProcessed(stream)) if (IsAudioBufferProcessed(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;
while (writeCursor < MAX_SAMPLES_PER_UPDATE) while (writeCursor < MAX_SAMPLES_PER_UPDATE)
{ {
// Start by trying to write the whole chunk at once // Start by trying to write the whole chunk at once
int writeLength = MAX_SAMPLES_PER_UPDATE-writeCursor; int writeLength = MAX_SAMPLES_PER_UPDATE-writeCursor;
// Limit to the maximum readable size // Limit to the maximum readable size
int readLength = waveLength-readCursor; int readLength = waveLength-readCursor;
if (writeLength > readLength) writeLength = readLength; if (writeLength > readLength) writeLength = readLength;
// Write the slice // Write the slice
memcpy(writeBuf + writeCursor, data + readCursor, writeLength*sizeof(short)); memcpy(writeBuf + writeCursor, data + readCursor, writeLength*sizeof(short));
// Update cursors and loop audio // Update cursors and loop audio
readCursor = (readCursor + writeLength) % waveLength; readCursor = (readCursor + writeLength) % waveLength;
writeCursor += writeLength; writeCursor += writeLength;
} }
// Copy finished frame to audio stream // Copy finished frame to audio stream
UpdateAudioStream(stream, writeBuf, MAX_SAMPLES_PER_UPDATE); UpdateAudioStream(stream, writeBuf, MAX_SAMPLES_PER_UPDATE);
} }
@ -136,13 +136,13 @@ int main()
DrawText(FormatText("sine frequency: %i",(int)frequency), GetScreenWidth() - 220, 10, 20, RED); DrawText(FormatText("sine frequency: %i",(int)frequency), GetScreenWidth() - 220, 10, 20, RED);
DrawText("click mouse button to change frequency", 10, 10, 20, DARKGRAY); DrawText("click mouse button to change frequency", 10, 10, 20, DARKGRAY);
// Draw the current buffer state proportionate to the screen // Draw the current buffer state proportionate to the screen
for (int i = 0; i < screenWidth; i++) for (int i = 0; i < screenWidth; i++)
{ {
position.x = i; position.x = i;
position.y = 250 + 50*data[i*MAX_SAMPLES/screenWidth]/32000; position.y = 250 + 50*data[i*MAX_SAMPLES/screenWidth]/32000;
DrawPixelV(position, RED); DrawPixelV(position, RED);
} }
@ -154,7 +154,7 @@ int main()
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
free(data); // Unload sine wave data free(data); // Unload sine wave data
free(writeBuf); // Unload write buffer free(writeBuf); // Unload write buffer
CloseAudioStream(stream); // Close raw audio stream and delete buffers from RAM CloseAudioStream(stream); // Close raw audio stream and delete buffers from RAM
CloseAudioDevice(); // Close audio device (music streaming is automatically stopped) CloseAudioDevice(); // Close audio device (music streaming is automatically stopped)

View file

@ -4,21 +4,21 @@
* *
* NOTE: This example requires OpenAL Soft library installed * NOTE: This example requires OpenAL Soft library installed
* *
* This example has been created using raylib 1.3 (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)
* *
* Copyright (c) 2015 Ramon Santamaria (@raysan5) * Copyright (c) 2014 Ramon Santamaria (@raysan5)
* *
********************************************************************************************/ ********************************************************************************************/
#include "raylib.h" #include "raylib.h"
int main() int main(void)
{ {
// Initialization // Initialization
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
int screenWidth = 800; const int screenWidth = 800;
int screenHeight = 450; const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [audio] example - sound loading and playing"); InitWindow(screenWidth, screenHeight, "raylib [audio] example - sound loading and playing");
@ -26,8 +26,8 @@ int main()
Sound fxWav = LoadSound("resources/sound.wav"); // Load WAV audio file Sound fxWav = LoadSound("resources/sound.wav"); // Load WAV audio file
Sound fxOgg = LoadSound("resources/tanatana.ogg"); // Load OGG audio file Sound fxOgg = LoadSound("resources/tanatana.ogg"); // Load OGG audio file
SetTargetFPS(60); SetTargetFPS(60); // Set our game to run at 60 frames-per-second
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
// Main game loop // Main game loop

View file

@ -13,21 +13,21 @@
#define MAX_BUILDINGS 100 #define MAX_BUILDINGS 100
int main() int main(void)
{ {
// Initialization // Initialization
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
int screenWidth = 800; const int screenWidth = 800;
int screenHeight = 450; const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [core] example - 2d camera"); InitWindow(screenWidth, screenHeight, "raylib [core] example - 2d camera");
Rectangle player = { 400, 280, 40, 40 }; Rectangle player = { 400, 280, 40, 40 };
Rectangle buildings[MAX_BUILDINGS]; Rectangle buildings[MAX_BUILDINGS];
Color buildColors[MAX_BUILDINGS]; Color buildColors[MAX_BUILDINGS];
int spacing = 0; int spacing = 0;
for (int i = 0; i < MAX_BUILDINGS; i++) for (int i = 0; i < MAX_BUILDINGS; i++)
{ {
buildings[i].width = GetRandomValue(50, 200); buildings[i].width = GetRandomValue(50, 200);
@ -36,22 +36,22 @@ int main()
buildings[i].x = -6000 + spacing; buildings[i].x = -6000 + spacing;
spacing += buildings[i].width; spacing += buildings[i].width;
buildColors[i] = (Color){ GetRandomValue(200, 240), GetRandomValue(200, 240), GetRandomValue(200, 250), 255 }; buildColors[i] = (Color){ GetRandomValue(200, 240), GetRandomValue(200, 240), GetRandomValue(200, 250), 255 };
} }
Camera2D camera; 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){ 0, 0 };
camera.rotation = 0.0f; camera.rotation = 0.0f;
camera.zoom = 1.0f; camera.zoom = 1.0f;
SetTargetFPS(60); SetTargetFPS(60); // Set our game to run at 60 frames-per-second
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
// Main game loop // Main game loop
while (!WindowShouldClose()) // Detect window close button or ESC key while (!WindowShouldClose()) // Detect window close button or ESC key
{ {
// Update // Update
//---------------------------------------------------------------------------------- //----------------------------------------------------------------------------------
@ -65,26 +65,26 @@ int main()
player.x -= 2; // Player movement player.x -= 2; // Player movement
camera.offset.x += 2; // Camera displacement with 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 };
// Camera rotation controls // Camera rotation controls
if (IsKeyDown(KEY_A)) camera.rotation--; if (IsKeyDown(KEY_A)) camera.rotation--;
else if (IsKeyDown(KEY_S)) camera.rotation++; else if (IsKeyDown(KEY_S)) camera.rotation++;
// Limit camera rotation to 80 degrees (-40 to 40) // Limit camera rotation to 80 degrees (-40 to 40)
if (camera.rotation > 40) camera.rotation = 40; if (camera.rotation > 40) camera.rotation = 40;
else if (camera.rotation < -40) camera.rotation = -40; else if (camera.rotation < -40) camera.rotation = -40;
// Camera zoom controls // Camera zoom controls
camera.zoom += ((float)GetMouseWheelMove()*0.05f); camera.zoom += ((float)GetMouseWheelMove()*0.05f);
if (camera.zoom > 3.0f) camera.zoom = 3.0f; if (camera.zoom > 3.0f) camera.zoom = 3.0f;
else if (camera.zoom < 0.1f) camera.zoom = 0.1f; else if (camera.zoom < 0.1f) camera.zoom = 0.1f;
// Camera reset (zoom and rotation) // Camera reset (zoom and rotation)
if (IsKeyPressed(KEY_R)) if (IsKeyPressed(KEY_R))
{ {
camera.zoom = 1.0f; camera.zoom = 1.0f;
camera.rotation = 0.0f; camera.rotation = 0.0f;
@ -94,32 +94,32 @@ int main()
// Draw // Draw
//---------------------------------------------------------------------------------- //----------------------------------------------------------------------------------
BeginDrawing(); BeginDrawing();
ClearBackground(RAYWHITE); ClearBackground(RAYWHITE);
BeginMode2D(camera); BeginMode2D(camera);
DrawRectangle(-6000, 320, 13000, 8000, DARKGRAY); DrawRectangle(-6000, 320, 13000, 8000, DARKGRAY);
for (int i = 0; i < MAX_BUILDINGS; i++) DrawRectangleRec(buildings[i], buildColors[i]); for (int i = 0; i < MAX_BUILDINGS; i++) DrawRectangleRec(buildings[i], buildColors[i]);
DrawRectangleRec(player, RED); DrawRectangleRec(player, RED);
DrawLine(camera.target.x, -screenHeight*10, camera.target.x, screenHeight*10, GREEN); DrawLine(camera.target.x, -screenHeight*10, camera.target.x, screenHeight*10, GREEN);
DrawLine(-screenWidth*10, camera.target.y, screenWidth*10, camera.target.y, GREEN); DrawLine(-screenWidth*10, camera.target.y, screenWidth*10, camera.target.y, GREEN);
EndMode2D(); EndMode2D();
DrawText("SCREEN AREA", 640, 10, 20, RED); DrawText("SCREEN AREA", 640, 10, 20, RED);
DrawRectangle(0, 0, screenWidth, 5, RED); DrawRectangle(0, 0, screenWidth, 5, RED);
DrawRectangle(0, 5, 5, screenHeight - 10, RED); DrawRectangle(0, 5, 5, screenHeight - 10, RED);
DrawRectangle(screenWidth - 5, 5, 5, screenHeight - 10, RED); DrawRectangle(screenWidth - 5, 5, 5, screenHeight - 10, RED);
DrawRectangle(0, screenHeight - 5, screenWidth, 5, RED); DrawRectangle(0, screenHeight - 5, screenWidth, 5, RED);
DrawRectangle( 10, 10, 250, 113, Fade(SKYBLUE, 0.5f)); DrawRectangle( 10, 10, 250, 113, Fade(SKYBLUE, 0.5f));
DrawRectangleLines( 10, 10, 250, 113, BLUE); DrawRectangleLines( 10, 10, 250, 113, BLUE);
DrawText("Free 2d camera controls:", 20, 20, 10, BLACK); DrawText("Free 2d camera controls:", 20, 20, 10, BLACK);
DrawText("- Right/Left to move Offset", 40, 40, 10, DARKGRAY); DrawText("- Right/Left to move Offset", 40, 40, 10, DARKGRAY);
DrawText("- Mouse Wheel to Zoom in-out", 40, 60, 10, DARKGRAY); DrawText("- Mouse Wheel to Zoom in-out", 40, 60, 10, DARKGRAY);
@ -131,7 +131,7 @@ int main()
} }
// De-Initialization // De-Initialization
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
CloseWindow(); // Close window and OpenGL context CloseWindow(); // Close window and OpenGL context
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------

View file

@ -13,15 +13,15 @@
#define MAX_COLUMNS 20 #define MAX_COLUMNS 20
int main() int main(void)
{ {
// Initialization // Initialization
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
int screenWidth = 800; const int screenWidth = 800;
int screenHeight = 450; const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [core] example - 3d camera first person"); InitWindow(screenWidth, screenHeight, "raylib [core] example - 3d camera first person");
// Define the camera to look into our 3d world (position, target, up vector) // Define the camera to look into our 3d world (position, target, up vector)
Camera camera = { 0 }; Camera camera = { 0 };
camera.position = (Vector3){ 4.0f, 2.0f, 4.0f }; camera.position = (Vector3){ 4.0f, 2.0f, 4.0f };
@ -34,14 +34,14 @@ int main()
float heights[MAX_COLUMNS]; float heights[MAX_COLUMNS];
Vector3 positions[MAX_COLUMNS]; Vector3 positions[MAX_COLUMNS];
Color colors[MAX_COLUMNS]; Color colors[MAX_COLUMNS];
for (int i = 0; i < MAX_COLUMNS; i++) for (int i = 0; i < MAX_COLUMNS; i++)
{ {
heights[i] = (float)GetRandomValue(1, 12); heights[i] = (float)GetRandomValue(1, 12);
positions[i] = (Vector3){ GetRandomValue(-15, 15), heights[i]/2, GetRandomValue(-15, 15) }; positions[i] = (Vector3){ GetRandomValue(-15, 15), heights[i]/2, GetRandomValue(-15, 15) };
colors[i] = (Color){ GetRandomValue(20, 255), GetRandomValue(10, 55), 30, 255 }; colors[i] = (Color){ GetRandomValue(20, 255), GetRandomValue(10, 55), 30, 255 };
} }
SetCameraMode(camera, CAMERA_FIRST_PERSON); // Set a first person camera mode SetCameraMode(camera, CAMERA_FIRST_PERSON); // Set a first person camera mode
SetTargetFPS(60); // Set our game to run at 60 frames-per-second SetTargetFPS(60); // Set our game to run at 60 frames-per-second
@ -67,7 +67,7 @@ int main()
DrawCube((Vector3){ -16.0f, 2.5f, 0.0f }, 1.0f, 5.0f, 32.0f, BLUE); // Draw a blue wall DrawCube((Vector3){ -16.0f, 2.5f, 0.0f }, 1.0f, 5.0f, 32.0f, BLUE); // Draw a blue wall
DrawCube((Vector3){ 16.0f, 2.5f, 0.0f }, 1.0f, 5.0f, 32.0f, LIME); // Draw a green wall DrawCube((Vector3){ 16.0f, 2.5f, 0.0f }, 1.0f, 5.0f, 32.0f, LIME); // Draw a green wall
DrawCube((Vector3){ 0.0f, 2.5f, 16.0f }, 32.0f, 5.0f, 1.0f, GOLD); // Draw a yellow wall DrawCube((Vector3){ 0.0f, 2.5f, 16.0f }, 32.0f, 5.0f, 1.0f, GOLD); // Draw a yellow wall
// Draw some cubes around // Draw some cubes around
for (int i = 0; i < MAX_COLUMNS; i++) for (int i = 0; i < MAX_COLUMNS; i++)
{ {
@ -76,7 +76,7 @@ int main()
} }
EndMode3D(); EndMode3D();
DrawRectangle( 10, 10, 220, 70, Fade(SKYBLUE, 0.5f)); DrawRectangle( 10, 10, 220, 70, Fade(SKYBLUE, 0.5f));
DrawRectangleLines( 10, 10, 220, 70, BLUE); DrawRectangleLines( 10, 10, 220, 70, BLUE);
@ -89,7 +89,7 @@ int main()
} }
// De-Initialization // De-Initialization
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
CloseWindow(); // Close window and OpenGL context CloseWindow(); // Close window and OpenGL context
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------

View file

@ -11,12 +11,12 @@
#include "raylib.h" #include "raylib.h"
int main() int main(void)
{ {
// Initialization // Initialization
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
int screenWidth = 800; const int screenWidth = 800;
int screenHeight = 450; const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [core] example - 3d camera free"); InitWindow(screenWidth, screenHeight, "raylib [core] example - 3d camera free");
@ -27,9 +27,9 @@ int main()
camera.up = (Vector3){ 0.0f, 1.0f, 0.0f }; // Camera up vector (rotation towards target) 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.fovy = 45.0f; // Camera field-of-view Y
camera.type = CAMERA_PERSPECTIVE; // Camera mode type camera.type = CAMERA_PERSPECTIVE; // Camera mode type
Vector3 cubePosition = { 0.0f, 0.0f, 0.0f }; Vector3 cubePosition = { 0.0f, 0.0f, 0.0f };
SetCameraMode(camera, CAMERA_FREE); // Set a free camera mode SetCameraMode(camera, CAMERA_FREE); // Set a free camera mode
SetTargetFPS(60); // Set our game to run at 60 frames-per-second SetTargetFPS(60); // Set our game to run at 60 frames-per-second
@ -41,7 +41,7 @@ int main()
// Update // Update
//---------------------------------------------------------------------------------- //----------------------------------------------------------------------------------
UpdateCamera(&camera); // Update camera UpdateCamera(&camera); // Update camera
if (IsKeyDown('Z')) camera.target = (Vector3){ 0.0f, 0.0f, 0.0f }; if (IsKeyDown('Z')) camera.target = (Vector3){ 0.0f, 0.0f, 0.0f };
//---------------------------------------------------------------------------------- //----------------------------------------------------------------------------------
@ -59,10 +59,10 @@ int main()
DrawGrid(10, 1.0f); DrawGrid(10, 1.0f);
EndMode3D(); EndMode3D();
DrawRectangle( 10, 10, 320, 133, Fade(SKYBLUE, 0.5f)); DrawRectangle( 10, 10, 320, 133, Fade(SKYBLUE, 0.5f));
DrawRectangleLines( 10, 10, 320, 133, BLUE); DrawRectangleLines( 10, 10, 320, 133, BLUE);
DrawText("Free camera default controls:", 20, 20, 10, BLACK); DrawText("Free camera default controls:", 20, 20, 10, BLACK);
DrawText("- Mouse Wheel to Zoom in-out", 40, 40, 10, DARKGRAY); DrawText("- Mouse Wheel to Zoom in-out", 40, 40, 10, DARKGRAY);
DrawText("- Mouse Wheel Pressed to Pan", 40, 60, 10, DARKGRAY); DrawText("- Mouse Wheel Pressed to Pan", 40, 60, 10, DARKGRAY);

View file

@ -11,7 +11,7 @@
#include "raylib.h" #include "raylib.h"
int main() int main(void)
{ {
// Initialization // Initialization
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
@ -30,7 +30,7 @@ int main()
Vector3 cubePosition = { 0.0f, 0.0f, 0.0f }; Vector3 cubePosition = { 0.0f, 0.0f, 0.0f };
SetTargetFPS(60); // Set our game to run at 60 frames-per-second SetTargetFPS(60); // Set our game to run at 60 frames-per-second
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
// Main game loop // Main game loop

View file

@ -11,12 +11,12 @@
#include "raylib.h" #include "raylib.h"
int main() int main(void)
{ {
// Initialization // Initialization
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
int screenWidth = 800; const int screenWidth = 800;
int screenHeight = 450; const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [core] example - 3d picking"); InitWindow(screenWidth, screenHeight, "raylib [core] example - 3d picking");

View file

@ -21,16 +21,16 @@
#include "raylib.h" #include "raylib.h"
int main() int main(void)
{ {
// Initialization // Initialization
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
int screenWidth = 800; const int screenWidth = 800;
int screenHeight = 450; const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [core] example - basic window"); InitWindow(screenWidth, screenHeight, "raylib [core] example - basic window");
SetTargetFPS(60); SetTargetFPS(60); // Set our game to run at 60 frames-per-second
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
// Main game loop // Main game loop
@ -54,7 +54,7 @@ int main()
} }
// De-Initialization // De-Initialization
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
CloseWindow(); // Close window and OpenGL context CloseWindow(); // Close window and OpenGL context
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------

View file

@ -19,66 +19,66 @@
// Custom logging funtion // Custom logging funtion
void LogCustom(int msgType, const char *text, va_list args) void LogCustom(int msgType, const char *text, va_list args)
{ {
char timeStr[64]; char timeStr[64];
time_t now = time(NULL); time_t now = time(NULL);
struct tm *tm_info = localtime(&now); struct tm *tm_info = localtime(&now);
strftime(timeStr, sizeof(timeStr), "%Y-%m-%d %H:%M:%S", tm_info); strftime(timeStr, sizeof(timeStr), "%Y-%m-%d %H:%M:%S", tm_info);
printf("[%s] ", timeStr); printf("[%s] ", timeStr);
switch (msgType) switch (msgType)
{ {
case LOG_INFO: printf("[INFO] : "); break; case LOG_INFO: printf("[INFO] : "); break;
case LOG_ERROR: printf("[ERROR]: "); break; case LOG_ERROR: printf("[ERROR]: "); break;
case LOG_WARNING: printf("[WARN] : "); break; case LOG_WARNING: printf("[WARN] : "); break;
case LOG_DEBUG: printf("[DEBUG]: "); break; case LOG_DEBUG: printf("[DEBUG]: "); break;
default: break; default: break;
} }
vprintf(text, args); vprintf(text, args);
printf("\n"); printf("\n");
} }
int main(int argc, char* argv[]) int main(int argc, char* argv[])
{ {
// Initialization // Initialization
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
int screenWidth = 800; const int screenWidth = 800;
int screenHeight = 450; const int screenHeight = 450;
// First thing we do is setting our custom logger to ensure everything raylib logs // First thing we do is setting our custom logger to ensure everything raylib logs
// will use our own logger instead of its internal one // will use our own logger instead of its internal one
SetTraceLogCallback(LogCustom); SetTraceLogCallback(LogCustom);
InitWindow(screenWidth, screenHeight, "raylib [core] example - custom logging"); InitWindow(screenWidth, screenHeight, "raylib [core] example - custom logging");
SetTargetFPS(60); SetTargetFPS(60); // Set our game to run at 60 frames-per-second
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
// Main game loop // Main game loop
while (!WindowShouldClose()) // Detect window close button or ESC key while (!WindowShouldClose()) // Detect window close button or ESC key
{ {
// Update // Update
//---------------------------------------------------------------------------------- //----------------------------------------------------------------------------------
// TODO: Update your variables here // TODO: Update your variables here
//---------------------------------------------------------------------------------- //----------------------------------------------------------------------------------
// Draw // Draw
//---------------------------------------------------------------------------------- //----------------------------------------------------------------------------------
BeginDrawing(); BeginDrawing();
ClearBackground(RAYWHITE); ClearBackground(RAYWHITE);
DrawText("Check out the console output to see the custom logger in action!", 60, 200, 20, LIGHTGRAY); DrawText("Check out the console output to see the custom logger in action!", 60, 200, 20, LIGHTGRAY);
EndDrawing(); EndDrawing();
//---------------------------------------------------------------------------------- //----------------------------------------------------------------------------------
} }
// De-Initialization // De-Initialization
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
CloseWindow(); // Close window and OpenGL context CloseWindow(); // Close window and OpenGL context
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
return 0; return 0;
} }

View file

@ -13,19 +13,19 @@
#include "raylib.h" #include "raylib.h"
int main() int main(void)
{ {
// Initialization // Initialization
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
int screenWidth = 800; const int screenWidth = 800;
int screenHeight = 450; const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [core] example - drop files"); InitWindow(screenWidth, screenHeight, "raylib [core] example - drop files");
int count = 0; int count = 0;
char **droppedFiles = { 0 }; char **droppedFiles = { 0 };
SetTargetFPS(60); SetTargetFPS(60); // Set our game to run at 60 frames-per-second
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
// Main game loop // Main game loop
@ -49,15 +49,15 @@ int main()
else else
{ {
DrawText("Dropped files:", 100, 40, 20, DARKGRAY); DrawText("Dropped files:", 100, 40, 20, DARKGRAY);
for (int i = 0; i < count; i++) for (int i = 0; i < count; i++)
{ {
if (i%2 == 0) DrawRectangle(0, 85 + 40*i, screenWidth, 40, Fade(LIGHTGRAY, 0.5f)); if (i%2 == 0) DrawRectangle(0, 85 + 40*i, screenWidth, 40, Fade(LIGHTGRAY, 0.5f));
else DrawRectangle(0, 85 + 40*i, screenWidth, 40, Fade(LIGHTGRAY, 0.3f)); else DrawRectangle(0, 85 + 40*i, screenWidth, 40, Fade(LIGHTGRAY, 0.3f));
DrawText(droppedFiles[i], 120, 100 + 40*i, 10, GRAY); DrawText(droppedFiles[i], 120, 100 + 40*i, 10, GRAY);
} }
DrawText("Drop new files...", 100, 110 + 40*count, 20, DARKGRAY); DrawText("Drop new files...", 100, 110 + 40*count, 20, DARKGRAY);
} }
@ -68,7 +68,7 @@ int main()
// De-Initialization // De-Initialization
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
ClearDroppedFiles(); // Clear internal buffers ClearDroppedFiles(); // Clear internal buffers
CloseWindow(); // Close window and OpenGL context CloseWindow(); // Close window and OpenGL context
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------

View file

@ -3,15 +3,15 @@
* raylib [core] example - Gamepad input * raylib [core] example - Gamepad input
* *
* NOTE: This example requires a Gamepad connected to the system * NOTE: This example requires a Gamepad connected to the system
* raylib is configured to work with the following gamepads: * raylib is configured to work with the following gamepads:
* - Xbox 360 Controller (Xbox 360, Xbox One) * - Xbox 360 Controller (Xbox 360, Xbox One)
* - PLAYSTATION(R)3 Controller * - PLAYSTATION(R)3 Controller
* Check raylib.h for buttons configuration * Check raylib.h for buttons configuration
* *
* This example has been created using raylib 1.6 (www.raylib.com) * 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) * raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details)
* *
* Copyright (c) 2013-2016 Ramon Santamaria (@raysan5) * Copyright (c) 2013-2019 Ramon Santamaria (@raysan5)
* *
********************************************************************************************/ ********************************************************************************************/
@ -26,21 +26,21 @@
#define PS3_NAME_ID "PLAYSTATION(R)3 Controller" #define PS3_NAME_ID "PLAYSTATION(R)3 Controller"
#endif #endif
int main() int main(void)
{ {
// Initialization // Initialization
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
int screenWidth = 800; const int screenWidth = 800;
int screenHeight = 450; const int screenHeight = 450;
SetConfigFlags(FLAG_MSAA_4X_HINT); // Set MSAA 4X hint before windows creation
SetConfigFlags(FLAG_MSAA_4X_HINT); // Set MSAA 4X hint before windows creation
InitWindow(screenWidth, screenHeight, "raylib [core] example - gamepad input"); InitWindow(screenWidth, screenHeight, "raylib [core] example - gamepad input");
Texture2D texPs3Pad = LoadTexture("resources/ps3.png"); Texture2D texPs3Pad = LoadTexture("resources/ps3.png");
Texture2D texXboxPad = LoadTexture("resources/xbox.png"); Texture2D texXboxPad = LoadTexture("resources/xbox.png");
SetTargetFPS(60); SetTargetFPS(60); // Set our game to run at 60 frames-per-second
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
// Main game loop // Main game loop
@ -56,7 +56,7 @@ int main()
BeginDrawing(); BeginDrawing();
ClearBackground(RAYWHITE); ClearBackground(RAYWHITE);
if (IsGamepadAvailable(GAMEPAD_PLAYER1)) if (IsGamepadAvailable(GAMEPAD_PLAYER1))
{ {
DrawText(FormatText("GP1: %s", GetGamepadName(GAMEPAD_PLAYER1)), 10, 10, 10, BLACK); DrawText(FormatText("GP1: %s", GetGamepadName(GAMEPAD_PLAYER1)), 10, 10, 10, BLACK);
@ -64,7 +64,7 @@ int main()
if (IsGamepadName(GAMEPAD_PLAYER1, XBOX360_NAME_ID)) if (IsGamepadName(GAMEPAD_PLAYER1, XBOX360_NAME_ID))
{ {
DrawTexture(texXboxPad, 0, 0, DARKGRAY); DrawTexture(texXboxPad, 0, 0, DARKGRAY);
// Draw buttons: xbox home // Draw buttons: xbox home
if (IsGamepadButtonDown(GAMEPAD_PLAYER1, GAMEPAD_BUTTON_MIDDLE)) DrawCircle(394, 89, 19, RED); if (IsGamepadButtonDown(GAMEPAD_PLAYER1, GAMEPAD_BUTTON_MIDDLE)) DrawCircle(394, 89, 19, RED);
@ -75,7 +75,7 @@ int main()
if (IsGamepadButtonDown(GAMEPAD_PLAYER1, GAMEPAD_BUTTON_RIGHT_FACE_DOWN)) DrawCircle(536, 187, 15, LIME); if (IsGamepadButtonDown(GAMEPAD_PLAYER1, GAMEPAD_BUTTON_RIGHT_FACE_DOWN)) DrawCircle(536, 187, 15, LIME);
if (IsGamepadButtonDown(GAMEPAD_PLAYER1, GAMEPAD_BUTTON_RIGHT_FACE_RIGHT)) DrawCircle(572, 151, 15, MAROON); if (IsGamepadButtonDown(GAMEPAD_PLAYER1, GAMEPAD_BUTTON_RIGHT_FACE_RIGHT)) DrawCircle(572, 151, 15, MAROON);
if (IsGamepadButtonDown(GAMEPAD_PLAYER1, GAMEPAD_BUTTON_RIGHT_FACE_UP)) DrawCircle(536, 115, 15, GOLD); if (IsGamepadButtonDown(GAMEPAD_PLAYER1, GAMEPAD_BUTTON_RIGHT_FACE_UP)) DrawCircle(536, 115, 15, GOLD);
// Draw buttons: d-pad // Draw buttons: d-pad
DrawRectangle(317, 202, 19, 71, BLACK); DrawRectangle(317, 202, 19, 71, BLACK);
DrawRectangle(293, 228, 69, 19, BLACK); DrawRectangle(293, 228, 69, 19, BLACK);
@ -83,7 +83,7 @@ int main()
if (IsGamepadButtonDown(GAMEPAD_PLAYER1, GAMEPAD_BUTTON_LEFT_FACE_DOWN)) DrawRectangle(317, 202 + 45, 19, 26, RED); if (IsGamepadButtonDown(GAMEPAD_PLAYER1, GAMEPAD_BUTTON_LEFT_FACE_DOWN)) DrawRectangle(317, 202 + 45, 19, 26, RED);
if (IsGamepadButtonDown(GAMEPAD_PLAYER1, GAMEPAD_BUTTON_LEFT_FACE_LEFT)) DrawRectangle(292, 228, 25, 19, RED); if (IsGamepadButtonDown(GAMEPAD_PLAYER1, GAMEPAD_BUTTON_LEFT_FACE_LEFT)) DrawRectangle(292, 228, 25, 19, RED);
if (IsGamepadButtonDown(GAMEPAD_PLAYER1, GAMEPAD_BUTTON_LEFT_FACE_RIGHT)) DrawRectangle(292 + 44, 228, 26, 19, RED); if (IsGamepadButtonDown(GAMEPAD_PLAYER1, GAMEPAD_BUTTON_LEFT_FACE_RIGHT)) DrawRectangle(292 + 44, 228, 26, 19, RED);
// Draw buttons: left-right back // Draw buttons: left-right back
if (IsGamepadButtonDown(GAMEPAD_PLAYER1, GAMEPAD_BUTTON_LEFT_TRIGGER_1)) DrawCircle(259, 61, 20, RED); if (IsGamepadButtonDown(GAMEPAD_PLAYER1, GAMEPAD_BUTTON_LEFT_TRIGGER_1)) DrawCircle(259, 61, 20, RED);
if (IsGamepadButtonDown(GAMEPAD_PLAYER1, GAMEPAD_BUTTON_RIGHT_TRIGGER_1)) DrawCircle(536, 61, 20, RED); if (IsGamepadButtonDown(GAMEPAD_PLAYER1, GAMEPAD_BUTTON_RIGHT_TRIGGER_1)) DrawCircle(536, 61, 20, RED);
@ -91,21 +91,21 @@ int main()
// Draw axis: left joystick // Draw axis: left joystick
DrawCircle(259, 152, 39, BLACK); DrawCircle(259, 152, 39, BLACK);
DrawCircle(259, 152, 34, LIGHTGRAY); DrawCircle(259, 152, 34, LIGHTGRAY);
DrawCircle(259 + (GetGamepadAxisMovement(GAMEPAD_PLAYER1, GAMEPAD_AXIS_LEFT_X)*20), DrawCircle(259 + (GetGamepadAxisMovement(GAMEPAD_PLAYER1, GAMEPAD_AXIS_LEFT_X)*20),
152 - (GetGamepadAxisMovement(GAMEPAD_PLAYER1, GAMEPAD_AXIS_LEFT_Y)*20), 25, BLACK); 152 - (GetGamepadAxisMovement(GAMEPAD_PLAYER1, GAMEPAD_AXIS_LEFT_Y)*20), 25, BLACK);
// Draw axis: right joystick // Draw axis: right joystick
DrawCircle(461, 237, 38, BLACK); DrawCircle(461, 237, 38, BLACK);
DrawCircle(461, 237, 33, LIGHTGRAY); DrawCircle(461, 237, 33, LIGHTGRAY);
DrawCircle(461 + (GetGamepadAxisMovement(GAMEPAD_PLAYER1, GAMEPAD_AXIS_RIGHT_X)*20), DrawCircle(461 + (GetGamepadAxisMovement(GAMEPAD_PLAYER1, GAMEPAD_AXIS_RIGHT_X)*20),
237 - (GetGamepadAxisMovement(GAMEPAD_PLAYER1, GAMEPAD_AXIS_RIGHT_Y)*20), 25, BLACK); 237 - (GetGamepadAxisMovement(GAMEPAD_PLAYER1, GAMEPAD_AXIS_RIGHT_Y)*20), 25, BLACK);
// Draw axis: left-right triggers // Draw axis: left-right triggers
DrawRectangle(170, 30, 15, 70, GRAY); DrawRectangle(170, 30, 15, 70, GRAY);
DrawRectangle(604, 30, 15, 70, GRAY); DrawRectangle(604, 30, 15, 70, GRAY);
DrawRectangle(170, 30, 15, (((1.0f + GetGamepadAxisMovement(GAMEPAD_PLAYER1, GAMEPAD_AXIS_LEFT_TRIGGER))/2.0f)*70), RED); DrawRectangle(170, 30, 15, (((1.0f + GetGamepadAxisMovement(GAMEPAD_PLAYER1, GAMEPAD_AXIS_LEFT_TRIGGER))/2.0f)*70), RED);
DrawRectangle(604, 30, 15, (((1.0f + GetGamepadAxisMovement(GAMEPAD_PLAYER1, GAMEPAD_AXIS_RIGHT_TRIGGER))/2.0f)*70), RED); DrawRectangle(604, 30, 15, (((1.0f + GetGamepadAxisMovement(GAMEPAD_PLAYER1, GAMEPAD_AXIS_RIGHT_TRIGGER))/2.0f)*70), RED);
//DrawText(FormatText("Xbox axis LT: %02.02f", GetGamepadAxisMovement(GAMEPAD_PLAYER1, GAMEPAD_AXIS_LEFT_TRIGGER)), 10, 40, 10, BLACK); //DrawText(FormatText("Xbox axis LT: %02.02f", GetGamepadAxisMovement(GAMEPAD_PLAYER1, GAMEPAD_AXIS_LEFT_TRIGGER)), 10, 40, 10, BLACK);
//DrawText(FormatText("Xbox axis RT: %02.02f", GetGamepadAxisMovement(GAMEPAD_PLAYER1, GAMEPAD_AXIS_RIGHT_TRIGGER)), 10, 60, 10, BLACK); //DrawText(FormatText("Xbox axis RT: %02.02f", GetGamepadAxisMovement(GAMEPAD_PLAYER1, GAMEPAD_AXIS_RIGHT_TRIGGER)), 10, 60, 10, BLACK);
} }
@ -115,7 +115,7 @@ int main()
// Draw buttons: ps // Draw buttons: ps
if (IsGamepadButtonDown(GAMEPAD_PLAYER1, GAMEPAD_BUTTON_MIDDLE)) DrawCircle(396, 222, 13, RED); if (IsGamepadButtonDown(GAMEPAD_PLAYER1, GAMEPAD_BUTTON_MIDDLE)) DrawCircle(396, 222, 13, RED);
// Draw buttons: basic // Draw buttons: basic
if (IsGamepadButtonDown(GAMEPAD_PLAYER1, GAMEPAD_BUTTON_MIDDLE_LEFT)) DrawRectangle(328, 170, 32, 13, RED); if (IsGamepadButtonDown(GAMEPAD_PLAYER1, GAMEPAD_BUTTON_MIDDLE_LEFT)) DrawRectangle(328, 170, 32, 13, RED);
if (IsGamepadButtonDown(GAMEPAD_PLAYER1, GAMEPAD_BUTTON_MIDDLE_RIGHT)) DrawTriangle((Vector2){ 436, 168 }, (Vector2){ 436, 185 }, (Vector2){ 464, 177 }, RED); if (IsGamepadButtonDown(GAMEPAD_PLAYER1, GAMEPAD_BUTTON_MIDDLE_RIGHT)) DrawTriangle((Vector2){ 436, 168 }, (Vector2){ 436, 185 }, (Vector2){ 464, 177 }, RED);
@ -131,7 +131,7 @@ int main()
if (IsGamepadButtonDown(GAMEPAD_PLAYER1, GAMEPAD_BUTTON_LEFT_FACE_DOWN)) DrawRectangle(225, 132 + 54, 24, 30, RED); if (IsGamepadButtonDown(GAMEPAD_PLAYER1, GAMEPAD_BUTTON_LEFT_FACE_DOWN)) DrawRectangle(225, 132 + 54, 24, 30, RED);
if (IsGamepadButtonDown(GAMEPAD_PLAYER1, GAMEPAD_BUTTON_LEFT_FACE_LEFT)) DrawRectangle(195, 161, 30, 25, RED); if (IsGamepadButtonDown(GAMEPAD_PLAYER1, GAMEPAD_BUTTON_LEFT_FACE_LEFT)) DrawRectangle(195, 161, 30, 25, RED);
if (IsGamepadButtonDown(GAMEPAD_PLAYER1, GAMEPAD_BUTTON_LEFT_FACE_RIGHT)) DrawRectangle(195 + 54, 161, 30, 25, RED); if (IsGamepadButtonDown(GAMEPAD_PLAYER1, GAMEPAD_BUTTON_LEFT_FACE_RIGHT)) DrawRectangle(195 + 54, 161, 30, 25, RED);
// Draw buttons: left-right back buttons // Draw buttons: left-right back buttons
if (IsGamepadButtonDown(GAMEPAD_PLAYER1, GAMEPAD_BUTTON_LEFT_TRIGGER_1)) DrawCircle(239, 82, 20, RED); if (IsGamepadButtonDown(GAMEPAD_PLAYER1, GAMEPAD_BUTTON_LEFT_TRIGGER_1)) DrawCircle(239, 82, 20, RED);
if (IsGamepadButtonDown(GAMEPAD_PLAYER1, GAMEPAD_BUTTON_RIGHT_TRIGGER_1)) DrawCircle(557, 82, 20, RED); if (IsGamepadButtonDown(GAMEPAD_PLAYER1, GAMEPAD_BUTTON_RIGHT_TRIGGER_1)) DrawCircle(557, 82, 20, RED);
@ -139,42 +139,42 @@ int main()
// Draw axis: left joystick // Draw axis: left joystick
DrawCircle(319, 255, 35, BLACK); DrawCircle(319, 255, 35, BLACK);
DrawCircle(319, 255, 31, LIGHTGRAY); DrawCircle(319, 255, 31, LIGHTGRAY);
DrawCircle(319 + (GetGamepadAxisMovement(GAMEPAD_PLAYER1, GAMEPAD_AXIS_LEFT_X)*20), DrawCircle(319 + (GetGamepadAxisMovement(GAMEPAD_PLAYER1, GAMEPAD_AXIS_LEFT_X)*20),
255 + (GetGamepadAxisMovement(GAMEPAD_PLAYER1, GAMEPAD_AXIS_LEFT_Y)*20), 25, BLACK); 255 + (GetGamepadAxisMovement(GAMEPAD_PLAYER1, GAMEPAD_AXIS_LEFT_Y)*20), 25, BLACK);
// Draw axis: right joystick // Draw axis: right joystick
DrawCircle(475, 255, 35, BLACK); DrawCircle(475, 255, 35, BLACK);
DrawCircle(475, 255, 31, LIGHTGRAY); DrawCircle(475, 255, 31, LIGHTGRAY);
DrawCircle(475 + (GetGamepadAxisMovement(GAMEPAD_PLAYER1, GAMEPAD_AXIS_RIGHT_X)*20), DrawCircle(475 + (GetGamepadAxisMovement(GAMEPAD_PLAYER1, GAMEPAD_AXIS_RIGHT_X)*20),
255 + (GetGamepadAxisMovement(GAMEPAD_PLAYER1, GAMEPAD_AXIS_RIGHT_Y)*20), 25, BLACK); 255 + (GetGamepadAxisMovement(GAMEPAD_PLAYER1, GAMEPAD_AXIS_RIGHT_Y)*20), 25, BLACK);
// Draw axis: left-right triggers // Draw axis: left-right triggers
DrawRectangle(169, 48, 15, 70, GRAY); DrawRectangle(169, 48, 15, 70, GRAY);
DrawRectangle(611, 48, 15, 70, GRAY); DrawRectangle(611, 48, 15, 70, GRAY);
DrawRectangle(169, 48, 15, (((1.0f - GetGamepadAxisMovement(GAMEPAD_PLAYER1, GAMEPAD_AXIS_LEFT_TRIGGER))/2.0f)*70), RED); DrawRectangle(169, 48, 15, (((1.0f - GetGamepadAxisMovement(GAMEPAD_PLAYER1, GAMEPAD_AXIS_LEFT_TRIGGER))/2.0f)*70), RED);
DrawRectangle(611, 48, 15, (((1.0f - GetGamepadAxisMovement(GAMEPAD_PLAYER1, GAMEPAD_AXIS_RIGHT_TRIGGER))/2.0f)*70), RED); DrawRectangle(611, 48, 15, (((1.0f - GetGamepadAxisMovement(GAMEPAD_PLAYER1, GAMEPAD_AXIS_RIGHT_TRIGGER))/2.0f)*70), RED);
} }
else else
{ {
DrawText("- GENERIC GAMEPAD -", 280, 180, 20, GRAY); DrawText("- GENERIC GAMEPAD -", 280, 180, 20, GRAY);
// TODO: Draw generic gamepad // TODO: Draw generic gamepad
} }
DrawText(FormatText("DETECTED AXIS [%i]:", GetGamepadAxisCount(GAMEPAD_PLAYER1)), 10, 50, 10, MAROON); DrawText(FormatText("DETECTED AXIS [%i]:", GetGamepadAxisCount(GAMEPAD_PLAYER1)), 10, 50, 10, MAROON);
for (int i = 0; i < GetGamepadAxisCount(GAMEPAD_PLAYER1); i++) for (int i = 0; i < GetGamepadAxisCount(GAMEPAD_PLAYER1); i++)
{ {
DrawText(FormatText("AXIS %i: %.02f", i, GetGamepadAxisMovement(GAMEPAD_PLAYER1, i)), 20, 70 + 20*i, 10, DARKGRAY); DrawText(FormatText("AXIS %i: %.02f", i, GetGamepadAxisMovement(GAMEPAD_PLAYER1, i)), 20, 70 + 20*i, 10, DARKGRAY);
} }
if (GetGamepadButtonPressed() != -1) DrawText(FormatText("DETECTED BUTTON: %i", GetGamepadButtonPressed()), 10, 430, 10, RED); if (GetGamepadButtonPressed() != -1) DrawText(FormatText("DETECTED BUTTON: %i", GetGamepadButtonPressed()), 10, 430, 10, RED);
else DrawText("DETECTED BUTTON: NONE", 10, 430, 10, GRAY); else DrawText("DETECTED BUTTON: NONE", 10, 430, 10, GRAY);
} }
else else
{ {
DrawText("GP1: NOT DETECTED", 10, 10, 10, GRAY); DrawText("GP1: NOT DETECTED", 10, 10, 10, GRAY);
DrawTexture(texXboxPad, 0, 0, LIGHTGRAY); DrawTexture(texXboxPad, 0, 0, LIGHTGRAY);
} }
@ -186,7 +186,7 @@ int main()
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
UnloadTexture(texPs3Pad); UnloadTexture(texPs3Pad);
UnloadTexture(texXboxPad); UnloadTexture(texXboxPad);
CloseWindow(); // Close window and OpenGL context CloseWindow(); // Close window and OpenGL context
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------

View file

@ -14,27 +14,27 @@
#define MAX_GESTURE_STRINGS 20 #define MAX_GESTURE_STRINGS 20
int main() int main(void)
{ {
// Initialization // Initialization
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
int screenWidth = 800; const int screenWidth = 800;
int screenHeight = 450; const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [core] example - input gestures"); InitWindow(screenWidth, screenHeight, "raylib [core] example - input gestures");
Vector2 touchPosition = { 0, 0 }; Vector2 touchPosition = { 0, 0 };
Rectangle touchArea = { 220, 10, screenWidth - 230, screenHeight - 20 }; Rectangle touchArea = { 220, 10, screenWidth - 230, screenHeight - 20 };
int gesturesCount = 0; int gesturesCount = 0;
char gestureStrings[MAX_GESTURE_STRINGS][32]; char gestureStrings[MAX_GESTURE_STRINGS][32];
int currentGesture = GESTURE_NONE; int currentGesture = GESTURE_NONE;
int lastGesture = GESTURE_NONE; int lastGesture = GESTURE_NONE;
//SetGesturesEnabled(0b0000000000001001); // Enable only some gestures to be detected //SetGesturesEnabled(0b0000000000001001); // Enable only some gestures to be detected
SetTargetFPS(60); SetTargetFPS(60); // Set our game to run at 60 frames-per-second
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
// Main game loop // Main game loop
@ -65,14 +65,14 @@ int main()
case GESTURE_PINCH_OUT: strcpy(gestureStrings[gesturesCount], "GESTURE PINCH OUT"); break; case GESTURE_PINCH_OUT: strcpy(gestureStrings[gesturesCount], "GESTURE PINCH OUT"); break;
default: break; default: break;
} }
gesturesCount++; gesturesCount++;
// Reset gestures strings // Reset gestures strings
if (gesturesCount >= MAX_GESTURE_STRINGS) if (gesturesCount >= MAX_GESTURE_STRINGS)
{ {
for (int i = 0; i < MAX_GESTURE_STRINGS; i++) strcpy(gestureStrings[i], "\0"); for (int i = 0; i < MAX_GESTURE_STRINGS; i++) strcpy(gestureStrings[i], "\0");
gesturesCount = 0; gesturesCount = 0;
} }
} }
@ -84,32 +84,32 @@ int main()
BeginDrawing(); BeginDrawing();
ClearBackground(RAYWHITE); ClearBackground(RAYWHITE);
DrawRectangleRec(touchArea, GRAY); DrawRectangleRec(touchArea, GRAY);
DrawRectangle(225, 15, screenWidth - 240, screenHeight - 30, RAYWHITE); DrawRectangle(225, 15, screenWidth - 240, screenHeight - 30, RAYWHITE);
DrawText("GESTURES TEST AREA", screenWidth - 270, screenHeight - 40, 20, Fade(GRAY, 0.5f)); DrawText("GESTURES TEST AREA", screenWidth - 270, screenHeight - 40, 20, Fade(GRAY, 0.5f));
for (int i = 0; i < gesturesCount; i++) for (int i = 0; i < gesturesCount; i++)
{ {
if (i%2 == 0) DrawRectangle(10, 30 + 20*i, 200, 20, Fade(LIGHTGRAY, 0.5f)); if (i%2 == 0) DrawRectangle(10, 30 + 20*i, 200, 20, Fade(LIGHTGRAY, 0.5f));
else DrawRectangle(10, 30 + 20*i, 200, 20, Fade(LIGHTGRAY, 0.3f)); else DrawRectangle(10, 30 + 20*i, 200, 20, Fade(LIGHTGRAY, 0.3f));
if (i < gesturesCount - 1) DrawText(gestureStrings[i], 35, 36 + 20*i, 10, DARKGRAY); if (i < gesturesCount - 1) DrawText(gestureStrings[i], 35, 36 + 20*i, 10, DARKGRAY);
else DrawText(gestureStrings[i], 35, 36 + 20*i, 10, MAROON); else DrawText(gestureStrings[i], 35, 36 + 20*i, 10, MAROON);
} }
DrawRectangleLines(10, 29, 200, screenHeight - 50, GRAY); DrawRectangleLines(10, 29, 200, screenHeight - 50, GRAY);
DrawText("DETECTED GESTURES", 50, 15, 10, GRAY); DrawText("DETECTED GESTURES", 50, 15, 10, GRAY);
if (currentGesture != GESTURE_NONE) DrawCircleV(touchPosition, 30, MAROON); if (currentGesture != GESTURE_NONE) DrawCircleV(touchPosition, 30, MAROON);
EndDrawing(); EndDrawing();
//---------------------------------------------------------------------------------- //----------------------------------------------------------------------------------
} }
// De-Initialization // De-Initialization
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
CloseWindow(); // Close window and OpenGL context CloseWindow(); // Close window and OpenGL context
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
} }

View file

@ -11,18 +11,18 @@
#include "raylib.h" #include "raylib.h"
int main() int main(void)
{ {
// Initialization // Initialization
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
int screenWidth = 800; const int screenWidth = 800;
int screenHeight = 450; const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [core] example - keyboard input"); InitWindow(screenWidth, screenHeight, "raylib [core] example - keyboard input");
Vector2 ballPosition = { (float)screenWidth/2, (float)screenHeight/2 }; Vector2 ballPosition = { (float)screenWidth/2, (float)screenHeight/2 };
SetTargetFPS(60); // Set target frames-per-second SetTargetFPS(60); // Set our game to run at 60 frames-per-second
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
// Main game loop // Main game loop

View file

@ -11,19 +11,19 @@
#include "raylib.h" #include "raylib.h"
int main() int main(void)
{ {
// Initialization // Initialization
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
int screenWidth = 800; const int screenWidth = 800;
int screenHeight = 450; const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [core] example - mouse input"); InitWindow(screenWidth, screenHeight, "raylib [core] example - mouse input");
Vector2 ballPosition = { -100.0f, -100.0f }; Vector2 ballPosition = { -100.0f, -100.0f };
Color ballColor = DARKBLUE; Color ballColor = DARKBLUE;
SetTargetFPS(60); SetTargetFPS(60); // Set our game to run at 60 frames-per-second
//--------------------------------------------------------------------------------------- //---------------------------------------------------------------------------------------
// Main game loop // Main game loop
@ -32,7 +32,7 @@ int main()
// Update // Update
//---------------------------------------------------------------------------------- //----------------------------------------------------------------------------------
ballPosition = GetMousePosition(); ballPosition = GetMousePosition();
if (IsMouseButtonPressed(MOUSE_LEFT_BUTTON)) ballColor = MAROON; if (IsMouseButtonPressed(MOUSE_LEFT_BUTTON)) ballColor = MAROON;
else if (IsMouseButtonPressed(MOUSE_MIDDLE_BUTTON)) ballColor = LIME; else if (IsMouseButtonPressed(MOUSE_MIDDLE_BUTTON)) ballColor = LIME;
else if (IsMouseButtonPressed(MOUSE_RIGHT_BUTTON)) ballColor = DARKBLUE; else if (IsMouseButtonPressed(MOUSE_RIGHT_BUTTON)) ballColor = DARKBLUE;

View file

@ -11,19 +11,19 @@
#include "raylib.h" #include "raylib.h"
int main() int main(void)
{ {
// Initialization // Initialization
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
int screenWidth = 800; const int screenWidth = 800;
int screenHeight = 450; const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [core] example - input mouse wheel"); InitWindow(screenWidth, screenHeight, "raylib [core] example - input mouse wheel");
int boxPositionY = screenHeight/2 - 40; int boxPositionY = screenHeight/2 - 40;
int scrollSpeed = 4; // Scrolling speed in pixels int scrollSpeed = 4; // Scrolling speed in pixels
SetTargetFPS(60); SetTargetFPS(60); // Set our game to run at 60 frames-per-second
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
// Main game loop // Main game loop

View file

@ -13,31 +13,31 @@
#include "raylib.h" #include "raylib.h"
int main() int main(void)
{ {
// Initialization // Initialization
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
int screenWidth = 800; const int screenWidth = 800;
int screenHeight = 450; const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [core] example - input multitouch"); InitWindow(screenWidth, screenHeight, "raylib [core] example - input multitouch");
Vector2 ballPosition = { -100.0f, -100.0f }; Vector2 ballPosition = { -100.0f, -100.0f };
Color ballColor = BEIGE; Color ballColor = BEIGE;
int touchCounter = 0;
Vector2 touchPosition;
SetTargetFPS(60); int touchCounter = 0;
Vector2 touchPosition = { 0.0f };
SetTargetFPS(60); // Set our game to run at 60 frames-per-second
//--------------------------------------------------------------------------------------- //---------------------------------------------------------------------------------------
// Main game loop // Main game loop
while (!WindowShouldClose()) // Detect window close button or ESC key while (!WindowShouldClose()) // Detect window close button or ESC key
{ {
// Update // Update
//---------------------------------------------------------------------------------- //----------------------------------------------------------------------------------
ballPosition = GetMousePosition(); ballPosition = GetMousePosition();
ballColor = BEIGE; ballColor = BEIGE;
if (IsMouseButtonDown(MOUSE_LEFT_BUTTON)) ballColor = MAROON; if (IsMouseButtonDown(MOUSE_LEFT_BUTTON)) ballColor = MAROON;
@ -47,7 +47,7 @@ int main()
if (IsMouseButtonPressed(MOUSE_LEFT_BUTTON)) touchCounter = 10; if (IsMouseButtonPressed(MOUSE_LEFT_BUTTON)) touchCounter = 10;
if (IsMouseButtonPressed(MOUSE_MIDDLE_BUTTON)) touchCounter = 10; if (IsMouseButtonPressed(MOUSE_MIDDLE_BUTTON)) touchCounter = 10;
if (IsMouseButtonPressed(MOUSE_RIGHT_BUTTON)) touchCounter = 10; if (IsMouseButtonPressed(MOUSE_RIGHT_BUTTON)) touchCounter = 10;
if (touchCounter > 0) touchCounter--; if (touchCounter > 0) touchCounter--;
//---------------------------------------------------------------------------------- //----------------------------------------------------------------------------------
@ -59,15 +59,15 @@ int main()
// Multitouch // Multitouch
for (int i = 0; i < MAX_TOUCH_POINTS; ++i) for (int i = 0; i < MAX_TOUCH_POINTS; ++i)
{ {
touchPosition = GetTouchPosition(i); // Get the touch point touchPosition = GetTouchPosition(i); // Get the touch point
if ((touchPosition.x >= 0) && (touchPosition.y >= 0)) // Make sure point is not (-1,-1) as this means there is no touch for it if ((touchPosition.x >= 0) && (touchPosition.y >= 0)) // Make sure point is not (-1,-1) as this means there is no touch for it
{ {
// Draw circle and touch index number // Draw circle and touch index number
DrawCircleV(touchPosition, 34, ORANGE); DrawCircleV(touchPosition, 34, ORANGE);
DrawText(FormatText("%d", i), touchPosition.x - 10, touchPosition.y - 70, 40, BLACK); DrawText(FormatText("%d", i), touchPosition.x - 10, touchPosition.y - 70, 40, BLACK);
} }
} }
// Draw the normal mouse location // Draw the normal mouse location

View file

@ -2,7 +2,7 @@
* *
* raylib example - loading thread * raylib example - loading thread
* *
* NOTE: This example requires linking with pthreads library, * NOTE: This example requires linking with pthreads library,
* on MinGW, it can be accomplished passing -static parameter to compiler * on MinGW, it can be accomplished passing -static parameter to compiler
* *
* This example has been created using raylib 2.5 (www.raylib.com) * This example has been created using raylib 2.5 (www.raylib.com)
@ -27,21 +27,21 @@ static void *LoadDataThread(void *arg); // Loading data thread function decl
static int dataProgress = 0; // Data progress accumulator static int dataProgress = 0; // Data progress accumulator
int main() int main(void)
{ {
// Initialization // Initialization
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
int screenWidth = 800; const int screenWidth = 800;
int screenHeight = 450; const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [core] example - loading thread"); InitWindow(screenWidth, screenHeight, "raylib [core] example - loading thread");
pthread_t threadId; // Loading data thread id pthread_t threadId; // Loading data thread id
enum { STATE_WAITING, STATE_LOADING, STATE_FINISHED } state = STATE_WAITING; enum { STATE_WAITING, STATE_LOADING, STATE_FINISHED } state = STATE_WAITING;
int framesCounter = 0; int framesCounter = 0;
SetTargetFPS(60); SetTargetFPS(60); // Set our game to run at 60 frames-per-second
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
// Main game loop // Main game loop
@ -90,25 +90,25 @@ int main()
BeginDrawing(); BeginDrawing();
ClearBackground(RAYWHITE); ClearBackground(RAYWHITE);
switch (state) switch (state)
{ {
case STATE_WAITING: DrawText("PRESS ENTER to START LOADING DATA", 150, 170, 20, DARKGRAY); break; case STATE_WAITING: DrawText("PRESS ENTER to START LOADING DATA", 150, 170, 20, DARKGRAY); break;
case STATE_LOADING: case STATE_LOADING:
{ {
DrawRectangle(150, 200, dataProgress, 60, SKYBLUE); DrawRectangle(150, 200, dataProgress, 60, SKYBLUE);
if ((framesCounter/15)%2) DrawText("LOADING DATA...", 240, 210, 40, DARKBLUE); if ((framesCounter/15)%2) DrawText("LOADING DATA...", 240, 210, 40, DARKBLUE);
} break; } break;
case STATE_FINISHED: case STATE_FINISHED:
{ {
DrawRectangle(150, 200, 500, 60, LIME); DrawRectangle(150, 200, 500, 60, LIME);
DrawText("DATA LOADED!", 250, 210, 40, GREEN); DrawText("DATA LOADED!", 250, 210, 40, GREEN);
} break; } break;
default: break; default: break;
} }
DrawRectangleLines(150, 200, 500, 60, DARKGRAY); DrawRectangleLines(150, 200, 500, 60, DARKGRAY);
EndDrawing(); EndDrawing();
@ -130,11 +130,11 @@ static void *LoadDataThread(void *arg)
clock_t prevTime = clock(); // Previous time clock_t prevTime = clock(); // Previous time
// We simulate data loading with a time counter for 5 seconds // We simulate data loading with a time counter for 5 seconds
while (timeCounter < 5000) while (timeCounter < 5000)
{ {
clock_t currentTime = clock() - prevTime; clock_t currentTime = clock() - prevTime;
timeCounter = currentTime*1000/CLOCKS_PER_SEC; timeCounter = currentTime*1000/CLOCKS_PER_SEC;
// We accumulate time over a global variable to be used in // We accumulate time over a global variable to be used in
// main thread as a progress bar // main thread as a progress bar
dataProgress = timeCounter/10; dataProgress = timeCounter/10;

View file

@ -11,20 +11,20 @@
#include "raylib.h" #include "raylib.h"
int main() int main(void)
{ {
// Initialization // Initialization
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
int screenWidth = 800; const int screenWidth = 800;
int screenHeight = 450; const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [core] example - generate random values"); InitWindow(screenWidth, screenHeight, "raylib [core] example - generate random values");
int framesCounter = 0; // Variable used to count frames int framesCounter = 0; // Variable used to count frames
int randValue = GetRandomValue(-8, 5); // Get a random integer number between -8 and 5 (both included) int randValue = GetRandomValue(-8, 5); // Get a random integer number between -8 and 5 (both included)
SetTargetFPS(60); // Set our game to run at 60 frames-per-second SetTargetFPS(60); // Set our game to run at 60 frames-per-second
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
// Main game loop // Main game loop

View file

@ -14,21 +14,20 @@
// NOTE: Storage positions must start with 0, directly related to file memory layout // NOTE: Storage positions must start with 0, directly related to file memory layout
typedef enum { STORAGE_SCORE = 0, STORAGE_HISCORE } StorageData; typedef enum { STORAGE_SCORE = 0, STORAGE_HISCORE } StorageData;
int main() int main(void)
{ {
// Initialization // Initialization
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
int screenWidth = 800; const int screenWidth = 800;
int screenHeight = 450; const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [core] example - storage save/load values"); InitWindow(screenWidth, screenHeight, "raylib [core] example - storage save/load values");
int score = 0; int score = 0;
int hiscore = 0; int hiscore = 0;
int framesCounter = 0; int framesCounter = 0;
SetTargetFPS(60); SetTargetFPS(60); // Set our game to run at 60 frames-per-second
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
// Main game loop // Main game loop
@ -41,7 +40,7 @@ int main()
score = GetRandomValue(1000, 2000); score = GetRandomValue(1000, 2000);
hiscore = GetRandomValue(2000, 4000); hiscore = GetRandomValue(2000, 4000);
} }
if (IsKeyPressed(KEY_ENTER)) if (IsKeyPressed(KEY_ENTER))
{ {
StorageSaveValue(STORAGE_SCORE, score); StorageSaveValue(STORAGE_SCORE, score);
@ -53,7 +52,7 @@ int main()
score = StorageLoadValue(STORAGE_SCORE); score = StorageLoadValue(STORAGE_SCORE);
hiscore = StorageLoadValue(STORAGE_HISCORE); hiscore = StorageLoadValue(STORAGE_HISCORE);
} }
framesCounter++; framesCounter++;
//---------------------------------------------------------------------------------- //----------------------------------------------------------------------------------
@ -65,9 +64,9 @@ int main()
DrawText(FormatText("SCORE: %i", score), 280, 130, 40, MAROON); DrawText(FormatText("SCORE: %i", score), 280, 130, 40, MAROON);
DrawText(FormatText("HI-SCORE: %i", hiscore), 210, 200, 50, BLACK); DrawText(FormatText("HI-SCORE: %i", hiscore), 210, 200, 50, BLACK);
DrawText(FormatText("frames: %i", framesCounter), 10, 10, 20, LIME); DrawText(FormatText("frames: %i", framesCounter), 10, 10, 20, LIME);
DrawText("Press R to generate random numbers", 220, 40, 20, LIGHTGRAY); DrawText("Press R to generate random numbers", 220, 40, 20, LIGHTGRAY);
DrawText("Press ENTER to SAVE values", 250, 310, 20, LIGHTGRAY); DrawText("Press ENTER to SAVE values", 250, 310, 20, LIGHTGRAY);
DrawText("Press SPACE to LOAD values", 252, 350, 20, LIGHTGRAY); DrawText("Press SPACE to LOAD values", 252, 350, 20, LIGHTGRAY);
@ -77,7 +76,7 @@ int main()
} }
// De-Initialization // De-Initialization
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
CloseWindow(); // Close window and OpenGL context CloseWindow(); // Close window and OpenGL context
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------

View file

@ -17,22 +17,22 @@
#define GLSL_VERSION 100 #define GLSL_VERSION 100
#endif #endif
int main() int main(void)
{ {
// Initialization // Initialization
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
int screenWidth = 1080; const int screenWidth = 1080;
int screenHeight = 600; const int screenHeight = 600;
// NOTE: screenWidth/screenHeight should match VR device aspect ratio // NOTE: screenWidth/screenHeight should match VR device aspect ratio
InitWindow(screenWidth, screenHeight, "raylib [core] example - vr simulator"); InitWindow(screenWidth, screenHeight, "raylib [core] example - vr simulator");
// Init VR simulator (Oculus Rift CV1 parameters) // Init VR simulator (Oculus Rift CV1 parameters)
InitVrSimulator(); InitVrSimulator();
VrDeviceInfo hmd = { 0 }; // VR device parameters (head-mounted-device) VrDeviceInfo hmd = { 0 }; // VR device parameters (head-mounted-device)
// Oculus Rift CV1 parameters for simulator // Oculus Rift CV1 parameters for simulator
hmd.hResolution = 2160; // HMD horizontal resolution in pixels hmd.hResolution = 2160; // HMD horizontal resolution in pixels
hmd.vResolution = 1200; // HMD vertical resolution in pixels hmd.vResolution = 1200; // HMD vertical resolution in pixels
@ -42,7 +42,7 @@ int main()
hmd.eyeToScreenDistance = 0.041f; // HMD distance between eye and display in meters hmd.eyeToScreenDistance = 0.041f; // HMD distance between eye and display in meters
hmd.lensSeparationDistance = 0.07f; // HMD lens separation distance in meters hmd.lensSeparationDistance = 0.07f; // HMD lens separation distance in meters
hmd.interpupillaryDistance = 0.07f; // HMD IPD (distance between pupils) in meters hmd.interpupillaryDistance = 0.07f; // HMD IPD (distance between pupils) in meters
// NOTE: CV1 uses a Fresnel-hybrid-asymmetric lenses with specific distortion compute shaders. // NOTE: CV1 uses a Fresnel-hybrid-asymmetric lenses with specific distortion compute shaders.
// Following parameters are an approximation to distortion stereo rendering but results differ from actual device. // Following parameters are an approximation to distortion stereo rendering but results differ from actual device.
hmd.lensDistortionValues[0] = 1.0f; // HMD lens distortion constant parameter 0 hmd.lensDistortionValues[0] = 1.0f; // HMD lens distortion constant parameter 0
@ -53,12 +53,12 @@ int main()
hmd.chromaAbCorrection[1] = -0.004f; // HMD chromatic aberration correction parameter 1 hmd.chromaAbCorrection[1] = -0.004f; // HMD chromatic aberration correction parameter 1
hmd.chromaAbCorrection[2] = 1.014f; // HMD chromatic aberration correction parameter 2 hmd.chromaAbCorrection[2] = 1.014f; // HMD chromatic aberration correction parameter 2
hmd.chromaAbCorrection[3] = 0.0f; // HMD chromatic aberration correction parameter 3 hmd.chromaAbCorrection[3] = 0.0f; // HMD chromatic aberration correction parameter 3
// Distortion shader (uses device lens distortion and chroma) // Distortion shader (uses device lens distortion and chroma)
Shader distortion = LoadShader(0, FormatText("resources/distortion%i.fs", GLSL_VERSION)); Shader distortion = LoadShader(0, FormatText("resources/distortion%i.fs", GLSL_VERSION));
SetVrConfiguration(hmd, distortion); // Set Vr device parameters for stereo rendering SetVrConfiguration(hmd, distortion); // Set Vr device parameters for stereo rendering
// Define the camera to look into our 3d world // Define the camera to look into our 3d world
Camera camera; Camera camera;
camera.position = (Vector3){ 5.0f, 2.0f, 5.0f }; // Camera position camera.position = (Vector3){ 5.0f, 2.0f, 5.0f }; // Camera position
@ -66,11 +66,11 @@ int main()
camera.up = (Vector3){ 0.0f, 1.0f, 0.0f }; // Camera up vector (rotation towards target) camera.up = (Vector3){ 0.0f, 1.0f, 0.0f }; // Camera up vector (rotation towards target)
camera.fovy = 60.0f; // Camera field-of-view Y camera.fovy = 60.0f; // Camera field-of-view Y
camera.type = CAMERA_PERSPECTIVE; // Camera type camera.type = CAMERA_PERSPECTIVE; // Camera type
Vector3 cubePosition = { 0.0f, 0.0f, 0.0f }; Vector3 cubePosition = { 0.0f, 0.0f, 0.0f };
SetCameraMode(camera, CAMERA_FIRST_PERSON); // Set first person camera mode SetCameraMode(camera, CAMERA_FIRST_PERSON); // Set first person camera mode
SetTargetFPS(90); // Set our game to run at 90 frames-per-second SetTargetFPS(90); // Set our game to run at 90 frames-per-second
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
@ -89,7 +89,7 @@ int main()
BeginDrawing(); BeginDrawing();
ClearBackground(RAYWHITE); ClearBackground(RAYWHITE);
BeginVrDrawing(); BeginVrDrawing();
BeginMode3D(camera); BeginMode3D(camera);
@ -100,7 +100,7 @@ int main()
DrawGrid(40, 1.0f); DrawGrid(40, 1.0f);
EndMode3D(); EndMode3D();
EndVrDrawing(); EndVrDrawing();
DrawFPS(10, 10); DrawFPS(10, 10);

View file

@ -16,7 +16,7 @@
#define max(a, b) ((a)>(b)? (a) : (b)) #define max(a, b) ((a)>(b)? (a) : (b))
#define min(a, b) ((a)<(b)? (a) : (b)) #define min(a, b) ((a)<(b)? (a) : (b))
int main() int main(void)
{ {
const int windowWidth = 800; const int windowWidth = 800;
const int windowHeight = 450; const int windowHeight = 450;
@ -28,63 +28,63 @@ int main()
int gameScreenWidth = 640; int gameScreenWidth = 640;
int gameScreenHeight = 480; int gameScreenHeight = 480;
// Render texture initialization // Render texture initialization
RenderTexture2D target = LoadRenderTexture(gameScreenWidth, gameScreenHeight); RenderTexture2D target = LoadRenderTexture(gameScreenWidth, gameScreenHeight);
SetTextureFilter(target.texture, FILTER_BILINEAR); // Texture scale filter to use SetTextureFilter(target.texture, FILTER_BILINEAR); // Texture scale filter to use
Color colors[10] = { 0 }; Color colors[10] = { 0 };
for (int i = 0; i < 10; i++) colors[i] = (Color){ GetRandomValue(100, 250), GetRandomValue(50, 150), GetRandomValue(10, 100), 255 }; for (int i = 0; i < 10; i++) colors[i] = (Color){ GetRandomValue(100, 250), GetRandomValue(50, 150), GetRandomValue(10, 100), 255 };
SetTargetFPS(60); SetTargetFPS(60); // Set our game to run at 60 frames-per-second
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
// Main game loop // Main game loop
while( !WindowShouldClose() ) // Detect window close button or ESC key while (!WindowShouldClose()) // Detect window close button or ESC key
{ {
// Update // Update
//---------------------------------------------------------------------------------- //----------------------------------------------------------------------------------
// Compute required framebuffer scaling // Compute required framebuffer scaling
float scale = min((float)GetScreenWidth()/gameScreenWidth, (float)GetScreenHeight()/gameScreenHeight); float scale = min((float)GetScreenWidth()/gameScreenWidth, (float)GetScreenHeight()/gameScreenHeight);
if (IsKeyPressed(KEY_SPACE)) if (IsKeyPressed(KEY_SPACE))
{ {
// Recalculate random colors for the bars // Recalculate random colors for the bars
for (int i = 0; i < 10; i++) colors[i] = (Color){ GetRandomValue(100, 250), GetRandomValue(50, 150), GetRandomValue(10, 100), 255 }; for (int i = 0; i < 10; i++) colors[i] = (Color){ GetRandomValue(100, 250), GetRandomValue(50, 150), GetRandomValue(10, 100), 255 };
} }
//---------------------------------------------------------------------------------- //----------------------------------------------------------------------------------
// Draw // Draw
//---------------------------------------------------------------------------------- //----------------------------------------------------------------------------------
BeginDrawing(); BeginDrawing();
ClearBackground(BLACK); ClearBackground(BLACK);
// Draw everything in the render texture // Draw everything in the render texture
BeginTextureMode(target); BeginTextureMode(target);
ClearBackground(RAYWHITE); // Clear render texture background color ClearBackground(RAYWHITE); // Clear render texture background color
for (int i = 0; i < 10; i++) DrawRectangle(0, (gameScreenHeight/10)*i, gameScreenWidth, gameScreenHeight/10, colors[i]); for (int i = 0; i < 10; i++) DrawRectangle(0, (gameScreenHeight/10)*i, gameScreenWidth, gameScreenHeight/10, colors[i]);
DrawText("You can resize the window,\nand see the screen scaling!", 10, 25, 20, WHITE); DrawText("You can resize the window,\nand see the screen scaling!", 10, 25, 20, WHITE);
EndTextureMode(); EndTextureMode();
// Draw RenderTexture2D to window, properly scaled // Draw RenderTexture2D to window, properly scaled
DrawTexturePro(target.texture, (Rectangle){ 0.0f, 0.0f, (float)target.texture.width, (float)-target.texture.height }, DrawTexturePro(target.texture, (Rectangle){ 0.0f, 0.0f, (float)target.texture.width, (float)-target.texture.height },
(Rectangle){ (GetScreenWidth() - ((float)gameScreenWidth*scale))*0.5, (GetScreenHeight() - ((float)gameScreenHeight*scale))*0.5, (Rectangle){ (GetScreenWidth() - ((float)gameScreenWidth*scale))*0.5, (GetScreenHeight() - ((float)gameScreenHeight*scale))*0.5,
(float)gameScreenWidth*scale, (float)gameScreenHeight*scale }, (Vector2){ 0, 0 }, 0.0f, WHITE); (float)gameScreenWidth*scale, (float)gameScreenHeight*scale }, (Vector2){ 0, 0 }, 0.0f, WHITE);
EndDrawing(); EndDrawing();
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
} }
// De-Initialization // De-Initialization
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
UnloadRenderTexture(target); // Unload render texture UnloadRenderTexture(target); // Unload render texture
CloseWindow(); // Close window and OpenGL context CloseWindow(); // Close window and OpenGL context
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
return 0; return 0;
} }

View file

@ -11,12 +11,12 @@
#include "raylib.h" #include "raylib.h"
int main() int main(void)
{ {
// Initialization // Initialization
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
int screenWidth = 800; const int screenWidth = 800;
int screenHeight = 450; const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [core] example - 3d camera free"); InitWindow(screenWidth, screenHeight, "raylib [core] example - 3d camera free");
@ -29,9 +29,9 @@ int main()
camera.type = CAMERA_PERSPECTIVE; camera.type = CAMERA_PERSPECTIVE;
Vector3 cubePosition = { 0.0f, 0.0f, 0.0f }; Vector3 cubePosition = { 0.0f, 0.0f, 0.0f };
Vector2 cubeScreenPosition; Vector2 cubeScreenPosition;
SetCameraMode(camera, CAMERA_FREE); // Set a free camera mode SetCameraMode(camera, CAMERA_FREE); // Set a free camera mode
SetTargetFPS(60); // Set our game to run at 60 frames-per-second SetTargetFPS(60); // Set our game to run at 60 frames-per-second
@ -43,7 +43,7 @@ int main()
// Update // Update
//---------------------------------------------------------------------------------- //----------------------------------------------------------------------------------
UpdateCamera(&camera); // Update camera UpdateCamera(&camera); // Update camera
// Calculate cube screen space position (with a little offset to be in top) // Calculate cube screen space position (with a little offset to be in top)
cubeScreenPosition = GetWorldToScreen((Vector3){cubePosition.x, cubePosition.y + 2.5f, cubePosition.z}, camera); cubeScreenPosition = GetWorldToScreen((Vector3){cubePosition.x, cubePosition.y + 2.5f, cubePosition.z}, camera);
//---------------------------------------------------------------------------------- //----------------------------------------------------------------------------------
@ -62,7 +62,7 @@ int main()
DrawGrid(10, 1.0f); DrawGrid(10, 1.0f);
EndMode3D(); EndMode3D();
DrawText("Enemy: 100 / 100", cubeScreenPosition.x - MeasureText("Enemy: 100 / 100", 20) / 2, cubeScreenPosition.y, 20, BLACK); DrawText("Enemy: 100 / 100", cubeScreenPosition.x - MeasureText("Enemy: 100 / 100", 20) / 2, cubeScreenPosition.y, 20, BLACK);
DrawText("Text is always on top of the cube", (screenWidth - MeasureText("Text is always on top of the cube", 20)) / 2, 25, 20, GRAY); DrawText("Text is always on top of the cube", (screenWidth - MeasureText("Text is always on top of the cube", 20)) / 2, 25, 20, GRAY);

View file

@ -11,12 +11,12 @@
#include "raylib.h" #include "raylib.h"
int main() int main(void)
{ {
// Initialization // Initialization
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
int screenWidth = 800; const int screenWidth = 800;
int screenHeight = 450; const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [models] example - model animation"); InitWindow(screenWidth, screenHeight, "raylib [models] example - model animation");
@ -32,7 +32,7 @@ int main()
Model model = LoadModel("resources/guy/guy.iqm"); // Load the animated model mesh and basic data Model model = LoadModel("resources/guy/guy.iqm"); // Load the animated model mesh and basic data
Texture2D texture = LoadTexture("resources/guy/guytex.png"); // Load model texture and set material Texture2D texture = LoadTexture("resources/guy/guytex.png"); // Load model texture and set material
SetMaterialTexture(&model.materials[0], MAP_DIFFUSE, texture); // Set model material map texture SetMaterialTexture(&model.materials[0], MAP_DIFFUSE, texture); // Set model material map texture
Vector3 position = { 0.0f, 0.0f, 0.0f }; // Set model position Vector3 position = { 0.0f, 0.0f, 0.0f }; // Set model position
// Load animation data // Load animation data
@ -91,7 +91,7 @@ int main()
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
// 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]);
UnloadModel(model); // Unload model UnloadModel(model); // Unload model
CloseWindow(); // Close window and OpenGL context CloseWindow(); // Close window and OpenGL context

View file

@ -11,12 +11,12 @@
#include "raylib.h" #include "raylib.h"
int main() int main(void)
{ {
// Initialization // Initialization
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
int screenWidth = 800; const int screenWidth = 800;
int screenHeight = 450; const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [models] example - drawing billboards"); InitWindow(screenWidth, screenHeight, "raylib [models] example - drawing billboards");
@ -27,10 +27,10 @@ int main()
camera.up = (Vector3){ 0.0f, 1.0f, 0.0f }; camera.up = (Vector3){ 0.0f, 1.0f, 0.0f };
camera.fovy = 45.0f; camera.fovy = 45.0f;
camera.type = CAMERA_PERSPECTIVE; camera.type = CAMERA_PERSPECTIVE;
Texture2D bill = LoadTexture("resources/billboard.png"); // Our texture billboard Texture2D bill = LoadTexture("resources/billboard.png"); // Our texture billboard
Vector3 billPosition = { 0.0f, 2.0f, 0.0f }; // Position where draw billboard Vector3 billPosition = { 0.0f, 2.0f, 0.0f }; // Position where draw billboard
SetCameraMode(camera, CAMERA_ORBITAL); // Set an orbital camera mode SetCameraMode(camera, CAMERA_ORBITAL); // Set an orbital camera mode
SetTargetFPS(60); // Set our game to run at 60 frames-per-second SetTargetFPS(60); // Set our game to run at 60 frames-per-second
@ -51,11 +51,11 @@ int main()
ClearBackground(RAYWHITE); ClearBackground(RAYWHITE);
BeginMode3D(camera); BeginMode3D(camera);
DrawGrid(10, 1.0f); // Draw a grid DrawGrid(10, 1.0f); // Draw a grid
DrawBillboard(camera, bill, billPosition, 2.0f, WHITE); DrawBillboard(camera, bill, billPosition, 2.0f, WHITE);
EndMode3D(); EndMode3D();
DrawFPS(10, 10); DrawFPS(10, 10);

View file

@ -11,31 +11,31 @@
#include "raylib.h" #include "raylib.h"
int main() int main(void)
{ {
// Initialization // Initialization
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
int screenWidth = 800; const int screenWidth = 800;
int screenHeight = 450; const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [models] example - box collisions"); InitWindow(screenWidth, screenHeight, "raylib [models] example - box collisions");
// Define the camera to look into our 3d world // Define the camera to look into our 3d world
Camera camera = {{ 0.0f, 10.0f, 10.0f }, { 0.0f, 0.0f, 0.0f }, { 0.0f, 1.0f, 0.0f }, 45.0f, 0 }; Camera camera = {{ 0.0f, 10.0f, 10.0f }, { 0.0f, 0.0f, 0.0f }, { 0.0f, 1.0f, 0.0f }, 45.0f, 0 };
Vector3 playerPosition = { 0.0f, 1.0f, 2.0f }; Vector3 playerPosition = { 0.0f, 1.0f, 2.0f };
Vector3 playerSize = { 1.0f, 2.0f, 1.0f }; Vector3 playerSize = { 1.0f, 2.0f, 1.0f };
Color playerColor = GREEN; Color playerColor = GREEN;
Vector3 enemyBoxPos = { -4.0f, 1.0f, 0.0f }; Vector3 enemyBoxPos = { -4.0f, 1.0f, 0.0f };
Vector3 enemyBoxSize = { 2.0f, 2.0f, 2.0f }; Vector3 enemyBoxSize = { 2.0f, 2.0f, 2.0f };
Vector3 enemySpherePos = { 4.0f, 0.0f, 0.0f }; Vector3 enemySpherePos = { 4.0f, 0.0f, 0.0f };
float enemySphereSize = 1.5f; float enemySphereSize = 1.5f;
bool collision = false; bool collision = false;
SetTargetFPS(60); // Set our game to run at 60 frames-per-second SetTargetFPS(60); // Set our game to run at 60 frames-per-second
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
// Main game loop // Main game loop
@ -43,40 +43,40 @@ int main()
{ {
// Update // Update
//---------------------------------------------------------------------------------- //----------------------------------------------------------------------------------
// Move player // Move player
if (IsKeyDown(KEY_RIGHT)) playerPosition.x += 0.2f; if (IsKeyDown(KEY_RIGHT)) playerPosition.x += 0.2f;
else if (IsKeyDown(KEY_LEFT)) playerPosition.x -= 0.2f; else if (IsKeyDown(KEY_LEFT)) playerPosition.x -= 0.2f;
else if (IsKeyDown(KEY_DOWN)) playerPosition.z += 0.2f; else if (IsKeyDown(KEY_DOWN)) playerPosition.z += 0.2f;
else if (IsKeyDown(KEY_UP)) playerPosition.z -= 0.2f; else if (IsKeyDown(KEY_UP)) playerPosition.z -= 0.2f;
collision = false; collision = false;
// Check collisions player vs enemy-box // Check collisions player vs enemy-box
if (CheckCollisionBoxes( if (CheckCollisionBoxes(
(BoundingBox){(Vector3){ playerPosition.x - playerSize.x/2, (BoundingBox){(Vector3){ playerPosition.x - playerSize.x/2,
playerPosition.y - playerSize.y/2, playerPosition.y - playerSize.y/2,
playerPosition.z - playerSize.z/2 }, playerPosition.z - playerSize.z/2 },
(Vector3){ playerPosition.x + playerSize.x/2, (Vector3){ playerPosition.x + playerSize.x/2,
playerPosition.y + playerSize.y/2, playerPosition.y + playerSize.y/2,
playerPosition.z + playerSize.z/2 }}, playerPosition.z + playerSize.z/2 }},
(BoundingBox){(Vector3){ enemyBoxPos.x - enemyBoxSize.x/2, (BoundingBox){(Vector3){ enemyBoxPos.x - enemyBoxSize.x/2,
enemyBoxPos.y - enemyBoxSize.y/2, enemyBoxPos.y - enemyBoxSize.y/2,
enemyBoxPos.z - enemyBoxSize.z/2 }, enemyBoxPos.z - enemyBoxSize.z/2 },
(Vector3){ enemyBoxPos.x + enemyBoxSize.x/2, (Vector3){ enemyBoxPos.x + enemyBoxSize.x/2,
enemyBoxPos.y + enemyBoxSize.y/2, enemyBoxPos.y + enemyBoxSize.y/2,
enemyBoxPos.z + enemyBoxSize.z/2 }})) collision = true; enemyBoxPos.z + enemyBoxSize.z/2 }})) collision = true;
// Check collisions player vs enemy-sphere // Check collisions player vs enemy-sphere
if (CheckCollisionBoxSphere( if (CheckCollisionBoxSphere(
(BoundingBox){(Vector3){ playerPosition.x - playerSize.x/2, (BoundingBox){(Vector3){ playerPosition.x - playerSize.x/2,
playerPosition.y - playerSize.y/2, playerPosition.y - playerSize.y/2,
playerPosition.z - playerSize.z/2 }, playerPosition.z - playerSize.z/2 },
(Vector3){ playerPosition.x + playerSize.x/2, (Vector3){ playerPosition.x + playerSize.x/2,
playerPosition.y + playerSize.y/2, playerPosition.y + playerSize.y/2,
playerPosition.z + playerSize.z/2 }}, playerPosition.z + playerSize.z/2 }},
enemySpherePos, enemySphereSize)) collision = true; enemySpherePos, enemySphereSize)) collision = true;
if (collision) playerColor = RED; if (collision) playerColor = RED;
else playerColor = GREEN; else playerColor = GREEN;
//---------------------------------------------------------------------------------- //----------------------------------------------------------------------------------
@ -92,18 +92,18 @@ int main()
// Draw enemy-box // Draw enemy-box
DrawCube(enemyBoxPos, enemyBoxSize.x, enemyBoxSize.y, enemyBoxSize.z, GRAY); DrawCube(enemyBoxPos, enemyBoxSize.x, enemyBoxSize.y, enemyBoxSize.z, GRAY);
DrawCubeWires(enemyBoxPos, enemyBoxSize.x, enemyBoxSize.y, enemyBoxSize.z, DARKGRAY); DrawCubeWires(enemyBoxPos, enemyBoxSize.x, enemyBoxSize.y, enemyBoxSize.z, DARKGRAY);
// Draw enemy-sphere // Draw enemy-sphere
DrawSphere(enemySpherePos, enemySphereSize, GRAY); DrawSphere(enemySpherePos, enemySphereSize, GRAY);
DrawSphereWires(enemySpherePos, enemySphereSize, 16, 16, DARKGRAY); DrawSphereWires(enemySpherePos, enemySphereSize, 16, 16, DARKGRAY);
// Draw player // Draw player
DrawCubeV(playerPosition, playerSize, playerColor); DrawCubeV(playerPosition, playerSize, playerColor);
DrawGrid(10, 1.0f); // Draw a grid DrawGrid(10, 1.0f); // Draw a grid
EndMode3D(); EndMode3D();
DrawText("Move player with cursors to collide", 220, 40, 20, GRAY); DrawText("Move player with cursors to collide", 220, 40, 20, GRAY);
DrawFPS(10, 10); DrawFPS(10, 10);

View file

@ -11,12 +11,12 @@
#include "raylib.h" #include "raylib.h"
int main() int main(void)
{ {
// Initialization // Initialization
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
int screenWidth = 800; const int screenWidth = 800;
int screenHeight = 450; const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [models] example - cubesmap loading and drawing"); InitWindow(screenWidth, screenHeight, "raylib [models] example - cubesmap loading and drawing");
@ -25,18 +25,18 @@ int main()
Image image = LoadImage("resources/cubicmap.png"); // Load cubicmap image (RAM) Image image = LoadImage("resources/cubicmap.png"); // Load cubicmap image (RAM)
Texture2D cubicmap = LoadTextureFromImage(image); // Convert image to texture to display (VRAM) Texture2D cubicmap = LoadTextureFromImage(image); // Convert image to texture to display (VRAM)
Mesh mesh = GenMeshCubicmap(image, (Vector3){ 1.0f, 1.0f, 1.0f }); Mesh mesh = GenMeshCubicmap(image, (Vector3){ 1.0f, 1.0f, 1.0f });
Model model = LoadModelFromMesh(mesh); Model model = LoadModelFromMesh(mesh);
// NOTE: By default each cube is mapped to one part of texture atlas // NOTE: By default each cube is mapped to one part of texture atlas
Texture2D texture = LoadTexture("resources/cubicmap_atlas.png"); // Load map texture Texture2D texture = LoadTexture("resources/cubicmap_atlas.png"); // Load map texture
model.materials[0].maps[MAP_DIFFUSE].texture = texture; // Set map diffuse texture model.materials[0].maps[MAP_DIFFUSE].texture = texture; // Set map diffuse texture
Vector3 mapPosition = { -16.0f, 0.0f, -8.0f }; // Set model position Vector3 mapPosition = { -16.0f, 0.0f, -8.0f }; // Set model position
UnloadImage(image); // Unload cubesmap image from RAM, already uploaded to VRAM UnloadImage(image); // Unload cubesmap image from RAM, already uploaded to VRAM
SetCameraMode(camera, CAMERA_ORBITAL); // Set an orbital camera mode SetCameraMode(camera, CAMERA_ORBITAL); // Set an orbital camera mode
SetTargetFPS(60); // Set our game to run at 60 frames-per-second SetTargetFPS(60); // Set our game to run at 60 frames-per-second
@ -61,10 +61,10 @@ int main()
DrawModel(model, mapPosition, 1.0f, WHITE); DrawModel(model, mapPosition, 1.0f, WHITE);
EndMode3D(); EndMode3D();
DrawTextureEx(cubicmap, (Vector2){ screenWidth - cubicmap.width*4 - 20, 20 }, 0.0f, 4.0f, WHITE); DrawTextureEx(cubicmap, (Vector2){ screenWidth - cubicmap.width*4 - 20, 20 }, 0.0f, 4.0f, WHITE);
DrawRectangleLines(screenWidth - cubicmap.width*4 - 20, 20, cubicmap.width*4, cubicmap.height*4, GREEN); DrawRectangleLines(screenWidth - cubicmap.width*4 - 20, 20, cubicmap.width*4, cubicmap.height*4, GREEN);
DrawText("cubicmap image used to", 658, 90, 10, GRAY); DrawText("cubicmap image used to", 658, 90, 10, GRAY);
DrawText("generate map 3d model", 658, 104, 10, GRAY); DrawText("generate map 3d model", 658, 104, 10, GRAY);

View file

@ -13,12 +13,12 @@
#include <stdlib.h> // Required for: free() #include <stdlib.h> // Required for: free()
int main() int main(void)
{ {
// Initialization // Initialization
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
int screenWidth = 800; const int screenWidth = 800;
int screenHeight = 450; const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [models] example - first person maze"); InitWindow(screenWidth, screenHeight, "raylib [models] example - first person maze");
@ -29,18 +29,18 @@ int main()
Texture2D cubicmap = LoadTextureFromImage(imMap); // Convert image to texture to display (VRAM) Texture2D cubicmap = LoadTextureFromImage(imMap); // Convert image to texture to display (VRAM)
Mesh mesh = GenMeshCubicmap(imMap, (Vector3){ 1.0f, 1.0f, 1.0f }); Mesh mesh = GenMeshCubicmap(imMap, (Vector3){ 1.0f, 1.0f, 1.0f });
Model model = LoadModelFromMesh(mesh); Model model = LoadModelFromMesh(mesh);
// NOTE: By default each cube is mapped to one part of texture atlas // NOTE: By default each cube is mapped to one part of texture atlas
Texture2D texture = LoadTexture("resources/cubicmap_atlas.png"); // Load map texture Texture2D texture = LoadTexture("resources/cubicmap_atlas.png"); // Load map texture
model.materials[0].maps[MAP_DIFFUSE].texture = texture; // Set map diffuse texture model.materials[0].maps[MAP_DIFFUSE].texture = texture; // Set map diffuse texture
// Get map image data to be used for collision detection // Get map image data to be used for collision detection
Color *mapPixels = GetImageData(imMap); Color *mapPixels = GetImageData(imMap);
UnloadImage(imMap); // Unload image from RAM UnloadImage(imMap); // Unload image from RAM
Vector3 mapPosition = { -16.0f, 0.0f, -8.0f }; // Set model position Vector3 mapPosition = { -16.0f, 0.0f, -8.0f }; // Set model position
Vector3 playerPosition = camera.position; // Set player position Vector3 playerPosition = camera.position; // Set player position
SetCameraMode(camera, CAMERA_FIRST_PERSON); // Set camera mode SetCameraMode(camera, CAMERA_FIRST_PERSON); // Set camera mode
SetTargetFPS(60); // Set our game to run at 60 frames-per-second SetTargetFPS(60); // Set our game to run at 60 frames-per-second
@ -52,23 +52,23 @@ int main()
// Update // Update
//---------------------------------------------------------------------------------- //----------------------------------------------------------------------------------
Vector3 oldCamPos = camera.position; // Store old camera position Vector3 oldCamPos = camera.position; // Store old camera position
UpdateCamera(&camera); // Update camera UpdateCamera(&camera); // Update camera
// Check player collision (we simplify to 2D collision detection) // Check player collision (we simplify to 2D collision detection)
Vector2 playerPos = { camera.position.x, camera.position.z }; Vector2 playerPos = { camera.position.x, camera.position.z };
float playerRadius = 0.1f; // Collision radius (player is modelled as a cilinder for collision) float playerRadius = 0.1f; // Collision radius (player is modelled as a cilinder for collision)
int playerCellX = (int)(playerPos.x - mapPosition.x + 0.5f); int playerCellX = (int)(playerPos.x - mapPosition.x + 0.5f);
int playerCellY = (int)(playerPos.y - mapPosition.z + 0.5f); int playerCellY = (int)(playerPos.y - mapPosition.z + 0.5f);
// Out-of-limits security check // Out-of-limits security check
if (playerCellX < 0) playerCellX = 0; if (playerCellX < 0) playerCellX = 0;
else if (playerCellX >= cubicmap.width) playerCellX = cubicmap.width - 1; else if (playerCellX >= cubicmap.width) playerCellX = cubicmap.width - 1;
if (playerCellY < 0) playerCellY = 0; if (playerCellY < 0) playerCellY = 0;
else if (playerCellY >= cubicmap.height) playerCellY = cubicmap.height - 1; else if (playerCellY >= cubicmap.height) playerCellY = cubicmap.height - 1;
// Check map collisions using image data and player position // Check map collisions using image data and player position
// TODO: Improvement: Just check player surrounding cells for collision // TODO: Improvement: Just check player surrounding cells for collision
for (int y = 0; y < cubicmap.height; y++) for (int y = 0; y < cubicmap.height; y++)
@ -76,7 +76,7 @@ int main()
for (int x = 0; x < cubicmap.width; x++) for (int x = 0; x < cubicmap.width; x++)
{ {
if ((mapPixels[y*cubicmap.width + x].r == 255) && // Collision: white pixel, only check R channel if ((mapPixels[y*cubicmap.width + x].r == 255) && // Collision: white pixel, only check R channel
(CheckCollisionCircleRec(playerPos, playerRadius, (CheckCollisionCircleRec(playerPos, playerRadius,
(Rectangle){ mapPosition.x - 0.5f + x*1.0f, mapPosition.z - 0.5f + y*1.0f, 1.0f, 1.0f }))) (Rectangle){ mapPosition.x - 0.5f + x*1.0f, mapPosition.z - 0.5f + y*1.0f, 1.0f, 1.0f })))
{ {
// Collision detected, reset camera position // Collision detected, reset camera position
@ -98,10 +98,10 @@ int main()
//DrawCubeV(playerPosition, (Vector3){ 0.2f, 0.4f, 0.2f }, RED); // Draw player //DrawCubeV(playerPosition, (Vector3){ 0.2f, 0.4f, 0.2f }, RED); // Draw player
EndMode3D(); EndMode3D();
DrawTextureEx(cubicmap, (Vector2){ GetScreenWidth() - cubicmap.width*4 - 20, 20 }, 0.0f, 4.0f, WHITE); DrawTextureEx(cubicmap, (Vector2){ GetScreenWidth() - cubicmap.width*4 - 20, 20 }, 0.0f, 4.0f, WHITE);
DrawRectangleLines(GetScreenWidth() - cubicmap.width*4 - 20, 20, cubicmap.width*4, cubicmap.height*4, GREEN); DrawRectangleLines(GetScreenWidth() - cubicmap.width*4 - 20, 20, cubicmap.width*4, cubicmap.height*4, GREEN);
// Draw player position radar // Draw player position radar
DrawRectangle(GetScreenWidth() - cubicmap.width*4 - 20 + playerCellX*4, 20 + playerCellY*4, 4, 4, RED); DrawRectangle(GetScreenWidth() - cubicmap.width*4 - 20 + playerCellX*4, 20 + playerCellY*4, 4, 4, RED);
@ -114,7 +114,7 @@ int main()
// De-Initialization // De-Initialization
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
free(mapPixels); // Unload color array free(mapPixels); // Unload color array
UnloadTexture(cubicmap); // Unload cubicmap texture UnloadTexture(cubicmap); // Unload cubicmap texture
UnloadTexture(texture); // Unload map texture UnloadTexture(texture); // Unload map texture
UnloadModel(model); // Unload map model UnloadModel(model); // Unload map model

View file

@ -11,12 +11,12 @@
#include "raylib.h" #include "raylib.h"
int main() int main(void)
{ {
// Initialization // Initialization
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
int screenWidth = 800; const int screenWidth = 800;
int screenHeight = 450; const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [models] example - geometric shapes"); InitWindow(screenWidth, screenHeight, "raylib [models] example - geometric shapes");
@ -28,7 +28,7 @@ int main()
camera.fovy = 45.0f; camera.fovy = 45.0f;
camera.type = CAMERA_PERSPECTIVE; camera.type = CAMERA_PERSPECTIVE;
SetTargetFPS(60); // Set our game to run at 60 frames-per-second SetTargetFPS(60); // Set our game to run at 60 frames-per-second
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
// Main game loop // Main game loop

View file

@ -11,12 +11,12 @@
#include "raylib.h" #include "raylib.h"
int main() int main(void)
{ {
// Initialization // Initialization
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
int screenWidth = 800; const int screenWidth = 800;
int screenHeight = 450; const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [models] example - heightmap loading and drawing"); InitWindow(screenWidth, screenHeight, "raylib [models] example - heightmap loading and drawing");
@ -25,7 +25,7 @@ int main()
Image image = LoadImage("resources/heightmap.png"); // Load heightmap image (RAM) Image image = LoadImage("resources/heightmap.png"); // Load heightmap image (RAM)
Texture2D texture = LoadTextureFromImage(image); // Convert image to texture (VRAM) Texture2D texture = LoadTextureFromImage(image); // Convert image to texture (VRAM)
Mesh mesh = GenMeshHeightmap(image, (Vector3){ 16, 8, 16 }); // Generate heightmap mesh (RAM and VRAM) Mesh mesh = GenMeshHeightmap(image, (Vector3){ 16, 8, 16 }); // Generate heightmap mesh (RAM and VRAM)
Model model = LoadModelFromMesh(mesh); // Load model from generated mesh Model model = LoadModelFromMesh(mesh); // Load model from generated mesh
@ -33,7 +33,7 @@ int main()
Vector3 mapPosition = { -8.0f, 0.0f, -8.0f }; // Define model position Vector3 mapPosition = { -8.0f, 0.0f, -8.0f }; // Define model position
UnloadImage(image); // Unload heightmap image from RAM, already uploaded to VRAM UnloadImage(image); // Unload heightmap image from RAM, already uploaded to VRAM
SetCameraMode(camera, CAMERA_ORBITAL); // Set an orbital camera mode SetCameraMode(camera, CAMERA_ORBITAL); // Set an orbital camera mode
SetTargetFPS(60); // Set our game to run at 60 frames-per-second SetTargetFPS(60); // Set our game to run at 60 frames-per-second
@ -60,7 +60,7 @@ int main()
DrawGrid(20, 1.0f); DrawGrid(20, 1.0f);
EndMode3D(); EndMode3D();
DrawTexture(texture, screenWidth - texture.width - 20, 20, WHITE); DrawTexture(texture, screenWidth - texture.width - 20, 20, WHITE);
DrawRectangleLines(screenWidth - texture.width - 20, 20, texture.width, texture.height, GREEN); DrawRectangleLines(screenWidth - texture.width - 20, 20, texture.width, texture.height, GREEN);

View file

@ -25,12 +25,12 @@
// PBR material loading // PBR material loading
static Material LoadMaterialPBR(Color albedo, float metalness, float roughness); static Material LoadMaterialPBR(Color albedo, float metalness, float roughness);
int main() int main(void)
{ {
// Initialization // Initialization
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
int screenWidth = 800; const int screenWidth = 800;
int screenHeight = 450; const int screenHeight = 450;
SetConfigFlags(FLAG_MSAA_4X_HINT); // Enable Multi Sampling Anti Aliasing 4x (if available) SetConfigFlags(FLAG_MSAA_4X_HINT); // Enable Multi Sampling Anti Aliasing 4x (if available)
InitWindow(screenWidth, screenHeight, "raylib [models] example - pbr material"); InitWindow(screenWidth, screenHeight, "raylib [models] example - pbr material");
@ -45,7 +45,7 @@ int main()
// Load model and PBR material // Load model and PBR material
Model model = LoadModel("resources/pbr/trooper.obj"); Model model = LoadModel("resources/pbr/trooper.obj");
// Mesh tangents are generated... and uploaded to GPU // Mesh tangents are generated... and uploaded to GPU
// 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]);
@ -54,13 +54,13 @@ int main()
// Define lights attributes // Define lights attributes
// NOTE: Shader is passed to every light on creation to define shader bindings internally // NOTE: Shader is passed to every light on creation to define shader bindings internally
Light lights[MAX_LIGHTS] = { 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
SetTargetFPS(60); // Set our game to run at 60 frames-per-second SetTargetFPS(60); // Set our game to run at 60 frames-per-second
@ -72,7 +72,7 @@ int main()
// Update // Update
//---------------------------------------------------------------------------------- //----------------------------------------------------------------------------------
UpdateCamera(&camera); // Update camera UpdateCamera(&camera); // Update camera
// Send to material PBR shader camera view position // Send to material PBR shader camera view position
float cameraPos[3] = { camera.position.x, camera.position.y, camera.position.z }; float cameraPos[3] = { camera.position.x, camera.position.y, camera.position.z };
SetShaderValue(model.materials[0].shader, model.materials[0].shader.locs[LOC_VECTOR_VIEW], cameraPos, UNIFORM_VEC3); SetShaderValue(model.materials[0].shader, model.materials[0].shader.locs[LOC_VECTOR_VIEW], cameraPos, UNIFORM_VEC3);
@ -87,7 +87,7 @@ int main()
BeginMode3D(camera); BeginMode3D(camera);
DrawModel(model, Vector3Zero(), 1.0f, WHITE); DrawModel(model, Vector3Zero(), 1.0f, WHITE);
DrawGrid(10, 1.0f); DrawGrid(10, 1.0f);
EndMode3D(); EndMode3D();
@ -137,7 +137,7 @@ static Material LoadMaterialPBR(Color albedo, float metalness, float roughness)
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
mat.maps[MAP_ALBEDO].texture = LoadTexture("resources/pbr/trooper_albedo.png"); mat.maps[MAP_ALBEDO].texture = LoadTexture("resources/pbr/trooper_albedo.png");
mat.maps[MAP_NORMAL].texture = LoadTexture("resources/pbr/trooper_normals.png"); mat.maps[MAP_NORMAL].texture = LoadTexture("resources/pbr/trooper_normals.png");
@ -185,27 +185,27 @@ static Material LoadMaterialPBR(Color albedo, float metalness, float roughness)
mat.maps[MAP_BRDF].texture = GenTextureBRDF(shdrBRDF, BRDF_SIZE); mat.maps[MAP_BRDF].texture = GenTextureBRDF(shdrBRDF, BRDF_SIZE);
UnloadTexture(cubemap); UnloadTexture(cubemap);
UnloadTexture(texHDR); UnloadTexture(texHDR);
// Unload already used shaders (to create specific textures) // Unload already used shaders (to create specific textures)
UnloadShader(shdrCubemap); UnloadShader(shdrCubemap);
UnloadShader(shdrIrradiance); UnloadShader(shdrIrradiance);
UnloadShader(shdrPrefilter); UnloadShader(shdrPrefilter);
UnloadShader(shdrBRDF); UnloadShader(shdrBRDF);
// Set textures filtering for better quality // Set textures filtering for better quality
SetTextureFilter(mat.maps[MAP_ALBEDO].texture, FILTER_BILINEAR); SetTextureFilter(mat.maps[MAP_ALBEDO].texture, FILTER_BILINEAR);
SetTextureFilter(mat.maps[MAP_NORMAL].texture, FILTER_BILINEAR); SetTextureFilter(mat.maps[MAP_NORMAL].texture, FILTER_BILINEAR);
SetTextureFilter(mat.maps[MAP_METALNESS].texture, FILTER_BILINEAR); SetTextureFilter(mat.maps[MAP_METALNESS].texture, FILTER_BILINEAR);
SetTextureFilter(mat.maps[MAP_ROUGHNESS].texture, FILTER_BILINEAR); SetTextureFilter(mat.maps[MAP_ROUGHNESS].texture, FILTER_BILINEAR);
SetTextureFilter(mat.maps[MAP_OCCLUSION].texture, FILTER_BILINEAR); SetTextureFilter(mat.maps[MAP_OCCLUSION].texture, FILTER_BILINEAR);
// Enable sample usage in shader for assigned textures // Enable sample usage in shader for assigned textures
SetShaderValue(mat.shader, GetShaderLocation(mat.shader, "albedo.useSampler"), (int[1]){ 1 }, UNIFORM_INT); SetShaderValue(mat.shader, GetShaderLocation(mat.shader, "albedo.useSampler"), (int[1]){ 1 }, UNIFORM_INT);
SetShaderValue(mat.shader, GetShaderLocation(mat.shader, "normals.useSampler"), (int[1]){ 1 }, UNIFORM_INT); SetShaderValue(mat.shader, GetShaderLocation(mat.shader, "normals.useSampler"), (int[1]){ 1 }, UNIFORM_INT);
SetShaderValue(mat.shader, GetShaderLocation(mat.shader, "metalness.useSampler"), (int[1]){ 1 }, UNIFORM_INT); SetShaderValue(mat.shader, GetShaderLocation(mat.shader, "metalness.useSampler"), (int[1]){ 1 }, UNIFORM_INT);
SetShaderValue(mat.shader, GetShaderLocation(mat.shader, "roughness.useSampler"), (int[1]){ 1 }, UNIFORM_INT); SetShaderValue(mat.shader, GetShaderLocation(mat.shader, "roughness.useSampler"), (int[1]){ 1 }, UNIFORM_INT);
SetShaderValue(mat.shader, GetShaderLocation(mat.shader, "occlusion.useSampler"), (int[1]){ 1 }, UNIFORM_INT); SetShaderValue(mat.shader, GetShaderLocation(mat.shader, "occlusion.useSampler"), (int[1]){ 1 }, UNIFORM_INT);
int renderModeLoc = GetShaderLocation(mat.shader, "renderMode"); int renderModeLoc = GetShaderLocation(mat.shader, "renderMode");
SetShaderValue(mat.shader, renderModeLoc, (int[1]){ 0 }, UNIFORM_INT); SetShaderValue(mat.shader, renderModeLoc, (int[1]){ 0 }, UNIFORM_INT);

View file

@ -11,24 +11,24 @@
#include "raylib.h" #include "raylib.h"
#define NUM_MODELS 8 // We generate 8 parametric 3d shapes #define NUM_MODELS 8 // Parametric 3d shapes to generate
int main() int main(void)
{ {
// Initialization // Initialization
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
int screenWidth = 800; const int screenWidth = 800;
int screenHeight = 450; const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [models] example - mesh generation"); InitWindow(screenWidth, screenHeight, "raylib [models] example - mesh generation");
// We generate a checked image for texturing // We generate a checked image for texturing
Image checked = GenImageChecked(2, 2, 1, 1, RED, GREEN); Image checked = GenImageChecked(2, 2, 1, 1, RED, GREEN);
Texture2D texture = LoadTextureFromImage(checked); Texture2D texture = LoadTextureFromImage(checked);
UnloadImage(checked); UnloadImage(checked);
Model models[NUM_MODELS]; Model models[NUM_MODELS];
models[0] = LoadModelFromMesh(GenMeshPlane(2, 2, 5, 5)); models[0] = LoadModelFromMesh(GenMeshPlane(2, 2, 5, 5));
models[1] = LoadModelFromMesh(GenMeshCube(2.0f, 1.0f, 2.0f)); models[1] = LoadModelFromMesh(GenMeshCube(2.0f, 1.0f, 2.0f));
models[2] = LoadModelFromMesh(GenMeshSphere(2, 32, 32)); models[2] = LoadModelFromMesh(GenMeshSphere(2, 32, 32));
@ -37,7 +37,7 @@ int main()
models[5] = LoadModelFromMesh(GenMeshTorus(0.25f, 4.0f, 16, 32)); models[5] = LoadModelFromMesh(GenMeshTorus(0.25f, 4.0f, 16, 32));
models[6] = LoadModelFromMesh(GenMeshKnot(1.0f, 2.0f, 16, 128)); models[6] = LoadModelFromMesh(GenMeshKnot(1.0f, 2.0f, 16, 128));
models[7] = LoadModelFromMesh(GenMeshPoly(5, 2.0f)); models[7] = LoadModelFromMesh(GenMeshPoly(5, 2.0f));
// Set checked texture as default diffuse component for all models material // Set checked texture as default diffuse component for all models material
for (int i = 0; i < NUM_MODELS; i++) models[i].materials[0].maps[MAP_DIFFUSE].texture = texture; for (int i = 0; i < NUM_MODELS; i++) models[i].materials[0].maps[MAP_DIFFUSE].texture = texture;
@ -46,12 +46,12 @@ int main()
// Model drawing position // Model drawing position
Vector3 position = { 0.0f, 0.0f, 0.0f }; Vector3 position = { 0.0f, 0.0f, 0.0f };
int currentModel = 0; int currentModel = 0;
SetCameraMode(camera, CAMERA_ORBITAL); // Set a orbital camera mode SetCameraMode(camera, CAMERA_ORBITAL); // Set a orbital camera mode
SetTargetFPS(60); // Set our game to run at 60 frames-per-second SetTargetFPS(60); // Set our game to run at 60 frames-per-second
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
// Main game loop // Main game loop
@ -60,14 +60,14 @@ int main()
// Update // Update
//---------------------------------------------------------------------------------- //----------------------------------------------------------------------------------
UpdateCamera(&camera); // Update internal camera and our camera UpdateCamera(&camera); // Update internal camera and our camera
if (IsMouseButtonPressed(MOUSE_LEFT_BUTTON)) if (IsMouseButtonPressed(MOUSE_LEFT_BUTTON))
{ {
currentModel = (currentModel + 1)%NUM_MODELS; // Cycle between the textures currentModel = (currentModel + 1)%NUM_MODELS; // Cycle between the textures
} }
if (IsKeyPressed(KEY_RIGHT)) if (IsKeyPressed(KEY_RIGHT))
{ {
currentModel++; currentModel++;
if (currentModel >= NUM_MODELS) currentModel = 0; if (currentModel >= NUM_MODELS) currentModel = 0;
} }
@ -91,11 +91,11 @@ int main()
DrawGrid(10, 1.0); DrawGrid(10, 1.0);
EndMode3D(); EndMode3D();
DrawRectangle(30, 400, 310, 30, Fade(SKYBLUE, 0.5f)); DrawRectangle(30, 400, 310, 30, Fade(SKYBLUE, 0.5f));
DrawRectangleLines(30, 400, 310, 30, Fade(DARKBLUE, 0.5f)); DrawRectangleLines(30, 400, 310, 30, Fade(DARKBLUE, 0.5f));
DrawText("MOUSE LEFT BUTTON to CYCLE PROCEDURAL MODELS", 40, 410, 10, BLUE); DrawText("MOUSE LEFT BUTTON to CYCLE PROCEDURAL MODELS", 40, 410, 10, BLUE);
switch(currentModel) switch(currentModel)
{ {
case 0: DrawText("PLANE", 680, 10, 20, DARKBLUE); break; case 0: DrawText("PLANE", 680, 10, 20, DARKBLUE); break;
@ -115,10 +115,10 @@ int main()
// De-Initialization // De-Initialization
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
// 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]);
CloseWindow(); // Close window and OpenGL context CloseWindow(); // Close window and OpenGL context
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------

View file

@ -15,12 +15,12 @@
#define FLT_MAX 340282346638528859811704183484516925440.0f // Maximum value of a float, from bit pattern 01111111011111111111111111111111 #define FLT_MAX 340282346638528859811704183484516925440.0f // Maximum value of a float, from bit pattern 01111111011111111111111111111111
int main() int main(void)
{ {
// Initialization // Initialization
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
int screenWidth = 800; const int screenWidth = 800;
int screenHeight = 450; const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [models] example - mesh picking"); InitWindow(screenWidth, screenHeight, "raylib [models] example - mesh picking");
@ -33,22 +33,22 @@ int main()
camera.type = CAMERA_PERSPECTIVE; // Camera mode type camera.type = CAMERA_PERSPECTIVE; // Camera mode type
Ray ray = { 0 }; // Picking ray Ray ray = { 0 }; // Picking ray
Model tower = LoadModel("resources/models/turret.obj"); // Load OBJ model Model tower = LoadModel("resources/models/turret.obj"); // Load OBJ model
Texture2D texture = LoadTexture("resources/models/turret_diffuse.png"); // Load model texture Texture2D texture = LoadTexture("resources/models/turret_diffuse.png"); // Load model texture
tower.materials[0].maps[MAP_DIFFUSE].texture = texture; // Set model diffuse texture tower.materials[0].maps[MAP_DIFFUSE].texture = texture; // Set model diffuse texture
Vector3 towerPos = { 0.0f, 0.0f, 0.0f }; // Set model position Vector3 towerPos = { 0.0f, 0.0f, 0.0f }; // Set model position
BoundingBox towerBBox = MeshBoundingBox(tower.meshes[0]); // Get mesh bounding box BoundingBox towerBBox = MeshBoundingBox(tower.meshes[0]); // Get mesh bounding box
bool hitMeshBBox = false; bool hitMeshBBox = false;
bool hitTriangle = false; bool hitTriangle = false;
// Test triangle // Test triangle
Vector3 ta = (Vector3){ -25.0, 0.5, 0.0 }; Vector3 ta = (Vector3){ -25.0, 0.5, 0.0 };
Vector3 tb = (Vector3){ -4.0, 2.5, 1.0 }; Vector3 tb = (Vector3){ -4.0, 2.5, 1.0 };
Vector3 tc = (Vector3){ -8.0, 6.5, 0.0 }; Vector3 tc = (Vector3){ -8.0, 6.5, 0.0 };
Vector3 bary = { 0.0f, 0.0f, 0.0f }; Vector3 bary = { 0.0f, 0.0f, 0.0f };
SetCameraMode(camera, CAMERA_FREE); // Set a free camera mode SetCameraMode(camera, CAMERA_FREE); // Set a free camera mode
@ -60,7 +60,7 @@ int main()
// Update // Update
//---------------------------------------------------------------------------------- //----------------------------------------------------------------------------------
UpdateCamera(&camera); // Update camera UpdateCamera(&camera); // Update camera
// Display information about closest hit // Display information about closest hit
RayHitInfo nearestHit = { 0 }; RayHitInfo nearestHit = { 0 };
char *hitObjectName = "None"; char *hitObjectName = "None";
@ -70,10 +70,10 @@ int main()
// Get ray and test against ground, triangle, and mesh // Get ray and test against ground, triangle, and mesh
ray = GetMouseRay(GetMousePosition(), camera); ray = GetMouseRay(GetMousePosition(), camera);
// Check ray collision aginst ground plane // Check ray collision aginst ground plane
RayHitInfo groundHitInfo = GetCollisionRayGround(ray, 0.0f); RayHitInfo groundHitInfo = GetCollisionRayGround(ray, 0.0f);
if ((groundHitInfo.hit) && (groundHitInfo.distance < nearestHit.distance)) if ((groundHitInfo.hit) && (groundHitInfo.distance < nearestHit.distance))
{ {
nearestHit = groundHitInfo; nearestHit = groundHitInfo;
@ -83,8 +83,8 @@ int main()
// Check ray collision against test triangle // Check ray collision against test triangle
RayHitInfo triHitInfo = GetCollisionRayTriangle(ray, ta, tb, tc); RayHitInfo triHitInfo = GetCollisionRayTriangle(ray, ta, tb, tc);
if ((triHitInfo.hit) && (triHitInfo.distance < nearestHit.distance)) if ((triHitInfo.hit) && (triHitInfo.distance < nearestHit.distance))
{ {
nearestHit = triHitInfo; nearestHit = triHitInfo;
cursorColor = PURPLE; cursorColor = PURPLE;
@ -92,32 +92,31 @@ int main()
bary = Vector3Barycenter(nearestHit.position, ta, tb, tc); bary = Vector3Barycenter(nearestHit.position, ta, tb, tc);
hitTriangle = true; hitTriangle = true;
} }
else hitTriangle = false; else hitTriangle = false;
RayHitInfo meshHitInfo = { 0 }; RayHitInfo meshHitInfo = { 0 };
// Check ray collision against bounding box first, before trying the full ray-mesh test // Check ray collision against bounding box first, before trying the full ray-mesh test
if (CheckCollisionRayBox(ray, towerBBox)) if (CheckCollisionRayBox(ray, towerBBox))
{ {
hitMeshBBox = true; hitMeshBBox = true;
// 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))
{ {
nearestHit = meshHitInfo; nearestHit = meshHitInfo;
cursorColor = ORANGE; cursorColor = ORANGE;
hitObjectName = "Mesh"; hitObjectName = "Mesh";
} }
}
}
hitMeshBBox = false;
hitMeshBBox = false;
//---------------------------------------------------------------------------------- //----------------------------------------------------------------------------------
// Draw // Draw
//---------------------------------------------------------------------------------- //----------------------------------------------------------------------------------
BeginDrawing(); BeginDrawing();
@ -127,10 +126,10 @@ int main()
BeginMode3D(camera); BeginMode3D(camera);
// Draw the tower // Draw the tower
// WARNING: If scale is different than 1.0f, // WARNING: If scale is different than 1.0f,
// not considered by GetCollisionRayModel() // not considered by GetCollisionRayModel()
DrawModel(tower, towerPos, 1.0f, WHITE); DrawModel(tower, towerPos, 1.0f, WHITE);
// Draw the test triangle // Draw the test triangle
DrawLine3D(ta, tb, PURPLE); DrawLine3D(ta, tb, PURPLE);
DrawLine3D(tb, tc, PURPLE); DrawLine3D(tb, tc, PURPLE);
@ -140,7 +139,7 @@ int main()
if (hitMeshBBox) DrawBoundingBox(towerBBox, LIME); if (hitMeshBBox) DrawBoundingBox(towerBBox, LIME);
// If we hit something, draw the cursor at the hit point // If we hit something, draw the cursor at the hit point
if (nearestHit.hit) if (nearestHit.hit)
{ {
DrawCube(nearestHit.position, 0.3, 0.3, 0.3, cursorColor); DrawCube(nearestHit.position, 0.3, 0.3, 0.3, cursorColor);
DrawCubeWires(nearestHit.position, 0.3, 0.3, 0.3, RED); DrawCubeWires(nearestHit.position, 0.3, 0.3, 0.3, RED);
@ -149,40 +148,40 @@ int main()
normalEnd.x = nearestHit.position.x + nearestHit.normal.x; normalEnd.x = nearestHit.position.x + nearestHit.normal.x;
normalEnd.y = nearestHit.position.y + nearestHit.normal.y; normalEnd.y = nearestHit.position.y + nearestHit.normal.y;
normalEnd.z = nearestHit.position.z + nearestHit.normal.z; normalEnd.z = nearestHit.position.z + nearestHit.normal.z;
DrawLine3D(nearestHit.position, normalEnd, RED); DrawLine3D(nearestHit.position, normalEnd, RED);
} }
DrawRay(ray, MAROON); DrawRay(ray, MAROON);
DrawGrid(10, 10.0f); DrawGrid(10, 10.0f);
EndMode3D(); EndMode3D();
// Draw some debug GUI text // Draw some debug GUI text
DrawText(FormatText("Hit Object: %s", hitObjectName), 10, 50, 10, BLACK); DrawText(FormatText("Hit Object: %s", hitObjectName), 10, 50, 10, BLACK);
if (nearestHit.hit) if (nearestHit.hit)
{ {
int ypos = 70; int ypos = 70;
DrawText(FormatText("Distance: %3.2f", nearestHit.distance), 10, ypos, 10, BLACK); DrawText(FormatText("Distance: %3.2f", nearestHit.distance), 10, ypos, 10, BLACK);
DrawText(FormatText("Hit Pos: %3.2f %3.2f %3.2f", DrawText(FormatText("Hit Pos: %3.2f %3.2f %3.2f",
nearestHit.position.x, nearestHit.position.x,
nearestHit.position.y, nearestHit.position.y,
nearestHit.position.z), 10, ypos + 15, 10, BLACK); nearestHit.position.z), 10, ypos + 15, 10, BLACK);
DrawText(FormatText("Hit Norm: %3.2f %3.2f %3.2f", DrawText(FormatText("Hit Norm: %3.2f %3.2f %3.2f",
nearestHit.normal.x, nearestHit.normal.x,
nearestHit.normal.y, nearestHit.normal.y,
nearestHit.normal.z), 10, ypos + 30, 10, BLACK); nearestHit.normal.z), 10, ypos + 30, 10, BLACK);
if (hitTriangle) DrawText(FormatText("Barycenter: %3.2f %3.2f %3.2f", bary.x, bary.y, bary.z), 10, ypos + 45, 10, BLACK); if (hitTriangle) DrawText(FormatText("Barycenter: %3.2f %3.2f %3.2f", bary.x, bary.y, bary.z), 10, ypos + 45, 10, BLACK);
} }
DrawText("Use Mouse to Move Camera", 10, 430, 10, GRAY); DrawText("Use Mouse to Move Camera", 10, 430, 10, GRAY);
DrawText("(c) Turret 3D model by Alberto Cano", screenWidth - 200, screenHeight - 20, 10, GRAY); DrawText("(c) Turret 3D model by Alberto Cano", screenWidth - 200, screenHeight - 20, 10, GRAY);
DrawFPS(10, 10); DrawFPS(10, 10);
@ -195,7 +194,7 @@ int main()
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
UnloadModel(tower); // Unload model UnloadModel(tower); // Unload model
UnloadTexture(texture); // Unload texture UnloadTexture(texture); // Unload texture
CloseWindow(); // Close window and OpenGL context CloseWindow(); // Close window and OpenGL context
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------

View file

@ -11,12 +11,12 @@
#include "raylib.h" #include "raylib.h"
int main() int main(void)
{ {
// Initialization // Initialization
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
int screenWidth = 800; const int screenWidth = 800;
int screenHeight = 450; const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [models] example - obj model loading"); InitWindow(screenWidth, screenHeight, "raylib [models] example - obj model loading");
@ -33,7 +33,7 @@ int main()
model.materials[0].maps[MAP_DIFFUSE].texture = texture; // Set map diffuse texture model.materials[0].maps[MAP_DIFFUSE].texture = texture; // Set map diffuse texture
Vector3 position = { 0.0f, 0.0f, 0.0f }; // Set model position Vector3 position = { 0.0f, 0.0f, 0.0f }; // Set model position
SetTargetFPS(60); // Set our game to run at 60 frames-per-second SetTargetFPS(60); // Set our game to run at 60 frames-per-second
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
// Main game loop // Main game loop

View file

@ -13,12 +13,12 @@
#include <string.h> // Required for: strcpy() #include <string.h> // Required for: strcpy()
int main() int main(void)
{ {
// Initialization // Initialization
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
int screenWidth = 800; const int screenWidth = 800;
int screenHeight = 450; const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib example - obj viewer"); InitWindow(screenWidth, screenHeight, "raylib example - obj viewer");
@ -37,7 +37,7 @@ int main()
char objFilename[64] = "turret.obj"; char objFilename[64] = "turret.obj";
SetTargetFPS(60); // Set our game to run at 60 frames-per-second SetTargetFPS(60); // Set our game to run at 60 frames-per-second
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
// Main game loop // Main game loop

View file

@ -1,6 +1,6 @@
/******************************************************************************************* /*******************************************************************************************
* *
* raylib [models] example - Show the difference between perspective and orthographic projection * raylib [models] example - Show the difference between perspective and orthographic projection
* *
* This program is heavily based on the geometric objects example * This program is heavily based on the geometric objects example
* *
@ -18,19 +18,19 @@
#define FOVY_PERSPECTIVE 45.0f #define FOVY_PERSPECTIVE 45.0f
#define WIDTH_ORTHOGRAPHIC 10.0f #define WIDTH_ORTHOGRAPHIC 10.0f
int main() int main(void)
{ {
// Initialization // Initialization
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
int screenWidth = 800; const int screenWidth = 800;
int screenHeight = 450; const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [models] example - geometric shapes"); InitWindow(screenWidth, screenHeight, "raylib [models] example - geometric shapes");
// Define the camera to look into our 3d world // Define the camera to look into our 3d world
Camera camera = {{ 0.0f, 10.0f, 10.0f }, { 0.0f, 0.0f, 0.0f }, { 0.0f, 1.0f, 0.0f }, FOVY_PERSPECTIVE, CAMERA_PERSPECTIVE }; Camera camera = {{ 0.0f, 10.0f, 10.0f }, { 0.0f, 0.0f, 0.0f }, { 0.0f, 1.0f, 0.0f }, FOVY_PERSPECTIVE, CAMERA_PERSPECTIVE };
SetTargetFPS(60); // Set our game to run at 60 frames-per-second SetTargetFPS(60); // Set our game to run at 60 frames-per-second
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
// Main game loop // Main game loop
@ -38,14 +38,14 @@ int main()
{ {
// Update // Update
//---------------------------------------------------------------------------------- //----------------------------------------------------------------------------------
if (IsKeyPressed(KEY_SPACE)) if (IsKeyPressed(KEY_SPACE))
{ {
if (camera.type == CAMERA_PERSPECTIVE) if (camera.type == CAMERA_PERSPECTIVE)
{ {
camera.fovy = WIDTH_ORTHOGRAPHIC; camera.fovy = WIDTH_ORTHOGRAPHIC;
camera.type = CAMERA_ORTHOGRAPHIC; camera.type = CAMERA_ORTHOGRAPHIC;
} }
else else
{ {
camera.fovy = FOVY_PERSPECTIVE; camera.fovy = FOVY_PERSPECTIVE;
camera.type = CAMERA_PERSPECTIVE; camera.type = CAMERA_PERSPECTIVE;

View file

@ -22,13 +22,13 @@ void DrawSphereBasic(Color color); // Draw sphere without any matrix transf
//------------------------------------------------------------------------------------ //------------------------------------------------------------------------------------
// Program main entry point // Program main entry point
//------------------------------------------------------------------------------------ //------------------------------------------------------------------------------------
int main() int main(void)
{ {
// Initialization // Initialization
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
const int screenWidth = 800; const int screenWidth = 800;
const int screenHeight = 450; const int screenHeight = 450;
const float sunRadius = 4.0f; const float sunRadius = 4.0f;
const float earthRadius = 0.6f; const float earthRadius = 0.6f;
const float earthOrbitRadius = 8.0f; const float earthOrbitRadius = 8.0f;
@ -44,26 +44,26 @@ int main()
camera.up = (Vector3){ 0.0f, 1.0f, 0.0f }; camera.up = (Vector3){ 0.0f, 1.0f, 0.0f };
camera.fovy = 45.0f; camera.fovy = 45.0f;
camera.type = CAMERA_PERSPECTIVE; camera.type = CAMERA_PERSPECTIVE;
SetCameraMode(camera, CAMERA_FREE); SetCameraMode(camera, CAMERA_FREE);
float rotationSpeed = 0.2f; // General system rotation speed float rotationSpeed = 0.2f; // General system rotation speed
float earthRotation = 0.0f; // Rotation of earth around itself (days) in degrees float earthRotation = 0.0f; // Rotation of earth around itself (days) in degrees
float earthOrbitRotation = 0.0f; // Rotation of earth around the Sun (years) in degrees float earthOrbitRotation = 0.0f; // Rotation of earth around the Sun (years) in degrees
float moonRotation = 0.0f; // Rotation of moon around itself float moonRotation = 0.0f; // Rotation of moon around itself
float moonOrbitRotation = 0.0f; // Rotation of moon around earth in degrees float moonOrbitRotation = 0.0f; // Rotation of moon around earth in degrees
SetTargetFPS(60); // Set our game to run at 60 frames-per-second SetTargetFPS(60); // Set our game to run at 60 frames-per-second
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
// Main game loop // Main game loop
while (!WindowShouldClose()) // Detect window close button or ESC key while (!WindowShouldClose()) // Detect window close button or ESC key
{ {
// Update // Update
//---------------------------------------------------------------------------------- //----------------------------------------------------------------------------------
UpdateCamera(&camera); UpdateCamera(&camera);
earthRotation += (5.0f*rotationSpeed); earthRotation += (5.0f*rotationSpeed);
earthOrbitRotation += (365/360.0f*(5.0f*rotationSpeed)*rotationSpeed); earthOrbitRotation += (365/360.0f*(5.0f*rotationSpeed)*rotationSpeed);
moonRotation += (2.0f*rotationSpeed); moonRotation += (2.0f*rotationSpeed);
@ -77,12 +77,12 @@ int main()
ClearBackground(RAYWHITE); ClearBackground(RAYWHITE);
BeginMode3D(camera); BeginMode3D(camera);
rlPushMatrix(); rlPushMatrix();
rlScalef(sunRadius, sunRadius, sunRadius); // Scale Sun rlScalef(sunRadius, sunRadius, sunRadius); // Scale Sun
DrawSphereBasic(GOLD); // Draw the Sun DrawSphereBasic(GOLD); // Draw the Sun
rlPopMatrix(); rlPopMatrix();
rlPushMatrix(); rlPushMatrix();
rlRotatef(earthOrbitRotation, 0.0f, 1.0f, 0.0f); // Rotation for Earth orbit around Sun rlRotatef(earthOrbitRotation, 0.0f, 1.0f, 0.0f); // Rotation for Earth orbit around Sun
rlTranslatef(earthOrbitRadius, 0.0f, 0.0f); // Translation for Earth orbit rlTranslatef(earthOrbitRadius, 0.0f, 0.0f); // Translation for Earth orbit
@ -91,19 +91,19 @@ int main()
rlPushMatrix(); rlPushMatrix();
rlRotatef(earthRotation, 0.25, 1.0, 0.0); // Rotation for Earth itself rlRotatef(earthRotation, 0.25, 1.0, 0.0); // Rotation for Earth itself
rlScalef(earthRadius, earthRadius, earthRadius);// Scale Earth rlScalef(earthRadius, earthRadius, earthRadius);// Scale Earth
DrawSphereBasic(BLUE); // Draw the Earth DrawSphereBasic(BLUE); // Draw the Earth
rlPopMatrix(); rlPopMatrix();
rlRotatef(moonOrbitRotation, 0.0f, 1.0f, 0.0f); // Rotation for Moon orbit around Earth rlRotatef(moonOrbitRotation, 0.0f, 1.0f, 0.0f); // Rotation for Moon orbit around Earth
rlTranslatef(moonOrbitRadius, 0.0f, 0.0f); // Translation for Moon orbit rlTranslatef(moonOrbitRadius, 0.0f, 0.0f); // Translation for Moon orbit
rlRotatef(-moonOrbitRotation, 0.0f, 1.0f, 0.0f); // Rotation for Moon orbit around Earth inverted rlRotatef(-moonOrbitRotation, 0.0f, 1.0f, 0.0f); // Rotation for Moon orbit around Earth inverted
rlRotatef(moonRotation, 0.0f, 1.0f, 0.0f); // Rotation for Moon itself rlRotatef(moonRotation, 0.0f, 1.0f, 0.0f); // Rotation for Moon itself
rlScalef(moonRadius, moonRadius, moonRadius); // Scale Moon rlScalef(moonRadius, moonRadius, moonRadius); // Scale Moon
DrawSphereBasic(LIGHTGRAY); // Draw the Moon DrawSphereBasic(LIGHTGRAY); // Draw the Moon
rlPopMatrix(); rlPopMatrix();
// Some reference elements (not affected by previous matrix transformations) // Some reference elements (not affected by previous matrix transformations)
DrawCircle3D((Vector3){ 0.0f, 0.0f, 0.0f }, earthOrbitRadius, (Vector3){ 1, 0, 0 }, 90.0f, Fade(RED, 0.5f)); DrawCircle3D((Vector3){ 0.0f, 0.0f, 0.0f }, earthOrbitRadius, (Vector3){ 1, 0, 0 }, 90.0f, Fade(RED, 0.5f));
DrawGrid(20, 1.0f); DrawGrid(20, 1.0f);
@ -135,7 +135,7 @@ void DrawSphereBasic(Color color)
{ {
int rings = 16; int rings = 16;
int slices = 16; int slices = 16;
rlBegin(RL_TRIANGLES); rlBegin(RL_TRIANGLES);
rlColor4ub(color.r, color.g, color.b, color.a); rlColor4ub(color.r, color.g, color.b, color.a);

View file

@ -11,22 +11,22 @@
#include "raylib.h" #include "raylib.h"
int main() int main(void)
{ {
// Initialization // Initialization
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
int screenWidth = 800; const int screenWidth = 800;
int screenHeight = 450; const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [models] example - skybox loading and drawing"); InitWindow(screenWidth, screenHeight, "raylib [models] example - skybox loading and drawing");
// Define the camera to look into our 3d world // Define the camera to look into our 3d world
Camera camera = {{ 1.0f, 1.0f, 1.0f }, { 4.0f, 1.0f, 4.0f }, { 0.0f, 1.0f, 0.0f }, 45.0f, 0 }; Camera camera = {{ 1.0f, 1.0f, 1.0f }, { 4.0f, 1.0f, 4.0f }, { 0.0f, 1.0f, 0.0f }, 45.0f, 0 };
// Load skybox model // Load skybox model
Mesh cube = GenMeshCube(1.0f, 1.0f, 1.0f); Mesh cube = GenMeshCube(1.0f, 1.0f, 1.0f);
Model skybox = LoadModelFromMesh(cube); Model skybox = LoadModelFromMesh(cube);
// Load skybox shader and set required locations // Load skybox shader and set required locations
// NOTE: Some locations are automatically set at shader loading // NOTE: Some locations are automatically set at shader loading
#if defined(PLATFORM_DESKTOP) #if defined(PLATFORM_DESKTOP)
@ -43,17 +43,17 @@ int main()
Shader shdrCubemap = LoadShader("resources/shaders/glsl100/cubemap.vs", "resources/shaders/glsl100/cubemap.fs"); Shader shdrCubemap = LoadShader("resources/shaders/glsl100/cubemap.vs", "resources/shaders/glsl100/cubemap.fs");
#endif #endif
SetShaderValue(shdrCubemap, GetShaderLocation(shdrCubemap, "equirectangularMap"), (int[1]){ 0 }, UNIFORM_INT); SetShaderValue(shdrCubemap, GetShaderLocation(shdrCubemap, "equirectangularMap"), (int[1]){ 0 }, UNIFORM_INT);
// Load HDR panorama (sphere) texture // Load HDR panorama (sphere) texture
Texture2D texHDR = LoadTexture("resources/dresden_square.hdr"); Texture2D texHDR = LoadTexture("resources/dresden_square.hdr");
// Generate cubemap (texture with 6 quads-cube-mapping) from panorama HDR texture // Generate cubemap (texture with 6 quads-cube-mapping) from panorama HDR texture
// NOTE: New texture is generated rendering to texture, shader computes the sphre->cube coordinates mapping // NOTE: New texture is generated rendering to texture, shader computes the sphre->cube coordinates mapping
skybox.materials[0].maps[MAP_CUBEMAP].texture = GenTextureCubemap(shdrCubemap, texHDR, 512); skybox.materials[0].maps[MAP_CUBEMAP].texture = GenTextureCubemap(shdrCubemap, texHDR, 512);
UnloadTexture(texHDR); // Texture not required anymore, cubemap already generated UnloadTexture(texHDR); // Texture not required anymore, cubemap already generated
UnloadShader(shdrCubemap); // Unload cubemap generation shader, not required anymore UnloadShader(shdrCubemap); // Unload cubemap generation shader, not required anymore
SetCameraMode(camera, CAMERA_FIRST_PERSON); // Set a first person camera mode SetCameraMode(camera, CAMERA_FIRST_PERSON); // Set a first person camera mode
SetTargetFPS(60); // Set our game to run at 60 frames-per-second SetTargetFPS(60); // Set our game to run at 60 frames-per-second
@ -76,7 +76,7 @@ int main()
BeginMode3D(camera); BeginMode3D(camera);
DrawModel(skybox, (Vector3){0, 0, 0}, 1.0f, WHITE); DrawModel(skybox, (Vector3){0, 0, 0}, 1.0f, WHITE);
DrawGrid(10, 1.0f); DrawGrid(10, 1.0f);
EndMode3D(); EndMode3D();

View file

@ -17,10 +17,7 @@
// Draw angle gauge controls // Draw angle gauge controls
void DrawAngleGauge(Texture2D angleGauge, int x, int y, float angle, char title[], Color color); void DrawAngleGauge(Texture2D angleGauge, int x, int y, float angle, char title[], Color color);
//---------------------------------------------------------------------------------- int main(void)
// Main entry point
//----------------------------------------------------------------------------------
int main()
{ {
// Initialization // Initialization
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
@ -53,10 +50,10 @@ int main()
float roll = 0.0f; float roll = 0.0f;
float yaw = 0.0f; float yaw = 0.0f;
SetTargetFPS(60); SetTargetFPS(60); // Set our game to run at 60 frames-per-second
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
// Main game loop
while (!WindowShouldClose()) // Detect window close button or ESC key while (!WindowShouldClose()) // Detect window close button or ESC key
{ {
// Update // Update

View file

@ -10,7 +10,7 @@
* gcc -o $(NAME_PART).exe $(FILE_NAME) -s -static / * gcc -o $(NAME_PART).exe $(FILE_NAME) -s -static /
* -lraylib -lpthread -lglfw3 -lopengl32 -lgdi32 -lopenal32 -lwinmm / * -lraylib -lpthread -lglfw3 -lopengl32 -lgdi32 -lopenal32 -lwinmm /
* -std=c99 -Wl,--subsystem,windows -Wl,-allow-multiple-definition * -std=c99 -Wl,--subsystem,windows -Wl,-allow-multiple-definition
* *
* Copyright (c) 2016-2018 Victor Fisac * Copyright (c) 2016-2018 Victor Fisac
* *
********************************************************************************************/ ********************************************************************************************/
@ -21,12 +21,12 @@
#define PHYSAC_NO_THREADS #define PHYSAC_NO_THREADS
#include "physac.h" #include "physac.h"
int main() int main(void)
{ {
// Initialization // Initialization
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
int screenWidth = 800; const int screenWidth = 800;
int screenHeight = 450; const int screenHeight = 450;
SetConfigFlags(FLAG_MSAA_4X_HINT); SetConfigFlags(FLAG_MSAA_4X_HINT);
InitWindow(screenWidth, screenHeight, "Physac [raylib] - Physics demo"); InitWindow(screenWidth, screenHeight, "Physac [raylib] - Physics demo");
@ -41,13 +41,13 @@ int main()
// Create floor rectangle physics body // Create floor rectangle physics body
PhysicsBody floor = CreatePhysicsBodyRectangle((Vector2){ screenWidth/2, screenHeight }, 500, 100, 10); PhysicsBody floor = CreatePhysicsBodyRectangle((Vector2){ screenWidth/2, screenHeight }, 500, 100, 10);
floor->enabled = false; // Disable body state to convert it to static (no dynamics, but collisions) floor->enabled = false; // Disable body state to convert it to static (no dynamics, but collisions)
// Create obstacle circle physics body // Create obstacle circle physics body
PhysicsBody circle = CreatePhysicsBodyCircle((Vector2){ screenWidth/2, screenHeight/2 }, 45, 10); PhysicsBody circle = CreatePhysicsBodyCircle((Vector2){ screenWidth/2, screenHeight/2 }, 45, 10);
circle->enabled = false; // Disable body state to convert it to static (no dynamics, but collisions) circle->enabled = false; // Disable body state to convert it to static (no dynamics, but collisions)
SetTargetFPS(60); SetTargetFPS(60); // Set our game to run at 60 frames-per-second
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
// Main game loop // Main game loop
@ -132,9 +132,9 @@ int main()
} }
// De-Initialization // De-Initialization
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
ClosePhysics(); // Unitialize physics ClosePhysics(); // Unitialize physics
CloseWindow(); // Close window and OpenGL context CloseWindow(); // Close window and OpenGL context
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------

View file

@ -10,7 +10,7 @@
* gcc -o $(NAME_PART).exe $(FILE_NAME) -s -static / * gcc -o $(NAME_PART).exe $(FILE_NAME) -s -static /
* -lraylib -lpthread -lglfw3 -lopengl32 -lgdi32 -lopenal32 -lwinmm / * -lraylib -lpthread -lglfw3 -lopengl32 -lgdi32 -lopenal32 -lwinmm /
* -std=c99 -Wl,--subsystem,windows -Wl,-allow-multiple-definition * -std=c99 -Wl,--subsystem,windows -Wl,-allow-multiple-definition
* *
* Copyright (c) 2016-2018 Victor Fisac * Copyright (c) 2016-2018 Victor Fisac
* *
********************************************************************************************/ ********************************************************************************************/
@ -21,12 +21,12 @@
#define PHYSAC_NO_THREADS #define PHYSAC_NO_THREADS
#include "physac.h" #include "physac.h"
int main() int main(void)
{ {
// Initialization // Initialization
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
int screenWidth = 800; const int screenWidth = 800;
int screenHeight = 450; const int screenHeight = 450;
SetConfigFlags(FLAG_MSAA_4X_HINT); SetConfigFlags(FLAG_MSAA_4X_HINT);
InitWindow(screenWidth, screenHeight, "Physac [raylib] - Physics friction"); InitWindow(screenWidth, screenHeight, "Physac [raylib] - Physics friction");
@ -65,7 +65,7 @@ int main()
bodyB->dynamicFriction = 1; bodyB->dynamicFriction = 1;
SetPhysicsBodyRotation(bodyB, 330*DEG2RAD); SetPhysicsBodyRotation(bodyB, 330*DEG2RAD);
SetTargetFPS(60); SetTargetFPS(60); // Set our game to run at 60 frames-per-second
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
// Main game loop // Main game loop
@ -82,7 +82,7 @@ int main()
bodyA->velocity = (Vector2){ 0, 0 }; bodyA->velocity = (Vector2){ 0, 0 };
bodyA->angularVelocity = 0; bodyA->angularVelocity = 0;
SetPhysicsBodyRotation(bodyA, 30*DEG2RAD); SetPhysicsBodyRotation(bodyA, 30*DEG2RAD);
bodyB->position = (Vector2){ screenWidth - 35, screenHeight*0.6f }; bodyB->position = (Vector2){ screenWidth - 35, screenHeight*0.6f };
bodyB->velocity = (Vector2){ 0, 0 }; bodyB->velocity = (Vector2){ 0, 0 };
bodyB->angularVelocity = 0; bodyB->angularVelocity = 0;
@ -137,9 +137,9 @@ int main()
} }
// De-Initialization // De-Initialization
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
ClosePhysics(); // Unitialize physics ClosePhysics(); // Unitialize physics
CloseWindow(); // Close window and OpenGL context CloseWindow(); // Close window and OpenGL context
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------

View file

@ -10,7 +10,7 @@
* gcc -o $(NAME_PART).exe $(FILE_NAME) -s -static / * gcc -o $(NAME_PART).exe $(FILE_NAME) -s -static /
* -lraylib -lpthread -lglfw3 -lopengl32 -lgdi32 -lopenal32 -lwinmm / * -lraylib -lpthread -lglfw3 -lopengl32 -lgdi32 -lopenal32 -lwinmm /
* -std=c99 -Wl,--subsystem,windows -Wl,-allow-multiple-definition * -std=c99 -Wl,--subsystem,windows -Wl,-allow-multiple-definition
* *
* Copyright (c) 2016-2018 Victor Fisac * Copyright (c) 2016-2018 Victor Fisac
* *
********************************************************************************************/ ********************************************************************************************/
@ -23,12 +23,12 @@
#define VELOCITY 0.5f #define VELOCITY 0.5f
int main() int main(void)
{ {
// Initialization // Initialization
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
int screenWidth = 800; const int screenWidth = 800;
int screenHeight = 450; const int screenHeight = 450;
SetConfigFlags(FLAG_MSAA_4X_HINT); SetConfigFlags(FLAG_MSAA_4X_HINT);
InitWindow(screenWidth, screenHeight, "Physac [raylib] - Physics movement"); InitWindow(screenWidth, screenHeight, "Physac [raylib] - Physics movement");
@ -56,9 +56,9 @@ int main()
// Create movement physics body // Create movement physics body
PhysicsBody body = CreatePhysicsBodyRectangle((Vector2){ screenWidth/2, screenHeight/2 }, 50, 50, 1); PhysicsBody body = CreatePhysicsBodyRectangle((Vector2){ screenWidth/2, screenHeight/2 }, 50, 50, 1);
body->freezeOrient = true; // Constrain body rotation to avoid little collision torque amounts body->freezeOrient = true; // Constrain body rotation to avoid little collision torque amounts
SetTargetFPS(60); SetTargetFPS(60); // Set our game to run at 60 frames-per-second
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
// Main game loop // Main game loop
@ -123,9 +123,9 @@ int main()
} }
// De-Initialization // De-Initialization
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
ClosePhysics(); // Unitialize physics ClosePhysics(); // Unitialize physics
CloseWindow(); // Close window and OpenGL context CloseWindow(); // Close window and OpenGL context
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------

View file

@ -10,7 +10,7 @@
* gcc -o $(NAME_PART).exe $(FILE_NAME) -s -static / * gcc -o $(NAME_PART).exe $(FILE_NAME) -s -static /
* -lraylib -lpthread -lglfw3 -lopengl32 -lgdi32 -lopenal32 -lwinmm / * -lraylib -lpthread -lglfw3 -lopengl32 -lgdi32 -lopenal32 -lwinmm /
* -std=c99 -Wl,--subsystem,windows -Wl,-allow-multiple-definition * -std=c99 -Wl,--subsystem,windows -Wl,-allow-multiple-definition
* *
* Copyright (c) 2016-2018 Victor Fisac * Copyright (c) 2016-2018 Victor Fisac
* *
********************************************************************************************/ ********************************************************************************************/
@ -21,12 +21,12 @@
#define PHYSAC_NO_THREADS #define PHYSAC_NO_THREADS
#include "physac.h" #include "physac.h"
int main() int main(void)
{ {
// Initialization // Initialization
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
int screenWidth = 800; const int screenWidth = 800;
int screenHeight = 450; const int screenHeight = 450;
SetConfigFlags(FLAG_MSAA_4X_HINT); SetConfigFlags(FLAG_MSAA_4X_HINT);
InitWindow(screenWidth, screenHeight, "Physac [raylib] - Physics restitution"); InitWindow(screenWidth, screenHeight, "Physac [raylib] - Physics restitution");
@ -50,11 +50,11 @@ int main()
circleB->restitution = 0.5f; circleB->restitution = 0.5f;
PhysicsBody circleC = CreatePhysicsBodyCircle((Vector2){ screenWidth*0.75f, screenHeight/2 }, 30, 10); PhysicsBody circleC = CreatePhysicsBodyCircle((Vector2){ screenWidth*0.75f, screenHeight/2 }, 30, 10);
circleC->restitution = 1; circleC->restitution = 1;
SetTargetFPS(60);
// Restitution demo needs a very tiny physics time step for a proper simulation // Restitution demo needs a very tiny physics time step for a proper simulation
SetPhysicsTimeStep(1.0/60.0/100 * 1000); SetPhysicsTimeStep(1.0/60.0/100*1000);
SetTargetFPS(60); // Set our game to run at 60 frames-per-second
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
// Main game loop // Main game loop
@ -119,9 +119,9 @@ int main()
} }
// De-Initialization // De-Initialization
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
ClosePhysics(); // Unitialize physics ClosePhysics(); // Unitialize physics
CloseWindow(); // Close window and OpenGL context CloseWindow(); // Close window and OpenGL context
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------

View file

@ -10,7 +10,7 @@
* gcc -o $(NAME_PART).exe $(FILE_NAME) -s -static / * gcc -o $(NAME_PART).exe $(FILE_NAME) -s -static /
* -lraylib -lpthread -lglfw3 -lopengl32 -lgdi32 -lopenal32 -lwinmm / * -lraylib -lpthread -lglfw3 -lopengl32 -lgdi32 -lopenal32 -lwinmm /
* -std=c99 -Wl,--subsystem,windows -Wl,-allow-multiple-definition * -std=c99 -Wl,--subsystem,windows -Wl,-allow-multiple-definition
* *
* Copyright (c) 2016-2018 Victor Fisac * Copyright (c) 2016-2018 Victor Fisac
* *
********************************************************************************************/ ********************************************************************************************/
@ -21,12 +21,12 @@
#define PHYSAC_NO_THREADS #define PHYSAC_NO_THREADS
#include "physac.h" #include "physac.h"
int main() int main(void)
{ {
// Initialization // Initialization
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
int screenWidth = 800; const int screenWidth = 800;
int screenHeight = 450; const int screenHeight = 450;
SetConfigFlags(FLAG_MSAA_4X_HINT); SetConfigFlags(FLAG_MSAA_4X_HINT);
InitWindow(screenWidth, screenHeight, "Physac [raylib] - Body shatter"); InitWindow(screenWidth, screenHeight, "Physac [raylib] - Body shatter");
@ -43,7 +43,7 @@ int main()
// Create random polygon physics body to shatter // Create random polygon physics body to shatter
CreatePhysicsBodyPolygon((Vector2){ screenWidth/2, screenHeight/2 }, GetRandomValue(80, 200), GetRandomValue(3, 8), 10); CreatePhysicsBodyPolygon((Vector2){ screenWidth/2, screenHeight/2 }, GetRandomValue(80, 200), GetRandomValue(3, 8), 10);
SetTargetFPS(60); SetTargetFPS(60); // Set our game to run at 60 frames-per-second
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
// Main game loop // Main game loop
@ -115,9 +115,9 @@ int main()
} }
// De-Initialization // De-Initialization
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
ClosePhysics(); // Unitialize physics ClosePhysics(); // Unitialize physics
CloseWindow(); // Close window and OpenGL context CloseWindow(); // Close window and OpenGL context
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------

View file

@ -24,13 +24,13 @@
#define GLSL_VERSION 100 #define GLSL_VERSION 100
#endif #endif
int main() int main(void)
{ {
// Initialization // Initialization
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
int screenWidth = 800; const int screenWidth = 800;
int screenHeight = 450; const int screenHeight = 450;
SetConfigFlags(FLAG_MSAA_4X_HINT); // Enable Multi Sampling Anti Aliasing 4x (if available) SetConfigFlags(FLAG_MSAA_4X_HINT); // Enable Multi Sampling Anti Aliasing 4x (if available)
InitWindow(screenWidth, screenHeight, "raylib [shaders] example - custom uniform variable"); InitWindow(screenWidth, screenHeight, "raylib [shaders] example - custom uniform variable");
@ -48,20 +48,20 @@ int main()
model.materials[0].maps[MAP_DIFFUSE].texture = texture; // Set model diffuse texture model.materials[0].maps[MAP_DIFFUSE].texture = texture; // Set model diffuse texture
Vector3 position = { 0.0f, 0.0f, 0.0f }; // Set model position Vector3 position = { 0.0f, 0.0f, 0.0f }; // Set model position
// Load postprocessing shader // Load postprocessing shader
// NOTE: Defining 0 (NULL) for vertex shader forces usage of internal default vertex shader // NOTE: Defining 0 (NULL) for vertex shader forces usage of internal default vertex shader
Shader shader = LoadShader(0, FormatText("resources/shaders/glsl%i/swirl.fs", GLSL_VERSION)); Shader shader = LoadShader(0, FormatText("resources/shaders/glsl%i/swirl.fs", GLSL_VERSION));
// Get variable (uniform) location on the shader to connect with the program // Get variable (uniform) location on the shader to connect with the program
// NOTE: If uniform variable could not be found in the shader, function returns -1 // NOTE: If uniform variable could not be found in the shader, function returns -1
int swirlCenterLoc = GetShaderLocation(shader, "center"); int swirlCenterLoc = GetShaderLocation(shader, "center");
float swirlCenter[2] = { (float)screenWidth/2, (float)screenHeight/2 }; float swirlCenter[2] = { (float)screenWidth/2, (float)screenHeight/2 };
// Create a RenderTexture2D to be used for render to texture // Create a RenderTexture2D to be used for render to texture
RenderTexture2D target = LoadRenderTexture(screenWidth, screenHeight); RenderTexture2D target = LoadRenderTexture(screenWidth, screenHeight);
// Setup orbital camera // Setup orbital camera
SetCameraMode(camera, CAMERA_ORBITAL); // Set an orbital camera mode SetCameraMode(camera, CAMERA_ORBITAL); // Set an orbital camera mode
@ -80,7 +80,7 @@ int main()
// Send new value to the shader to be used on drawing // Send new value to the shader to be used on drawing
SetShaderValue(shader, swirlCenterLoc, swirlCenter, UNIFORM_VEC2); SetShaderValue(shader, swirlCenterLoc, swirlCenter, UNIFORM_VEC2);
UpdateCamera(&camera); // Update camera UpdateCamera(&camera); // Update camera
//---------------------------------------------------------------------------------- //----------------------------------------------------------------------------------
@ -89,9 +89,9 @@ int main()
BeginDrawing(); BeginDrawing();
ClearBackground(RAYWHITE); ClearBackground(RAYWHITE);
BeginTextureMode(target); // Enable drawing to texture BeginTextureMode(target); // Enable drawing to texture
ClearBackground(RAYWHITE); // Clear texture background ClearBackground(RAYWHITE); // Clear texture background
BeginMode3D(camera); // Begin 3d mode drawing BeginMode3D(camera); // Begin 3d mode drawing
@ -101,21 +101,21 @@ int main()
DrawGrid(10, 1.0f); // Draw a grid DrawGrid(10, 1.0f); // Draw a grid
EndMode3D(); // End 3d mode drawing, returns to orthographic 2d mode EndMode3D(); // End 3d mode drawing, returns to orthographic 2d mode
DrawText("TEXT DRAWN IN RENDER TEXTURE", 200, 10, 30, RED); DrawText("TEXT DRAWN IN RENDER TEXTURE", 200, 10, 30, RED);
EndTextureMode(); // End drawing to texture (now we have a texture available for next passes) EndTextureMode(); // End drawing to texture (now we have a texture available for next passes)
BeginShaderMode(shader); BeginShaderMode(shader);
// NOTE: Render texture must be y-flipped due to default OpenGL coordinates (left-bottom) // NOTE: Render texture must be y-flipped due to default OpenGL coordinates (left-bottom)
DrawTextureRec(target.texture, (Rectangle){ 0, 0, target.texture.width, -target.texture.height }, (Vector2){ 0, 0 }, WHITE); DrawTextureRec(target.texture, (Rectangle){ 0, 0, target.texture.width, -target.texture.height }, (Vector2){ 0, 0 }, WHITE);
EndShaderMode(); EndShaderMode();
// Draw some 2d text over drawn texture // Draw some 2d text over drawn texture
DrawText("(c) Barracks 3D model by Alberto Cano", screenWidth - 220, screenHeight - 20, 10, GRAY); DrawText("(c) Barracks 3D model by Alberto Cano", screenWidth - 220, screenHeight - 20, 10, GRAY);
DrawFPS(10, 10); DrawFPS(10, 10);
EndDrawing(); EndDrawing();

View file

@ -31,7 +31,7 @@
#define GLSL_VERSION 100 #define GLSL_VERSION 100
#endif #endif
int main() int main(void)
{ {
// Initialization // Initialization
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
@ -46,11 +46,11 @@ int main()
// NOTE: Defining 0 (NULL) for vertex shader forces usage of internal default vertex shader // NOTE: Defining 0 (NULL) for vertex shader forces usage of internal default vertex shader
Shader shader = LoadShader(0, FormatText("resources/shaders/glsl%i/eratosthenes.fs", GLSL_VERSION)); Shader shader = LoadShader(0, FormatText("resources/shaders/glsl%i/eratosthenes.fs", GLSL_VERSION));
SetTargetFPS(60); SetTargetFPS(60); // Set our game to run at 60 frames-per-second
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
// Main game loop // Main game loop
while (!WindowShouldClose()) // Detect window close button or ESC key while (!WindowShouldClose()) // Detect window close button or ESC key
{ {
// Update // Update
//---------------------------------------------------------------------------------- //----------------------------------------------------------------------------------
@ -64,7 +64,7 @@ int main()
ClearBackground(RAYWHITE); ClearBackground(RAYWHITE);
BeginTextureMode(target); // Enable drawing to texture BeginTextureMode(target); // Enable drawing to texture
ClearBackground(BLACK); // Clear the render texture ClearBackground(BLACK); // Clear the render texture
// Draw a rectangle in shader mode to be used as shader canvas // Draw a rectangle in shader mode to be used as shader canvas
// NOTE: Rectangle uses font white character texture coordinates, // NOTE: Rectangle uses font white character texture coordinates,

View file

@ -26,7 +26,7 @@
// A few good julia sets // A few good julia sets
const float POINTS_OF_INTEREST[6][2] = const float POINTS_OF_INTEREST[6][2] =
{ {
{ -0.348827, 0.607167 }, { -0.348827, 0.607167 },
{ -0.786268, 0.169728 }, { -0.786268, 0.169728 },
{ -0.8, 0.156 }, { -0.8, 0.156 },
@ -35,7 +35,7 @@ const float POINTS_OF_INTEREST[6][2] =
{ -0.70176, -0.3842 }, { -0.70176, -0.3842 },
}; };
int main() int main(void)
{ {
// Initialization // Initialization
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
@ -47,16 +47,16 @@ int main()
// Load julia set shader // Load julia set shader
// NOTE: Defining 0 (NULL) for vertex shader forces usage of internal default vertex shader // NOTE: Defining 0 (NULL) for vertex shader forces usage of internal default vertex shader
Shader shader = LoadShader(0, FormatText("resources/shaders/glsl%i/julia_set.fs", GLSL_VERSION)); Shader shader = LoadShader(0, FormatText("resources/shaders/glsl%i/julia_set.fs", GLSL_VERSION));
// c constant to use in z^2 + c // c constant to use in z^2 + c
float c[2] = { POINTS_OF_INTEREST[0][0], POINTS_OF_INTEREST[0][1] }; float c[2] = { POINTS_OF_INTEREST[0][0], POINTS_OF_INTEREST[0][1] };
// Offset and zoom to draw the julia set at. (centered on screen and default size) // Offset and zoom to draw the julia set at. (centered on screen and default size)
float offset[2] = { -(float)screenWidth/2, -(float)screenHeight/2 }; float offset[2] = { -(float)screenWidth/2, -(float)screenHeight/2 };
float zoom = 1.0f; float zoom = 1.0f;
Vector2 offsetSpeed = { 0.0f, 0.0f }; Vector2 offsetSpeed = { 0.0f, 0.0f };
// Get variable (uniform) locations on the shader to connect with the program // Get variable (uniform) locations on the shader to connect with the program
// NOTE: If uniform variable could not be found in the shader, function returns -1 // NOTE: If uniform variable could not be found in the shader, function returns -1
int cLoc = GetShaderLocation(shader, "c"); int cLoc = GetShaderLocation(shader, "c");
@ -64,35 +64,34 @@ int main()
int offsetLoc = GetShaderLocation(shader, "offset"); int offsetLoc = GetShaderLocation(shader, "offset");
// Tell the shader what the screen dimensions, zoom, offset and c are // Tell the shader what the screen dimensions, zoom, offset and c are
float screenDims[2] = { (float)GetScreenWidth(), (float)GetScreenHeight() }; float screenDims[2] = { (float)screenWidth, (float)screenHeight };
SetShaderValue(shader, GetShaderLocation(shader, "screenDims"), screenDims, UNIFORM_VEC2); SetShaderValue(shader, GetShaderLocation(shader, "screenDims"), screenDims, UNIFORM_VEC2);
SetShaderValue(shader, cLoc, c, UNIFORM_VEC2); SetShaderValue(shader, cLoc, c, UNIFORM_VEC2);
SetShaderValue(shader, zoomLoc, &zoom, UNIFORM_FLOAT); SetShaderValue(shader, zoomLoc, &zoom, UNIFORM_FLOAT);
SetShaderValue(shader, offsetLoc, offset, UNIFORM_VEC2); SetShaderValue(shader, offsetLoc, offset, UNIFORM_VEC2);
// Create a RenderTexture2D to be used for render to texture // Create a RenderTexture2D to be used for render to texture
RenderTexture2D target = LoadRenderTexture(screenWidth, screenHeight); RenderTexture2D target = LoadRenderTexture(screenWidth, screenHeight);
int incrementSpeed = 0; // Multiplier of speed to change c value
bool showControls = true; // Show controls
bool pause = false; // Pause animation
SetTargetFPS(60); // Set the window to run at 60 frames-per-second int incrementSpeed = 0; // Multiplier of speed to change c value
bool showControls = true; // Show controls
bool pause = false; // Pause animation
SetTargetFPS(60); // Set our game to run at 60 frames-per-second
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
// Main game loop // Main game loop
while (!WindowShouldClose()) // Detect window close button or ESC key while (!WindowShouldClose()) // Detect window close button or ESC key
{ {
// Update // Update
//---------------------------------------------------------------------------------- //----------------------------------------------------------------------------------
// Press [1 - 6] to reset c to a point of interest // Press [1 - 6] to reset c to a point of interest
if (IsKeyPressed(KEY_ONE) || if (IsKeyPressed(KEY_ONE) ||
IsKeyPressed(KEY_TWO) || IsKeyPressed(KEY_TWO) ||
IsKeyPressed(KEY_THREE) || IsKeyPressed(KEY_THREE) ||
IsKeyPressed(KEY_FOUR) || IsKeyPressed(KEY_FOUR) ||
IsKeyPressed(KEY_FIVE) || IsKeyPressed(KEY_FIVE) ||
IsKeyPressed(KEY_SIX)) IsKeyPressed(KEY_SIX))
{ {
if (IsKeyPressed(KEY_ONE)) c[0] = POINTS_OF_INTEREST[0][0], c[1] = POINTS_OF_INTEREST[0][1]; if (IsKeyPressed(KEY_ONE)) c[0] = POINTS_OF_INTEREST[0][0], c[1] = POINTS_OF_INTEREST[0][1];
@ -107,7 +106,7 @@ int main()
if (IsKeyPressed(KEY_SPACE)) pause = !pause; // Pause animation (c change) if (IsKeyPressed(KEY_SPACE)) pause = !pause; // Pause animation (c change)
if (IsKeyPressed(KEY_F1)) showControls = !showControls; // Toggle whether or not to show controls if (IsKeyPressed(KEY_F1)) showControls = !showControls; // Toggle whether or not to show controls
if (!pause) if (!pause)
{ {
if (IsKeyPressed(KEY_RIGHT)) incrementSpeed++; if (IsKeyPressed(KEY_RIGHT)) incrementSpeed++;
@ -121,10 +120,10 @@ int main()
if (IsMouseButtonDown(MOUSE_RIGHT_BUTTON)) zoom -= zoom*0.003f; if (IsMouseButtonDown(MOUSE_RIGHT_BUTTON)) zoom -= zoom*0.003f;
Vector2 mousePos = GetMousePosition(); Vector2 mousePos = GetMousePosition();
offsetSpeed.x = mousePos.x -(float)screenWidth/2; offsetSpeed.x = mousePos.x -(float)screenWidth/2;
offsetSpeed.y = mousePos.y -(float)screenHeight/2; offsetSpeed.y = mousePos.y -(float)screenHeight/2;
// Slowly move camera to targetOffset // Slowly move camera to targetOffset
offset[0] += GetFrameTime()*offsetSpeed.x*0.8f; offset[0] += GetFrameTime()*offsetSpeed.x*0.8f;
offset[1] += GetFrameTime()*offsetSpeed.y*0.8f; offset[1] += GetFrameTime()*offsetSpeed.y*0.8f;
@ -148,7 +147,7 @@ int main()
BeginDrawing(); BeginDrawing();
ClearBackground(BLACK); // Clear the screen of the previous frame. ClearBackground(BLACK); // Clear the screen of the previous frame.
// Using a render texture to draw Julia set // Using a render texture to draw Julia set
BeginTextureMode(target); // Enable drawing to texture BeginTextureMode(target); // Enable drawing to texture
ClearBackground(BLACK); // Clear the render texture ClearBackground(BLACK); // Clear the render texture
@ -165,7 +164,7 @@ int main()
BeginShaderMode(shader); BeginShaderMode(shader);
DrawTexture(target.texture, 0, 0, WHITE); DrawTexture(target.texture, 0, 0, WHITE);
EndShaderMode(); EndShaderMode();
if (showControls) if (showControls)
{ {
DrawText("Press Mouse buttons right/left to zoom in/out and move", 10, 15, 10, RAYWHITE); DrawText("Press Mouse buttons right/left to zoom in/out and move", 10, 15, 10, RAYWHITE);

View file

@ -24,13 +24,13 @@
#define GLSL_VERSION 100 #define GLSL_VERSION 100
#endif #endif
int main() int main(void)
{ {
// Initialization // Initialization
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
int screenWidth = 800; const int screenWidth = 800;
int screenHeight = 450; const int screenHeight = 450;
SetConfigFlags(FLAG_MSAA_4X_HINT); // Enable Multi Sampling Anti Aliasing 4x (if available) SetConfigFlags(FLAG_MSAA_4X_HINT); // Enable Multi Sampling Anti Aliasing 4x (if available)
InitWindow(screenWidth, screenHeight, "raylib [shaders] example - model shader"); InitWindow(screenWidth, screenHeight, "raylib [shaders] example - model shader");
@ -45,16 +45,16 @@ int main()
Model model = LoadModel("resources/models/watermill.obj"); // Load OBJ model Model model = LoadModel("resources/models/watermill.obj"); // Load OBJ model
Texture2D texture = LoadTexture("resources/models/watermill_diffuse.png"); // Load model texture Texture2D texture = LoadTexture("resources/models/watermill_diffuse.png"); // Load model texture
// Load shader for model // Load shader for model
// NOTE: Defining 0 (NULL) for vertex shader forces usage of internal default vertex shader // NOTE: Defining 0 (NULL) for vertex shader forces usage of internal default vertex shader
Shader shader = LoadShader(0, FormatText("resources/shaders/glsl%i/grayscale.fs", GLSL_VERSION)); Shader shader = LoadShader(0, FormatText("resources/shaders/glsl%i/grayscale.fs", GLSL_VERSION));
model.materials[0].shader = shader; // Set shader effect to 3d model model.materials[0].shader = shader; // Set shader effect to 3d model
model.materials[0].maps[MAP_DIFFUSE].texture = texture; // Bind texture to model model.materials[0].maps[MAP_DIFFUSE].texture = texture; // Bind texture to model
Vector3 position = { 0.0f, 0.0f, 0.0f }; // Set model position Vector3 position = { 0.0f, 0.0f, 0.0f }; // Set model position
SetCameraMode(camera, CAMERA_FREE); // Set an orbital camera mode SetCameraMode(camera, CAMERA_FREE); // Set an orbital camera mode
SetTargetFPS(60); // Set our game to run at 60 frames-per-second SetTargetFPS(60); // Set our game to run at 60 frames-per-second
@ -81,11 +81,8 @@ int main()
DrawGrid(10, 1.0f); // Draw a grid DrawGrid(10, 1.0f); // Draw a grid
EndMode3D(); EndMode3D();
DrawText("(c) Watermill 3D model by Alberto Cano", screenWidth - 210, screenHeight - 20, 10, GRAY); DrawText("(c) Watermill 3D model by Alberto Cano", screenWidth - 210, screenHeight - 20, 10, GRAY);
DrawText(FormatText("Camera position: (%.2f, %.2f, %.2f)", camera.position.x, camera.position.y, camera.position.z), 600, 20, 10, BLACK);
DrawText(FormatText("Camera target: (%.2f, %.2f, %.2f)", camera.target.x, camera.target.y, camera.target.z), 600, 40, 10, GRAY);
DrawFPS(10, 10); DrawFPS(10, 10);

View file

@ -69,12 +69,12 @@ static const char *paletteText[] = {
"RKBV (2-strip film)" "RKBV (2-strip film)"
}; };
int main() int main(void)
{ {
// Initialization // Initialization
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
int screenWidth = 800; const int screenWidth = 800;
int screenHeight = 450; const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [shaders] example - color palette switch"); InitWindow(screenWidth, screenHeight, "raylib [shaders] example - color palette switch");
@ -117,7 +117,7 @@ int main()
BeginShaderMode(shader); BeginShaderMode(shader);
for (int i = 0; i < COLORS_PER_PALETTE; i++) for (int i = 0; i < COLORS_PER_PALETTE; i++)
{ {
// Draw horizontal screen-wide rectangles with increasing "palette index" // Draw horizontal screen-wide rectangles with increasing "palette index"
// The used palette index is encoded in the RGB components of the pixel // The used palette index is encoded in the RGB components of the pixel
@ -129,7 +129,7 @@ int main()
DrawText("< >", 10, 10, 30, DARKBLUE); DrawText("< >", 10, 10, 30, DARKBLUE);
DrawText("CURRENT PALETTE:", 60, 15, 20, RAYWHITE); DrawText("CURRENT PALETTE:", 60, 15, 20, RAYWHITE);
DrawText(paletteText[currentPalette], 300, 15, 20, RED); DrawText(paletteText[currentPalette], 300, 15, 20, RED);
DrawFPS(700, 15); DrawFPS(700, 15);
EndDrawing(); EndDrawing();

View file

@ -58,31 +58,31 @@ static const char *postproShaderText[] = {
//"FXAA" //"FXAA"
}; };
int main() int main(void)
{ {
// Initialization // Initialization
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
int screenWidth = 800; const int screenWidth = 800;
int screenHeight = 450; const int screenHeight = 450;
SetConfigFlags(FLAG_MSAA_4X_HINT); // Enable Multi Sampling Anti Aliasing 4x (if available) SetConfigFlags(FLAG_MSAA_4X_HINT); // Enable Multi Sampling Anti Aliasing 4x (if available)
InitWindow(screenWidth, screenHeight, "raylib [shaders] example - postprocessing shader"); InitWindow(screenWidth, screenHeight, "raylib [shaders] example - postprocessing shader");
// Define the camera to look into our 3d world // Define the camera to look into our 3d world
Camera camera = {{ 2.0f, 3.0f, 2.0f }, { 0.0f, 1.0f, 0.0f }, { 0.0f, 1.0f, 0.0f }, 45.0f, 0 }; Camera camera = {{ 2.0f, 3.0f, 2.0f }, { 0.0f, 1.0f, 0.0f }, { 0.0f, 1.0f, 0.0f }, 45.0f, 0 };
Model model = LoadModel("resources/models/church.obj"); // Load OBJ model Model model = LoadModel("resources/models/church.obj"); // Load OBJ model
Texture2D texture = LoadTexture("resources/models/church_diffuse.png"); // Load model texture (diffuse map) Texture2D texture = LoadTexture("resources/models/church_diffuse.png"); // Load model texture (diffuse map)
model.materials[0].maps[MAP_DIFFUSE].texture = texture; // Set model diffuse texture model.materials[0].maps[MAP_DIFFUSE].texture = texture; // Set model diffuse texture
Vector3 position = { 0.0f, 0.0f, 0.0f }; // Set model position Vector3 position = { 0.0f, 0.0f, 0.0f }; // Set model position
// Load all postpro shaders // Load all postpro shaders
// NOTE 1: All postpro shader use the base vertex shader (DEFAULT_VERTEX_SHADER) // NOTE 1: All postpro shader use the base vertex shader (DEFAULT_VERTEX_SHADER)
// NOTE 2: We load the correct shader depending on GLSL version // NOTE 2: We load the correct shader depending on GLSL version
Shader shaders[MAX_POSTPRO_SHADERS]; Shader shaders[MAX_POSTPRO_SHADERS];
// NOTE: Defining 0 (NULL) for vertex shader forces usage of internal default vertex shader // NOTE: Defining 0 (NULL) for vertex shader forces usage of internal default vertex shader
shaders[FX_GRAYSCALE] = LoadShader(0, FormatText("resources/shaders/glsl%i/grayscale.fs", GLSL_VERSION)); shaders[FX_GRAYSCALE] = LoadShader(0, FormatText("resources/shaders/glsl%i/grayscale.fs", GLSL_VERSION));
shaders[FX_POSTERIZATION] = LoadShader(0, FormatText("resources/shaders/glsl%i/posterization.fs", GLSL_VERSION)); shaders[FX_POSTERIZATION] = LoadShader(0, FormatText("resources/shaders/glsl%i/posterization.fs", GLSL_VERSION));
@ -96,12 +96,12 @@ int main()
shaders[FX_SOBEL] = LoadShader(0, FormatText("resources/shaders/glsl%i/sobel.fs", GLSL_VERSION)); shaders[FX_SOBEL] = LoadShader(0, FormatText("resources/shaders/glsl%i/sobel.fs", GLSL_VERSION));
shaders[FX_BLOOM] = LoadShader(0, FormatText("resources/shaders/glsl%i/bloom.fs", GLSL_VERSION)); shaders[FX_BLOOM] = LoadShader(0, FormatText("resources/shaders/glsl%i/bloom.fs", GLSL_VERSION));
shaders[FX_BLUR] = LoadShader(0, FormatText("resources/shaders/glsl%i/blur.fs", GLSL_VERSION)); shaders[FX_BLUR] = LoadShader(0, FormatText("resources/shaders/glsl%i/blur.fs", GLSL_VERSION));
int currentShader = FX_GRAYSCALE; int currentShader = FX_GRAYSCALE;
// Create a RenderTexture2D to be used for render to texture // Create a RenderTexture2D to be used for render to texture
RenderTexture2D target = LoadRenderTexture(screenWidth, screenHeight); RenderTexture2D target = LoadRenderTexture(screenWidth, screenHeight);
// Setup orbital camera // Setup orbital camera
SetCameraMode(camera, CAMERA_ORBITAL); // Set an orbital camera mode SetCameraMode(camera, CAMERA_ORBITAL); // Set an orbital camera mode
@ -114,10 +114,10 @@ int main()
// Update // Update
//---------------------------------------------------------------------------------- //----------------------------------------------------------------------------------
UpdateCamera(&camera); // Update camera UpdateCamera(&camera); // Update camera
if (IsKeyPressed(KEY_RIGHT)) currentShader++; if (IsKeyPressed(KEY_RIGHT)) currentShader++;
else if (IsKeyPressed(KEY_LEFT)) currentShader--; else if (IsKeyPressed(KEY_LEFT)) currentShader--;
if (currentShader >= MAX_POSTPRO_SHADERS) currentShader = 0; if (currentShader >= MAX_POSTPRO_SHADERS) currentShader = 0;
else if (currentShader < 0) currentShader = MAX_POSTPRO_SHADERS - 1; else if (currentShader < 0) currentShader = MAX_POSTPRO_SHADERS - 1;
//---------------------------------------------------------------------------------- //----------------------------------------------------------------------------------
@ -129,7 +129,7 @@ int main()
ClearBackground(RAYWHITE); ClearBackground(RAYWHITE);
BeginTextureMode(target); // Enable drawing to texture BeginTextureMode(target); // Enable drawing to texture
ClearBackground(RAYWHITE); // Clear texture background ClearBackground(RAYWHITE); // Clear texture background
BeginMode3D(camera); // Begin 3d mode drawing BeginMode3D(camera); // Begin 3d mode drawing
@ -139,26 +139,26 @@ int main()
DrawGrid(10, 1.0f); // Draw a grid DrawGrid(10, 1.0f); // Draw a grid
EndMode3D(); // End 3d mode drawing, returns to orthographic 2d mode EndMode3D(); // End 3d mode drawing, returns to orthographic 2d mode
EndTextureMode(); // End drawing to texture (now we have a texture available for next passes) EndTextureMode(); // End drawing to texture (now we have a texture available for next passes)
// Render previously generated texture using selected postpro shader // Render previously generated texture using selected postpro shader
BeginShaderMode(shaders[currentShader]); BeginShaderMode(shaders[currentShader]);
// NOTE: Render texture must be y-flipped due to default OpenGL coordinates (left-bottom) // NOTE: Render texture must be y-flipped due to default OpenGL coordinates (left-bottom)
DrawTextureRec(target.texture, (Rectangle){ 0, 0, target.texture.width, -target.texture.height }, (Vector2){ 0, 0 }, WHITE); DrawTextureRec(target.texture, (Rectangle){ 0, 0, target.texture.width, -target.texture.height }, (Vector2){ 0, 0 }, WHITE);
EndShaderMode(); EndShaderMode();
// Draw 2d shapes and text over drawn texture // Draw 2d shapes and text over drawn texture
DrawRectangle(0, 9, 580, 30, Fade(LIGHTGRAY, 0.7f)); DrawRectangle(0, 9, 580, 30, Fade(LIGHTGRAY, 0.7f));
DrawText("(c) Church 3D model by Alberto Cano", screenWidth - 200, screenHeight - 20, 10, GRAY); DrawText("(c) Church 3D model by Alberto Cano", screenWidth - 200, screenHeight - 20, 10, GRAY);
DrawText("CURRENT POSTPRO SHADER:", 10, 15, 20, BLACK); DrawText("CURRENT POSTPRO SHADER:", 10, 15, 20, BLACK);
DrawText(postproShaderText[currentShader], 330, 15, 20, RED); DrawText(postproShaderText[currentShader], 330, 15, 20, RED);
DrawText("< >", 540, 10, 30, DARKBLUE); DrawText("< >", 540, 10, 30, DARKBLUE);
DrawFPS(700, 15); DrawFPS(700, 15);
EndDrawing(); EndDrawing();
@ -167,10 +167,10 @@ int main()
// De-Initialization // De-Initialization
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
// Unload all postpro shaders // Unload all postpro shaders
for (int i = 0; i < MAX_POSTPRO_SHADERS; i++) UnloadShader(shaders[i]); for (int i = 0; i < MAX_POSTPRO_SHADERS; i++) UnloadShader(shaders[i]);
UnloadTexture(texture); // Unload texture UnloadTexture(texture); // Unload texture
UnloadModel(model); // Unload model UnloadModel(model); // Unload model
UnloadRenderTexture(target); // Unload render texture UnloadRenderTexture(target); // Unload render texture

View file

@ -24,13 +24,13 @@
#define GLSL_VERSION 100 #define GLSL_VERSION 100
#endif #endif
int main() int main(void)
{ {
// Initialization // Initialization
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
int screenWidth = 800; const int screenWidth = 800;
int screenHeight = 450; const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [shaders] example - raymarching shapes"); InitWindow(screenWidth, screenHeight, "raylib [shaders] example - raymarching shapes");
Camera camera = { 0 }; Camera camera = { 0 };
@ -44,7 +44,7 @@ int main()
// Load raymarching shader // Load raymarching shader
// NOTE: Defining 0 (NULL) for vertex shader forces usage of internal default vertex shader // NOTE: Defining 0 (NULL) for vertex shader forces usage of internal default vertex shader
Shader shader = LoadShader(0, FormatText("resources/shaders/glsl%i/raymarching.fs", GLSL_VERSION)); Shader shader = LoadShader(0, FormatText("resources/shaders/glsl%i/raymarching.fs", GLSL_VERSION));
// 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");
@ -72,7 +72,7 @@ int main()
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 cameraUp[3] = { camera.up.x, camera.up.y, camera.up.z };
float deltaTime = GetFrameTime(); float deltaTime = GetFrameTime();
runTime += deltaTime; runTime += deltaTime;
// Set shader required uniform values // Set shader required uniform values

View file

@ -24,23 +24,23 @@
#define GLSL_VERSION 100 #define GLSL_VERSION 100
#endif #endif
int main() int main(void)
{ {
// Initialization // Initialization
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
int screenWidth = 800; const int screenWidth = 800;
int screenHeight = 450; const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [shaders] example - shapes and texture shaders"); InitWindow(screenWidth, screenHeight, "raylib [shaders] example - shapes and texture shaders");
Texture2D fudesumi = LoadTexture("resources/fudesumi.png"); Texture2D fudesumi = LoadTexture("resources/fudesumi.png");
// Load shader to be used on some parts drawing // Load shader to be used on some parts drawing
// NOTE 1: Using GLSL 330 shader version, on OpenGL ES 2.0 use GLSL 100 shader version // NOTE 1: Using GLSL 330 shader version, on OpenGL ES 2.0 use GLSL 100 shader version
// NOTE 2: Defining 0 (NULL) for vertex shader forces usage of internal default vertex shader // NOTE 2: Defining 0 (NULL) for vertex shader forces usage of internal default vertex shader
Shader shader = LoadShader(0, FormatText("resources/shaders/glsl%i/grayscale.fs", GLSL_VERSION)); Shader shader = LoadShader(0, FormatText("resources/shaders/glsl%i/grayscale.fs", GLSL_VERSION));
SetTargetFPS(60); SetTargetFPS(60); // Set our game to run at 60 frames-per-second
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
// Main game loop // Main game loop
@ -56,19 +56,19 @@ int main()
BeginDrawing(); BeginDrawing();
ClearBackground(RAYWHITE); ClearBackground(RAYWHITE);
// Start drawing with default shader // Start drawing with default shader
DrawText("USING DEFAULT SHADER", 20, 40, 10, RED); DrawText("USING DEFAULT SHADER", 20, 40, 10, RED);
DrawCircle(80, 120, 35, DARKBLUE); DrawCircle(80, 120, 35, DARKBLUE);
DrawCircleGradient(80, 220, 60, GREEN, SKYBLUE); DrawCircleGradient(80, 220, 60, GREEN, SKYBLUE);
DrawCircleLines(80, 340, 80, DARKBLUE); DrawCircleLines(80, 340, 80, DARKBLUE);
// Activate our custom shader to be applied on next shapes/textures drawings // Activate our custom shader to be applied on next shapes/textures drawings
BeginShaderMode(shader); BeginShaderMode(shader);
DrawText("USING CUSTOM SHADER", 190, 40, 10, RED); DrawText("USING CUSTOM SHADER", 190, 40, 10, RED);
DrawRectangle(250 - 60, 90, 120, 60, RED); DrawRectangle(250 - 60, 90, 120, 60, RED);
@ -77,29 +77,29 @@ int main()
// Activate our default shader for next drawings // Activate our default shader for next drawings
EndShaderMode(); EndShaderMode();
DrawText("USING DEFAULT SHADER", 370, 40, 10, RED); DrawText("USING DEFAULT SHADER", 370, 40, 10, RED);
DrawTriangle((Vector2){430, 80}, DrawTriangle((Vector2){430, 80},
(Vector2){430 - 60, 150}, (Vector2){430 - 60, 150},
(Vector2){430 + 60, 150}, VIOLET); (Vector2){430 + 60, 150}, VIOLET);
DrawTriangleLines((Vector2){430, 160}, DrawTriangleLines((Vector2){430, 160},
(Vector2){430 - 20, 230}, (Vector2){430 - 20, 230},
(Vector2){430 + 20, 230}, DARKBLUE); (Vector2){430 + 20, 230}, DARKBLUE);
DrawPoly((Vector2){430, 320}, 6, 80, 0, BROWN); DrawPoly((Vector2){430, 320}, 6, 80, 0, BROWN);
// Activate our custom shader to be applied on next shapes/textures drawings // Activate our custom shader to be applied on next shapes/textures drawings
BeginShaderMode(shader); BeginShaderMode(shader);
DrawTexture(fudesumi, 500, -30, WHITE); // Using custom shader DrawTexture(fudesumi, 500, -30, WHITE); // Using custom shader
// Activate our default shader for next drawings // Activate our default shader for next drawings
EndShaderMode(); EndShaderMode();
DrawText("(c) Fudesumi sprite by Eiden Marsal", 380, screenHeight - 20, 10, GRAY); DrawText("(c) Fudesumi sprite by Eiden Marsal", 380, screenHeight - 20, 10, GRAY);
EndDrawing(); EndDrawing();
//---------------------------------------------------------------------------------- //----------------------------------------------------------------------------------
} }
@ -108,7 +108,7 @@ int main()
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
UnloadShader(shader); // Unload shader UnloadShader(shader); // Unload shader
UnloadTexture(fudesumi); // Unload texture UnloadTexture(fudesumi); // Unload texture
CloseWindow(); // Close window and OpenGL context CloseWindow(); // Close window and OpenGL context
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------

View file

@ -21,12 +21,12 @@
#define GLSL_VERSION 100 #define GLSL_VERSION 100
#endif #endif
int main() int main(void)
{ {
// Initialization // Initialization
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
int screenWidth = 800; const int screenWidth = 800;
int screenHeight = 450; const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [shaders] example - texture drawing"); InitWindow(screenWidth, screenHeight, "raylib [shaders] example - texture drawing");
@ -41,17 +41,18 @@ int main()
int timeLoc = GetShaderLocation(shader, "uTime"); int timeLoc = GetShaderLocation(shader, "uTime");
SetShaderValue(shader, timeLoc, &time, UNIFORM_FLOAT); SetShaderValue(shader, timeLoc, &time, UNIFORM_FLOAT);
SetTargetFPS(60); SetTargetFPS(60); // Set our game to run at 60 frames-per-second
//-------------------------------------------------------------------------------------- // -------------------------------------------------------------------------------------------------------------
while (!WindowShouldClose()) // Main game loop
while (!WindowShouldClose()) // Detect window close button or ESC key
{ {
// Update // Update
//---------------------------------------------------------------------------------- //----------------------------------------------------------------------------------
time = GetTime(); time = GetTime();
SetShaderValue(shader, timeLoc, &time, UNIFORM_FLOAT); SetShaderValue(shader, timeLoc, &time, UNIFORM_FLOAT);
//---------------------------------------------------------------------------------- //----------------------------------------------------------------------------------
// Draw // Draw
//---------------------------------------------------------------------------------- //----------------------------------------------------------------------------------
BeginDrawing(); BeginDrawing();
@ -61,13 +62,13 @@ int main()
BeginShaderMode(shader); // Enable our custom shader for next shapes/textures drawings BeginShaderMode(shader); // Enable our custom shader for next shapes/textures drawings
DrawTexture(texture, 0, 0, WHITE); // Drawing BLANK texture, all magic happens on shader DrawTexture(texture, 0, 0, WHITE); // Drawing BLANK texture, all magic happens on shader
EndShaderMode(); // Disable our custom shader, return to default shader EndShaderMode(); // Disable our custom shader, return to default shader
DrawText("BACKGROUND is PAINTED and ANIMATED on SHADER!", 10, 10, 20, MAROON); DrawText("BACKGROUND is PAINTED and ANIMATED on SHADER!", 10, 10, 20, MAROON);
EndDrawing(); EndDrawing();
//---------------------------------------------------------------------------------- //----------------------------------------------------------------------------------
} }
// De-Initialization // De-Initialization
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
UnloadShader(shader); UnloadShader(shader);

View file

@ -26,10 +26,7 @@
#define GLSL_VERSION 100 #define GLSL_VERSION 100
#endif #endif
// ------------------------------------------------------------------------------------------------------------- int main(void)
// Main Entry point
// -------------------------------------------------------------------------------------------------------------
int main()
{ {
// Initialization // Initialization
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
@ -69,13 +66,13 @@ int main()
SetShaderValue(shader, speedXLoc, &speedX, UNIFORM_FLOAT); SetShaderValue(shader, speedXLoc, &speedX, UNIFORM_FLOAT);
SetShaderValue(shader, speedYLoc, &speedY, UNIFORM_FLOAT); SetShaderValue(shader, speedYLoc, &speedY, UNIFORM_FLOAT);
float seconds = 0.0f; float seconds = 0.0f;
SetTargetFPS(60); SetTargetFPS(60); // Set our game to run at 60 frames-per-second
// ------------------------------------------------------------------------------------------------------------- // -------------------------------------------------------------------------------------------------------------
// Main game loop // Main game loop
while (!WindowShouldClose()) // Detect window close button or ESC key while (!WindowShouldClose()) // Detect window close button or ESC key
{ {
// Update // Update
//---------------------------------------------------------------------------------- //----------------------------------------------------------------------------------
@ -86,9 +83,9 @@ int main()
// Draw // Draw
//---------------------------------------------------------------------------------- //----------------------------------------------------------------------------------
BeginDrawing(); BeginDrawing();
ClearBackground(RAYWHITE); ClearBackground(RAYWHITE);
BeginShaderMode(shader); BeginShaderMode(shader);
@ -97,7 +94,7 @@ int main()
EndShaderMode(); EndShaderMode();
EndDrawing(); EndDrawing();
//---------------------------------------------------------------------------------- //----------------------------------------------------------------------------------
} }
@ -109,5 +106,5 @@ int main()
CloseWindow(); // Close window and OpenGL context CloseWindow(); // Close window and OpenGL context
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
return 0; return 0;
} }

View file

@ -11,16 +11,16 @@
#include "raylib.h" #include "raylib.h"
int main() int main(void)
{ {
// Initialization // Initialization
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
int screenWidth = 800; const int screenWidth = 800;
int screenHeight = 450; const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [shapes] example - basic shapes drawing"); InitWindow(screenWidth, screenHeight, "raylib [shapes] example - basic shapes drawing");
SetTargetFPS(60); SetTargetFPS(60); // Set our game to run at 60 frames-per-second
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
// Main game loop // Main game loop

View file

@ -11,58 +11,58 @@
#include "raylib.h" #include "raylib.h"
int main() int main(void)
{ {
// Initialization // Initialization
//--------------------------------------------------------- //---------------------------------------------------------
const int screenWidth = 800; const int screenWidth = 800;
const int screenHeight = 450; const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [shapes] example - bouncing ball"); InitWindow(screenWidth, screenHeight, "raylib [shapes] example - bouncing ball");
Vector2 ballPosition = { GetScreenWidth()/2, GetScreenHeight()/2 }; Vector2 ballPosition = { GetScreenWidth()/2, GetScreenHeight()/2 };
Vector2 ballSpeed = { 5.0f, 4.0f }; Vector2 ballSpeed = { 5.0f, 4.0f };
int ballRadius = 20; int ballRadius = 20;
bool pause = 0; bool pause = 0;
int framesCounter = 0; int framesCounter = 0;
SetTargetFPS(60); SetTargetFPS(60); // Set our game to run at 60 frames-per-second
//---------------------------------------------------------- //----------------------------------------------------------
// Main game loop // Main game loop
while (!WindowShouldClose()) // Detect window close button or ESC key while (!WindowShouldClose()) // Detect window close button or ESC key
{ {
// Update // Update
//----------------------------------------------------- //-----------------------------------------------------
if (IsKeyPressed(KEY_SPACE)) pause = !pause; if (IsKeyPressed(KEY_SPACE)) pause = !pause;
if (!pause) if (!pause)
{ {
ballPosition.x += ballSpeed.x; ballPosition.x += ballSpeed.x;
ballPosition.y += ballSpeed.y; ballPosition.y += ballSpeed.y;
// Check walls collision for bouncing // Check walls collision for bouncing
if ((ballPosition.x >= (GetScreenWidth() - ballRadius)) || (ballPosition.x <= ballRadius)) ballSpeed.x *= -1.0f; if ((ballPosition.x >= (GetScreenWidth() - ballRadius)) || (ballPosition.x <= ballRadius)) ballSpeed.x *= -1.0f;
if ((ballPosition.y >= (GetScreenHeight() - ballRadius)) || (ballPosition.y <= ballRadius)) ballSpeed.y *= -1.0f; if ((ballPosition.y >= (GetScreenHeight() - ballRadius)) || (ballPosition.y <= ballRadius)) ballSpeed.y *= -1.0f;
} }
else framesCounter++; else framesCounter++;
//----------------------------------------------------- //-----------------------------------------------------
// Draw // Draw
//----------------------------------------------------- //-----------------------------------------------------
BeginDrawing(); BeginDrawing();
ClearBackground(RAYWHITE); ClearBackground(RAYWHITE);
DrawCircleV(ballPosition, ballRadius, MAROON); DrawCircleV(ballPosition, ballRadius, MAROON);
DrawText("PRESS SPACE to PAUSE BALL MOVEMENT", 10, GetScreenHeight() - 25, 20, LIGHTGRAY); DrawText("PRESS SPACE to PAUSE BALL MOVEMENT", 10, GetScreenHeight() - 25, 20, LIGHTGRAY);
// On pause, we draw a blinking message // On pause, we draw a blinking message
if (pause && ((framesCounter/30)%2)) DrawText("PAUSED", 350, 200, 30, GRAY); if (pause && ((framesCounter/30)%2)) DrawText("PAUSED", 350, 200, 30, GRAY);
DrawFPS(10, 10); DrawFPS(10, 10);
EndDrawing(); EndDrawing();
//----------------------------------------------------- //-----------------------------------------------------
} }
@ -71,6 +71,6 @@ int main()
//--------------------------------------------------------- //---------------------------------------------------------
CloseWindow(); // Close window and OpenGL context CloseWindow(); // Close window and OpenGL context
//---------------------------------------------------------- //----------------------------------------------------------
return 0; return 0;
} }

View file

@ -12,89 +12,89 @@
#include "raylib.h" #include "raylib.h"
#include <stdlib.h> // Required for abs() #include <stdlib.h> // Required for abs()
int main() int main(void)
{ {
// Initialization // Initialization
//--------------------------------------------------------- //---------------------------------------------------------
int screenWidth = 800; const int screenWidth = 800;
int screenHeight = 450; const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [shapes] example - collision area"); InitWindow(screenWidth, screenHeight, "raylib [shapes] example - collision area");
// Box A: Moving box // Box A: Moving box
Rectangle boxA = { 10, GetScreenHeight()/2 - 50, 200, 100 }; Rectangle boxA = { 10, GetScreenHeight()/2 - 50, 200, 100 };
int boxASpeedX = 4; int boxASpeedX = 4;
// Box B: Mouse moved box // Box B: Mouse moved box
Rectangle boxB = { GetScreenWidth()/2 - 30, GetScreenHeight()/2 - 30, 60, 60 }; Rectangle boxB = { GetScreenWidth()/2 - 30, GetScreenHeight()/2 - 30, 60, 60 };
Rectangle boxCollision = { 0 }; // Collision rectangle Rectangle boxCollision = { 0 }; // Collision rectangle
int screenUpperLimit = 40; // Top menu limits int screenUpperLimit = 40; // Top menu limits
bool pause = false; // Movement pause bool pause = false; // Movement pause
bool collision = false; // Collision detection bool collision = false; // Collision detection
SetTargetFPS(60); SetTargetFPS(60); // Set our game to run at 60 frames-per-second
//---------------------------------------------------------- //----------------------------------------------------------
// Main game loop // Main game loop
while (!WindowShouldClose()) // Detect window close button or ESC key while (!WindowShouldClose()) // Detect window close button or ESC key
{ {
// Update // Update
//----------------------------------------------------- //-----------------------------------------------------
// Move box if not paused // Move box if not paused
if (!pause) boxA.x += boxASpeedX; if (!pause) boxA.x += boxASpeedX;
// Bounce box on x screen limits // Bounce box on x screen limits
if (((boxA.x + boxA.width) >= GetScreenWidth()) || (boxA.x <= 0)) boxASpeedX *= -1; if (((boxA.x + boxA.width) >= GetScreenWidth()) || (boxA.x <= 0)) boxASpeedX *= -1;
// Update player-controlled-box (box02) // Update player-controlled-box (box02)
boxB.x = GetMouseX() - boxB.width/2; boxB.x = GetMouseX() - boxB.width/2;
boxB.y = GetMouseY() - boxB.height/2; boxB.y = GetMouseY() - boxB.height/2;
// Make sure Box B does not go out of move area limits // Make sure Box B does not go out of move area limits
if ((boxB.x + boxB.width) >= GetScreenWidth()) boxB.x = GetScreenWidth() - boxB.width; if ((boxB.x + boxB.width) >= GetScreenWidth()) boxB.x = GetScreenWidth() - boxB.width;
else if (boxB.x <= 0) boxB.x = 0; else if (boxB.x <= 0) boxB.x = 0;
if ((boxB.y + boxB.height) >= GetScreenHeight()) boxB.y = GetScreenHeight() - boxB.height; if ((boxB.y + boxB.height) >= GetScreenHeight()) boxB.y = GetScreenHeight() - boxB.height;
else if (boxB.y <= screenUpperLimit) boxB.y = screenUpperLimit; else if (boxB.y <= screenUpperLimit) boxB.y = screenUpperLimit;
// Check boxes collision // Check boxes collision
collision = CheckCollisionRecs(boxA, boxB); collision = CheckCollisionRecs(boxA, boxB);
// Get collision rectangle (only on collision) // Get collision rectangle (only on collision)
if (collision) boxCollision = GetCollisionRec(boxA, boxB); if (collision) boxCollision = GetCollisionRec(boxA, boxB);
// Pause Box A movement // Pause Box A movement
if (IsKeyPressed(KEY_SPACE)) pause = !pause; if (IsKeyPressed(KEY_SPACE)) pause = !pause;
//----------------------------------------------------- //-----------------------------------------------------
// Draw // Draw
//----------------------------------------------------- //-----------------------------------------------------
BeginDrawing(); BeginDrawing();
ClearBackground(RAYWHITE); ClearBackground(RAYWHITE);
DrawRectangle(0, 0, screenWidth, screenUpperLimit, collision? RED : BLACK); DrawRectangle(0, 0, screenWidth, screenUpperLimit, collision? RED : BLACK);
DrawRectangleRec(boxA, GOLD); DrawRectangleRec(boxA, GOLD);
DrawRectangleRec(boxB, BLUE); DrawRectangleRec(boxB, BLUE);
if (collision) if (collision)
{ {
// Draw collision area // Draw collision area
DrawRectangleRec(boxCollision, LIME); DrawRectangleRec(boxCollision, LIME);
// Draw collision message // Draw collision message
DrawText("COLLISION!", GetScreenWidth()/2 - MeasureText("COLLISION!", 20)/2, screenUpperLimit/2 - 10, 20, BLACK); DrawText("COLLISION!", GetScreenWidth()/2 - MeasureText("COLLISION!", 20)/2, screenUpperLimit/2 - 10, 20, BLACK);
// Draw collision area // Draw collision area
DrawText(FormatText("Collision Area: %i", (int)boxCollision.width*(int)boxCollision.height), GetScreenWidth()/2 - 100, screenUpperLimit + 10, 20, BLACK); DrawText(FormatText("Collision Area: %i", (int)boxCollision.width*(int)boxCollision.height), GetScreenWidth()/2 - 100, screenUpperLimit + 10, 20, BLACK);
} }
DrawFPS(10, 10); DrawFPS(10, 10);
EndDrawing(); EndDrawing();
//----------------------------------------------------- //-----------------------------------------------------
} }
@ -103,6 +103,6 @@ int main()
//--------------------------------------------------------- //---------------------------------------------------------
CloseWindow(); // Close window and OpenGL context CloseWindow(); // Close window and OpenGL context
//---------------------------------------------------------- //----------------------------------------------------------
return 0; return 0;
} }

View file

@ -13,7 +13,7 @@
#define MAX_COLORS_COUNT 21 // Number of colors available #define MAX_COLORS_COUNT 21 // Number of colors available
int main() int main(void)
{ {
// Initialization // Initialization
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
@ -22,14 +22,14 @@ int main()
InitWindow(screenWidth, screenHeight, "raylib [shapes] example - colors palette"); InitWindow(screenWidth, screenHeight, "raylib [shapes] example - colors palette");
Color colors[MAX_COLORS_COUNT] = { Color colors[MAX_COLORS_COUNT] = {
DARKGRAY, MAROON, ORANGE, DARKGREEN, DARKBLUE, DARKPURPLE, DARKBROWN, DARKGRAY, MAROON, ORANGE, DARKGREEN, DARKBLUE, DARKPURPLE, DARKBROWN,
GRAY, RED, GOLD, LIME, BLUE, VIOLET, BROWN, LIGHTGRAY, PINK, YELLOW, GRAY, RED, GOLD, LIME, BLUE, VIOLET, BROWN, LIGHTGRAY, PINK, YELLOW,
GREEN, SKYBLUE, PURPLE, BEIGE }; GREEN, SKYBLUE, PURPLE, BEIGE };
const char *colorNames[MAX_COLORS_COUNT] = { const char *colorNames[MAX_COLORS_COUNT] = {
"DARKGRAY", "MAROON", "ORANGE", "DARKGREEN", "DARKBLUE", "DARKPURPLE", "DARKGRAY", "MAROON", "ORANGE", "DARKGREEN", "DARKBLUE", "DARKPURPLE",
"DARKBROWN", "GRAY", "RED", "GOLD", "LIME", "BLUE", "VIOLET", "BROWN", "DARKBROWN", "GRAY", "RED", "GOLD", "LIME", "BLUE", "VIOLET", "BROWN",
"LIGHTGRAY", "PINK", "YELLOW", "GREEN", "SKYBLUE", "PURPLE", "BEIGE" }; "LIGHTGRAY", "PINK", "YELLOW", "GREEN", "SKYBLUE", "PURPLE", "BEIGE" };
Rectangle colorsRecs[MAX_COLORS_COUNT] = { 0 }; // Rectangles array Rectangle colorsRecs[MAX_COLORS_COUNT] = { 0 }; // Rectangles array
@ -69,19 +69,19 @@ int main()
BeginDrawing(); BeginDrawing();
ClearBackground(RAYWHITE); ClearBackground(RAYWHITE);
DrawText("raylib colors palette", 28, 42, 20, BLACK); DrawText("raylib colors palette", 28, 42, 20, BLACK);
DrawText("press SPACE to see all colors", GetScreenWidth() - 180, GetScreenHeight() - 40, 10, GRAY); DrawText("press SPACE to see all colors", GetScreenWidth() - 180, GetScreenHeight() - 40, 10, GRAY);
for (int i = 0; i < MAX_COLORS_COUNT; i++) // Draw all rectangles for (int i = 0; i < MAX_COLORS_COUNT; i++) // Draw all rectangles
{ {
DrawRectangleRec(colorsRecs[i], Fade(colors[i], colorState[i]? 0.6f : 1.0f)); DrawRectangleRec(colorsRecs[i], Fade(colors[i], colorState[i]? 0.6f : 1.0f));
if (IsKeyDown(KEY_SPACE) || colorState[i]) if (IsKeyDown(KEY_SPACE) || colorState[i])
{ {
DrawRectangle(colorsRecs[i].x, colorsRecs[i].y + colorsRecs[i].height - 26, colorsRecs[i].width, 20, BLACK); DrawRectangle(colorsRecs[i].x, colorsRecs[i].y + colorsRecs[i].height - 26, colorsRecs[i].width, 20, BLACK);
DrawRectangleLinesEx(colorsRecs[i], 6, Fade(BLACK, 0.3f)); DrawRectangleLinesEx(colorsRecs[i], 6, Fade(BLACK, 0.3f));
DrawText(colorNames[i], colorsRecs[i].x + colorsRecs[i].width - MeasureText(colorNames[i], 10) - 12, DrawText(colorNames[i], colorsRecs[i].x + colorsRecs[i].width - MeasureText(colorNames[i], 10) - 12,
colorsRecs[i].y + colorsRecs[i].height - 20, 10, colors[i]); colorsRecs[i].y + colorsRecs[i].height - 20, 10, colors[i]);
} }
} }

View file

@ -16,7 +16,7 @@
#define RAYGUI_IMPLEMENTATION #define RAYGUI_IMPLEMENTATION
#include "raygui.h" // Required for GUI controls #include "raygui.h" // Required for GUI controls
int main() int main(void)
{ {
// Initialization // Initialization
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
@ -32,7 +32,7 @@ int main()
int endAngle = 180; int endAngle = 180;
int segments = 0; int segments = 0;
SetTargetFPS(60); SetTargetFPS(60); // Set our game to run at 60 frames-per-second
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
// Main game loop // Main game loop

View file

@ -30,12 +30,12 @@ int main(void)
int height = 100; int height = 100;
int segments = 0; int segments = 0;
int lineThick = 1; int lineThick = 1;
bool drawRect = false; bool drawRect = false;
bool drawRoundedRect = true; bool drawRoundedRect = true;
bool drawRoundedLines = false; bool drawRoundedLines = false;
SetTargetFPS(60); SetTargetFPS(60); // Set our game to run at 60 frames-per-second
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
// Main game loop // Main game loop
@ -45,20 +45,20 @@ int main(void)
//---------------------------------------------------------------------------------- //----------------------------------------------------------------------------------
Rectangle rec = { (GetScreenWidth() - width - 250)/2, (GetScreenHeight() - height)/2, width, height }; Rectangle rec = { (GetScreenWidth() - width - 250)/2, (GetScreenHeight() - height)/2, width, height };
//---------------------------------------------------------------------------------- //----------------------------------------------------------------------------------
// Draw // Draw
//---------------------------------------------------------------------------------- //----------------------------------------------------------------------------------
BeginDrawing(); BeginDrawing();
ClearBackground(RAYWHITE); ClearBackground(RAYWHITE);
DrawLine(560, 0, 560, GetScreenHeight(), Fade(LIGHTGRAY, 0.6f)); DrawLine(560, 0, 560, GetScreenHeight(), Fade(LIGHTGRAY, 0.6f));
DrawRectangle(560, 0, GetScreenWidth() - 500, GetScreenHeight(), Fade(LIGHTGRAY, 0.3f)); DrawRectangle(560, 0, GetScreenWidth() - 500, GetScreenHeight(), Fade(LIGHTGRAY, 0.3f));
if (drawRect) DrawRectangleRec(rec, Fade(GOLD, 0.6)); if (drawRect) DrawRectangleRec(rec, Fade(GOLD, 0.6));
if (drawRoundedRect) DrawRectangleRounded(rec, roundness, segments, Fade(MAROON, 0.2)); if (drawRoundedRect) DrawRectangleRounded(rec, roundness, segments, Fade(MAROON, 0.2));
if (drawRoundedLines) DrawRectangleRoundedLines(rec,roundness, segments, lineThick, Fade(MAROON, 0.4)); if (drawRoundedLines) DrawRectangleRoundedLines(rec,roundness, segments, lineThick, Fade(MAROON, 0.4));
// Draw GUI controls // Draw GUI controls
//------------------------------------------------------------------------------ //------------------------------------------------------------------------------
width = GuiSliderBar((Rectangle){ 640, 40, 105, 20 }, "Width", width, 0, GetScreenWidth() - 300, true ); width = GuiSliderBar((Rectangle){ 640, 40, 105, 20 }, "Width", width, 0, GetScreenWidth() - 300, true );
@ -66,22 +66,22 @@ int main(void)
roundness = GuiSliderBar((Rectangle){ 640, 140, 105, 20 }, "Roundness", roundness, 0.0f, 1.0f, true); roundness = GuiSliderBar((Rectangle){ 640, 140, 105, 20 }, "Roundness", roundness, 0.0f, 1.0f, true);
lineThick = GuiSliderBar((Rectangle){ 640, 170, 105, 20 }, "Thickness", lineThick, 0, 20, true); lineThick = GuiSliderBar((Rectangle){ 640, 170, 105, 20 }, "Thickness", lineThick, 0, 20, true);
segments = GuiSliderBar((Rectangle){ 640, 240, 105, 20}, "Segments", segments, 0, 60, true); segments = GuiSliderBar((Rectangle){ 640, 240, 105, 20}, "Segments", segments, 0, 60, true);
drawRoundedRect = GuiCheckBox((Rectangle){ 640, 320, 20, 20 }, "DrawRoundedRect", drawRoundedRect); drawRoundedRect = GuiCheckBox((Rectangle){ 640, 320, 20, 20 }, "DrawRoundedRect", drawRoundedRect);
drawRoundedLines = GuiCheckBox((Rectangle){ 640, 350, 20, 20 }, "DrawRoundedLines", drawRoundedLines); drawRoundedLines = GuiCheckBox((Rectangle){ 640, 350, 20, 20 }, "DrawRoundedLines", drawRoundedLines);
drawRect = GuiCheckBox((Rectangle){ 640, 380, 20, 20}, "DrawRect", drawRect); drawRect = GuiCheckBox((Rectangle){ 640, 380, 20, 20}, "DrawRect", drawRect);
//------------------------------------------------------------------------------ //------------------------------------------------------------------------------
DrawText(FormatText("MODE: %s", (segments >= 4)? "MANUAL" : "AUTO"), 640, 280, 10, (segments >= 4)? MAROON : DARKGRAY); DrawText(FormatText("MODE: %s", (segments >= 4)? "MANUAL" : "AUTO"), 640, 280, 10, (segments >= 4)? MAROON : DARKGRAY);
DrawFPS(10, 10); DrawFPS(10, 10);
EndDrawing(); EndDrawing();
//---------------------------------------------------------------------------------- //----------------------------------------------------------------------------------
} }
// De-Initialization // De-Initialization
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
CloseWindow(); // Close window and OpenGL context CloseWindow(); // Close window and OpenGL context
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------

View file

@ -16,7 +16,7 @@
#define RAYGUI_IMPLEMENTATION #define RAYGUI_IMPLEMENTATION
#include "raygui.h" // Required for GUI controls #include "raygui.h" // Required for GUI controls
int main() int main(void)
{ {
// Initialization // Initialization
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
@ -29,16 +29,16 @@ int main()
float innerRadius = 80.0f; float innerRadius = 80.0f;
float outerRadius = 190.0f; float outerRadius = 190.0f;
int startAngle = 0; int startAngle = 0;
int endAngle = 360; int endAngle = 360;
int segments = 0; int segments = 0;
bool drawRing = true; bool drawRing = true;
bool drawRingLines = false; bool drawRingLines = false;
bool drawCircleLines = false; bool drawCircleLines = false;
SetTargetFPS(60); SetTargetFPS(60); // Set our game to run at 60 frames-per-second
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
// Main game loop // Main game loop
@ -48,13 +48,13 @@ int main()
//---------------------------------------------------------------------------------- //----------------------------------------------------------------------------------
// NOTE: All variables update happens inside GUI control functions // NOTE: All variables update happens inside GUI control functions
//---------------------------------------------------------------------------------- //----------------------------------------------------------------------------------
// Draw // Draw
//---------------------------------------------------------------------------------- //----------------------------------------------------------------------------------
BeginDrawing(); BeginDrawing();
ClearBackground(RAYWHITE); ClearBackground(RAYWHITE);
DrawLine(500, 0, 500, GetScreenHeight(), Fade(LIGHTGRAY, 0.6f)); DrawLine(500, 0, 500, GetScreenHeight(), Fade(LIGHTGRAY, 0.6f));
DrawRectangle(500, 0, GetScreenWidth() - 500, GetScreenHeight(), Fade(LIGHTGRAY, 0.3f)); DrawRectangle(500, 0, GetScreenWidth() - 500, GetScreenHeight(), Fade(LIGHTGRAY, 0.3f));
@ -66,27 +66,27 @@ int main()
//------------------------------------------------------------------------------ //------------------------------------------------------------------------------
startAngle = GuiSliderBar((Rectangle){ 600, 40, 120, 20 }, "StartAngle", startAngle, -450, 450, true); startAngle = GuiSliderBar((Rectangle){ 600, 40, 120, 20 }, "StartAngle", startAngle, -450, 450, true);
endAngle = GuiSliderBar((Rectangle){ 600, 70, 120, 20 }, "EndAngle", endAngle, -450, 450, true); endAngle = GuiSliderBar((Rectangle){ 600, 70, 120, 20 }, "EndAngle", endAngle, -450, 450, true);
innerRadius = GuiSliderBar((Rectangle){ 600, 140, 120, 20 }, "InnerRadius", innerRadius, 0, 100, true); innerRadius = GuiSliderBar((Rectangle){ 600, 140, 120, 20 }, "InnerRadius", innerRadius, 0, 100, true);
outerRadius = GuiSliderBar((Rectangle){ 600, 170, 120, 20 }, "OuterRadius", outerRadius, 0, 200, true); outerRadius = GuiSliderBar((Rectangle){ 600, 170, 120, 20 }, "OuterRadius", outerRadius, 0, 200, true);
segments = GuiSliderBar((Rectangle){ 600, 240, 120, 20 }, "Segments", segments, 0, 100, true); segments = GuiSliderBar((Rectangle){ 600, 240, 120, 20 }, "Segments", segments, 0, 100, true);
drawRing = GuiCheckBox((Rectangle){ 600, 320, 20, 20 }, "Draw Ring", drawRing); drawRing = GuiCheckBox((Rectangle){ 600, 320, 20, 20 }, "Draw Ring", drawRing);
drawRingLines = GuiCheckBox((Rectangle){ 600, 350, 20, 20 }, "Draw RingLines", drawRingLines); drawRingLines = GuiCheckBox((Rectangle){ 600, 350, 20, 20 }, "Draw RingLines", drawRingLines);
drawCircleLines = GuiCheckBox((Rectangle){ 600, 380, 20, 20 }, "Draw CircleLines", drawCircleLines); drawCircleLines = GuiCheckBox((Rectangle){ 600, 380, 20, 20 }, "Draw CircleLines", drawCircleLines);
//------------------------------------------------------------------------------ //------------------------------------------------------------------------------
DrawText(FormatText("MODE: %s", (segments >= 4)? "MANUAL" : "AUTO"), 600, 270, 10, (segments >= 4)? MAROON : DARKGRAY); DrawText(FormatText("MODE: %s", (segments >= 4)? "MANUAL" : "AUTO"), 600, 270, 10, (segments >= 4)? MAROON : DARKGRAY);
DrawFPS(10, 10); DrawFPS(10, 10);
EndDrawing(); EndDrawing();
//---------------------------------------------------------------------------------- //----------------------------------------------------------------------------------
} }
// De-Initialization // De-Initialization
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
CloseWindow(); // Close window and OpenGL context CloseWindow(); // Close window and OpenGL context
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------

View file

@ -11,9 +11,9 @@
#include "raylib.h" #include "raylib.h"
#include "easings.h" // Required for easing functions #include "easings.h" // Required for easing functions
int main() int main(void)
{ {
// Initialization // Initialization
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
@ -21,16 +21,16 @@ int main()
const int screenHeight = 450; const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [shapes] example - easings ball anim"); InitWindow(screenWidth, screenHeight, "raylib [shapes] example - easings ball anim");
// Ball variable value to be animated with easings // Ball variable value to be animated with easings
int ballPositionX = -100; int ballPositionX = -100;
int ballRadius = 20; int ballRadius = 20;
float ballAlpha = 0.0f; float ballAlpha = 0.0f;
int state = 0; int state = 0;
int framesCounter = 0; int framesCounter = 0;
SetTargetFPS(60); SetTargetFPS(60); // Set our game to run at 60 frames-per-second
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
// Main game loop // Main game loop
@ -42,7 +42,7 @@ int main()
{ {
framesCounter++; framesCounter++;
ballPositionX = EaseElasticOut(framesCounter, -100, screenWidth/2 + 100, 120); ballPositionX = EaseElasticOut(framesCounter, -100, screenWidth/2 + 100, 120);
if (framesCounter >= 120) if (framesCounter >= 120)
{ {
framesCounter = 0; framesCounter = 0;
@ -53,7 +53,7 @@ int main()
{ {
framesCounter++; framesCounter++;
ballRadius = EaseElasticIn(framesCounter, 20, 500, 200); ballRadius = EaseElasticIn(framesCounter, 20, 500, 200);
if (framesCounter >= 200) if (framesCounter >= 200)
{ {
framesCounter = 0; framesCounter = 0;
@ -64,7 +64,7 @@ int main()
{ {
framesCounter++; framesCounter++;
ballAlpha = EaseCubicOut(framesCounter, 0.0f, 1.0f, 200); ballAlpha = EaseCubicOut(framesCounter, 0.0f, 1.0f, 200);
if (framesCounter >= 200) if (framesCounter >= 200)
{ {
framesCounter = 0; framesCounter = 0;
@ -73,7 +73,7 @@ int main()
} }
else if (state == 3) // Reset state to play again else if (state == 3) // Reset state to play again
{ {
if (IsKeyPressed(KEY_ENTER)) if (IsKeyPressed(KEY_ENTER))
{ {
// Reset required variables to play again // Reset required variables to play again
ballPositionX = -100; ballPositionX = -100;
@ -82,7 +82,7 @@ int main()
state = 0; state = 0;
} }
} }
if (IsKeyPressed(KEY_R)) framesCounter = 0; if (IsKeyPressed(KEY_R)) framesCounter = 0;
//---------------------------------------------------------------------------------- //----------------------------------------------------------------------------------
@ -94,15 +94,15 @@ int main()
if (state >= 2) DrawRectangle(0, 0, screenWidth, screenHeight, GREEN); if (state >= 2) DrawRectangle(0, 0, screenWidth, screenHeight, GREEN);
DrawCircle(ballPositionX, 200, ballRadius, Fade(RED, 1.0f - ballAlpha)); DrawCircle(ballPositionX, 200, ballRadius, Fade(RED, 1.0f - ballAlpha));
if (state == 3) DrawText("PRESS [ENTER] TO PLAY AGAIN!", 240, 200, 20, BLACK); if (state == 3) DrawText("PRESS [ENTER] TO PLAY AGAIN!", 240, 200, 20, BLACK);
EndDrawing(); EndDrawing();
//---------------------------------------------------------------------------------- //----------------------------------------------------------------------------------
} }
// De-Initialization // De-Initialization
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
CloseWindow(); // Close window and OpenGL context CloseWindow(); // Close window and OpenGL context
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------

View file

@ -13,7 +13,7 @@
#include "easings.h" // Required for easing functions #include "easings.h" // Required for easing functions
int main() int main(void)
{ {
// Initialization // Initialization
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
@ -21,16 +21,16 @@ int main()
const int screenHeight = 450; const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [shapes] example - easings box anim"); InitWindow(screenWidth, screenHeight, "raylib [shapes] example - easings box anim");
// Box variables to be animated with easings // Box variables to be animated with easings
Rectangle rec = { GetScreenWidth()/2, -100, 100, 100 }; Rectangle rec = { GetScreenWidth()/2, -100, 100, 100 };
float rotation = 0.0f; float rotation = 0.0f;
float alpha = 1.0f; float alpha = 1.0f;
int state = 0; int state = 0;
int framesCounter = 0; int framesCounter = 0;
SetTargetFPS(60); SetTargetFPS(60); // Set our game to run at 60 frames-per-second
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
// Main game loop // Main game loop
@ -43,12 +43,12 @@ int main()
case 0: // Move box down to center of screen case 0: // Move box down to center of screen
{ {
framesCounter++; framesCounter++;
// NOTE: Remember that 3rd parameter of easing function refers to // NOTE: Remember that 3rd parameter of easing function refers to
// desired value variation, do not confuse it with expected final value! // desired value variation, do not confuse it with expected final value!
rec.y = EaseElasticOut(framesCounter, -100, GetScreenHeight()/2 + 100, 120); rec.y = EaseElasticOut(framesCounter, -100, GetScreenHeight()/2 + 100, 120);
if (framesCounter >= 120) if (framesCounter >= 120)
{ {
framesCounter = 0; framesCounter = 0;
state = 1; state = 1;
@ -59,8 +59,8 @@ int main()
framesCounter++; framesCounter++;
rec.height = EaseBounceOut(framesCounter, 100, -90, 120); rec.height = EaseBounceOut(framesCounter, 100, -90, 120);
rec.width = EaseBounceOut(framesCounter, 100, GetScreenWidth(), 120); rec.width = EaseBounceOut(framesCounter, 100, GetScreenWidth(), 120);
if (framesCounter >= 120) if (framesCounter >= 120)
{ {
framesCounter = 0; framesCounter = 0;
state = 2; state = 2;
@ -70,8 +70,8 @@ int main()
{ {
framesCounter++; framesCounter++;
rotation = EaseQuadOut(framesCounter, 0.0f, 270.0f, 240); rotation = EaseQuadOut(framesCounter, 0.0f, 270.0f, 240);
if (framesCounter >= 240) if (framesCounter >= 240)
{ {
framesCounter = 0; framesCounter = 0;
state = 3; state = 3;
@ -81,8 +81,8 @@ int main()
{ {
framesCounter++; framesCounter++;
rec.height = EaseCircOut(framesCounter, 10, GetScreenWidth(), 120); rec.height = EaseCircOut(framesCounter, 10, GetScreenWidth(), 120);
if (framesCounter >= 120) if (framesCounter >= 120)
{ {
framesCounter = 0; framesCounter = 0;
state = 4; state = 4;
@ -92,7 +92,7 @@ int main()
{ {
framesCounter++; framesCounter++;
alpha = EaseSineOut(framesCounter, 1.0f, -1.0f, 160); alpha = EaseSineOut(framesCounter, 1.0f, -1.0f, 160);
if (framesCounter >= 160) if (framesCounter >= 160)
{ {
framesCounter = 0; framesCounter = 0;
@ -101,7 +101,7 @@ int main()
} break; } break;
default: break; default: break;
} }
// Reset animation at any moment // Reset animation at any moment
if (IsKeyPressed(KEY_SPACE)) if (IsKeyPressed(KEY_SPACE))
{ {
@ -112,7 +112,7 @@ int main()
framesCounter = 0; framesCounter = 0;
} }
//---------------------------------------------------------------------------------- //----------------------------------------------------------------------------------
// Draw // Draw
//---------------------------------------------------------------------------------- //----------------------------------------------------------------------------------
BeginDrawing(); BeginDrawing();
@ -120,7 +120,7 @@ int main()
ClearBackground(RAYWHITE); ClearBackground(RAYWHITE);
DrawRectanglePro(rec, (Vector2){ rec.width/2, rec.height/2 }, rotation, Fade(BLACK, alpha)); DrawRectanglePro(rec, (Vector2){ rec.width/2, rec.height/2 }, rotation, Fade(BLACK, alpha));
DrawText("PRESS [SPACE] TO RESET BOX ANIMATION!", 10, GetScreenHeight() - 25, 20, LIGHTGRAY); DrawText("PRESS [SPACE] TO RESET BOX ANIMATION!", 10, GetScreenHeight() - 25, 20, LIGHTGRAY);
EndDrawing(); EndDrawing();
@ -128,7 +128,7 @@ int main()
} }
// De-Initialization // De-Initialization
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
CloseWindow(); // Close window and OpenGL context CloseWindow(); // Close window and OpenGL context
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------

View file

@ -2,7 +2,7 @@
* *
* raylib [shapes] example - easings rectangle array * raylib [shapes] example - easings rectangle array
* *
* NOTE: This example requires 'easings.h' library, provided on raylib/src. Just copy * NOTE: This example requires 'easings.h' library, provided on raylib/src. Just copy
* the library to same directory as example or make sure it's available on include path. * the library to same directory as example or make sure it's available on include path.
* *
* This example has been created using raylib 2.0 (www.raylib.com) * This example has been created using raylib 2.0 (www.raylib.com)
@ -24,17 +24,17 @@
#define PLAY_TIME_IN_FRAMES 240 // At 60 fps = 4 seconds #define PLAY_TIME_IN_FRAMES 240 // At 60 fps = 4 seconds
int main() int main(void)
{ {
// Initialization // Initialization
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
int screenWidth = 800; const int screenWidth = 800;
int screenHeight = 450; const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [shapes] example - easings rectangle array"); InitWindow(screenWidth, screenHeight, "raylib [shapes] example - easings rectangle array");
Rectangle recs[MAX_RECS_X*MAX_RECS_Y]; Rectangle recs[MAX_RECS_X*MAX_RECS_Y];
for (int y = 0; y < MAX_RECS_Y; y++) for (int y = 0; y < MAX_RECS_Y; y++)
{ {
for (int x = 0; x < MAX_RECS_X; x++) for (int x = 0; x < MAX_RECS_X; x++)
@ -45,12 +45,12 @@ int main()
recs[y*MAX_RECS_X + x].height = RECS_HEIGHT; recs[y*MAX_RECS_X + x].height = RECS_HEIGHT;
} }
} }
float rotation = 0.0f; float rotation = 0.0f;
int framesCounter = 0; int framesCounter = 0;
int state = 0; // Rectangles animation state: 0-Playing, 1-Finished int state = 0; // Rectangles animation state: 0-Playing, 1-Finished
SetTargetFPS(60); SetTargetFPS(60); // Set our game to run at 60 frames-per-second
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
// Main game loop // Main game loop
@ -62,16 +62,16 @@ int main()
{ {
framesCounter++; framesCounter++;
for (int i = 0; i < MAX_RECS_X*MAX_RECS_Y; i++) for (int i = 0; i < MAX_RECS_X*MAX_RECS_Y; i++)
{ {
recs[i].height = EaseCircOut(framesCounter, RECS_HEIGHT, -RECS_HEIGHT, PLAY_TIME_IN_FRAMES); recs[i].height = EaseCircOut(framesCounter, RECS_HEIGHT, -RECS_HEIGHT, PLAY_TIME_IN_FRAMES);
recs[i].width = EaseCircOut(framesCounter, RECS_WIDTH, -RECS_WIDTH, PLAY_TIME_IN_FRAMES); recs[i].width = EaseCircOut(framesCounter, RECS_WIDTH, -RECS_WIDTH, PLAY_TIME_IN_FRAMES);
if (recs[i].height < 0) recs[i].height = 0; if (recs[i].height < 0) recs[i].height = 0;
if (recs[i].width < 0) recs[i].width = 0; if (recs[i].width < 0) recs[i].width = 0;
if ((recs[i].height == 0) && (recs[i].width == 0)) state = 1; // Finish playing if ((recs[i].height == 0) && (recs[i].width == 0)) state = 1; // Finish playing
rotation = EaseLinearIn(framesCounter, 0.0f, 360.0f, PLAY_TIME_IN_FRAMES); rotation = EaseLinearIn(framesCounter, 0.0f, 360.0f, PLAY_TIME_IN_FRAMES);
} }
} }
@ -79,13 +79,13 @@ int main()
{ {
// When animation has finished, press space to restart // When animation has finished, press space to restart
framesCounter = 0; framesCounter = 0;
for (int i = 0; i < MAX_RECS_X*MAX_RECS_Y; i++) for (int i = 0; i < MAX_RECS_X*MAX_RECS_Y; i++)
{ {
recs[i].height = RECS_HEIGHT; recs[i].height = RECS_HEIGHT;
recs[i].width = RECS_WIDTH; recs[i].width = RECS_WIDTH;
} }
state = 0; state = 0;
} }
//---------------------------------------------------------------------------------- //----------------------------------------------------------------------------------
@ -110,7 +110,7 @@ int main()
} }
// De-Initialization // De-Initialization
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
CloseWindow(); // Close window and OpenGL context CloseWindow(); // Close window and OpenGL context
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------

View file

@ -13,7 +13,7 @@
#include <math.h> // Required for: atan2f() #include <math.h> // Required for: atan2f()
int main() int main(void)
{ {
// Initialization // Initialization
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
@ -21,19 +21,19 @@ int main()
const int screenHeight = 450; const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [shapes] example - following eyes"); InitWindow(screenWidth, screenHeight, "raylib [shapes] example - following eyes");
Vector2 scleraLeftPosition = { GetScreenWidth()/2 - 100, GetScreenHeight()/2 }; Vector2 scleraLeftPosition = { GetScreenWidth()/2 - 100, GetScreenHeight()/2 };
Vector2 scleraRightPosition = { GetScreenWidth()/2 + 100, GetScreenHeight()/2 }; Vector2 scleraRightPosition = { GetScreenWidth()/2 + 100, GetScreenHeight()/2 };
float scleraRadius = 80; float scleraRadius = 80;
Vector2 irisLeftPosition = { GetScreenWidth()/2 - 100, GetScreenHeight()/2 }; Vector2 irisLeftPosition = { GetScreenWidth()/2 - 100, GetScreenHeight()/2 };
Vector2 irisRightPosition = { GetScreenWidth()/2 + 100, GetScreenHeight()/2}; Vector2 irisRightPosition = { GetScreenWidth()/2 + 100, GetScreenHeight()/2};
float irisRadius = 24; float irisRadius = 24;
float angle; float angle = 0.0f;
float dx, dy, dxx, dyy; float dx = 0.0f, dy = 0.0f, dxx = 0.0f, dyy = 0.0f;
SetTargetFPS(60); SetTargetFPS(60); // Set our game to run at 60 frames-per-second
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
// Main game loop // Main game loop
@ -43,13 +43,13 @@ int main()
//---------------------------------------------------------------------------------- //----------------------------------------------------------------------------------
irisLeftPosition = GetMousePosition(); irisLeftPosition = GetMousePosition();
irisRightPosition = GetMousePosition(); irisRightPosition = GetMousePosition();
// Check not inside the left eye sclera // Check not inside the left eye sclera
if (!CheckCollisionPointCircle(irisLeftPosition, scleraLeftPosition, scleraRadius - 20)) if (!CheckCollisionPointCircle(irisLeftPosition, scleraLeftPosition, scleraRadius - 20))
{ {
dx = irisLeftPosition.x - scleraLeftPosition.x; dx = irisLeftPosition.x - scleraLeftPosition.x;
dy = irisLeftPosition.y - scleraLeftPosition.y; dy = irisLeftPosition.y - scleraLeftPosition.y;
angle = atan2f(dy, dx); angle = atan2f(dy, dx);
dxx = (scleraRadius - irisRadius)*cosf(angle); dxx = (scleraRadius - irisRadius)*cosf(angle);
@ -64,7 +64,7 @@ int main()
{ {
dx = irisRightPosition.x - scleraRightPosition.x; dx = irisRightPosition.x - scleraRightPosition.x;
dy = irisRightPosition.y - scleraRightPosition.y; dy = irisRightPosition.y - scleraRightPosition.y;
angle = atan2f(dy, dx); angle = atan2f(dy, dx);
dxx = (scleraRadius - irisRadius)*cosf(angle); dxx = (scleraRadius - irisRadius)*cosf(angle);
@ -84,19 +84,19 @@ int main()
DrawCircleV(scleraLeftPosition, scleraRadius, LIGHTGRAY); DrawCircleV(scleraLeftPosition, scleraRadius, LIGHTGRAY);
DrawCircleV(irisLeftPosition, irisRadius, BROWN); DrawCircleV(irisLeftPosition, irisRadius, BROWN);
DrawCircleV(irisLeftPosition, 10, BLACK); DrawCircleV(irisLeftPosition, 10, BLACK);
DrawCircleV(scleraRightPosition, scleraRadius, LIGHTGRAY); DrawCircleV(scleraRightPosition, scleraRadius, LIGHTGRAY);
DrawCircleV(irisRightPosition, irisRadius, DARKGREEN); DrawCircleV(irisRightPosition, irisRadius, DARKGREEN);
DrawCircleV(irisRightPosition, 10, BLACK); DrawCircleV(irisRightPosition, 10, BLACK);
DrawFPS(10, 10); DrawFPS(10, 10);
EndDrawing(); EndDrawing();
//---------------------------------------------------------------------------------- //----------------------------------------------------------------------------------
} }
// De-Initialization // De-Initialization
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
CloseWindow(); // Close window and OpenGL context CloseWindow(); // Close window and OpenGL context
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------

View file

@ -11,20 +11,20 @@
#include "raylib.h" #include "raylib.h"
int main() int main(void)
{ {
// Initialization // Initialization
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
int screenWidth = 800; const int screenWidth = 800;
int screenHeight = 450; const int screenHeight = 450;
SetConfigFlags(FLAG_MSAA_4X_HINT); SetConfigFlags(FLAG_MSAA_4X_HINT);
InitWindow(screenWidth, screenHeight, "raylib [shapes] example - cubic-bezier lines"); InitWindow(screenWidth, screenHeight, "raylib [shapes] example - cubic-bezier lines");
Vector2 start = { 0, 0 }; Vector2 start = { 0, 0 };
Vector2 end = { screenWidth, screenHeight }; Vector2 end = { screenWidth, screenHeight };
SetTargetFPS(60); SetTargetFPS(60); // Set our game to run at 60 frames-per-second
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
// Main game loop // Main game loop
@ -41,17 +41,17 @@ int main()
BeginDrawing(); BeginDrawing();
ClearBackground(RAYWHITE); ClearBackground(RAYWHITE);
DrawText("USE MOUSE LEFT-RIGHT CLICK to DEFINE LINE START and END POINTS", 15, 20, 20, GRAY); DrawText("USE MOUSE LEFT-RIGHT CLICK to DEFINE LINE START and END POINTS", 15, 20, 20, GRAY);
DrawLineBezier(start, end, 2.0f, RED); DrawLineBezier(start, end, 2.0f, RED);
EndDrawing(); EndDrawing();
//---------------------------------------------------------------------------------- //----------------------------------------------------------------------------------
} }
// De-Initialization // De-Initialization
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
CloseWindow(); // Close window and OpenGL context CloseWindow(); // Close window and OpenGL context
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------

View file

@ -11,16 +11,16 @@
#include "raylib.h" #include "raylib.h"
int main() int main(void)
{ {
// Initialization // Initialization
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
int screenWidth = 800; const int screenWidth = 800;
int screenHeight = 450; const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [shapes] example - raylib logo using shapes"); InitWindow(screenWidth, screenHeight, "raylib [shapes] example - raylib logo using shapes");
SetTargetFPS(60); SetTargetFPS(60); // Set our game to run at 60 frames-per-second
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
// Main game loop // Main game loop

View file

@ -11,12 +11,12 @@
#include "raylib.h" #include "raylib.h"
int main() int main(void)
{ {
// Initialization // Initialization
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
int screenWidth = 800; const int screenWidth = 800;
int screenHeight = 450; const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [shapes] example - raylib logo animation"); InitWindow(screenWidth, screenHeight, "raylib [shapes] example - raylib logo animation");
@ -35,7 +35,7 @@ int main()
int state = 0; // Tracking animation states (State Machine) int state = 0; // Tracking animation states (State Machine)
float alpha = 1.0f; // Useful for fading float alpha = 1.0f; // Useful for fading
SetTargetFPS(60); SetTargetFPS(60); // Set our game to run at 60 frames-per-second
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
// Main game loop // Main game loop

View file

@ -15,23 +15,23 @@
#define MOUSE_SCALE_MARK_SIZE 12 #define MOUSE_SCALE_MARK_SIZE 12
int main() int main(void)
{ {
// Initialization // Initialization
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
int screenWidth = 800; const int screenWidth = 800;
int screenHeight = 450; const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [shapes] example - rectangle scaling mouse"); InitWindow(screenWidth, screenHeight, "raylib [shapes] example - rectangle scaling mouse");
Rectangle rec = { 100, 100, 200, 80 }; Rectangle rec = { 100, 100, 200, 80 };
Vector2 mousePosition = { 0 }; Vector2 mousePosition = { 0 };
bool mouseScaleReady = false; bool mouseScaleReady = false;
bool mouseScaleMode = false; bool mouseScaleMode = false;
SetTargetFPS(60); SetTargetFPS(60); // Set our game to run at 60 frames-per-second
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
// Main game loop // Main game loop
@ -40,25 +40,25 @@ int main()
// Update // Update
//---------------------------------------------------------------------------------- //----------------------------------------------------------------------------------
mousePosition = GetMousePosition(); mousePosition = GetMousePosition();
if (CheckCollisionPointRec(mousePosition, rec) && if (CheckCollisionPointRec(mousePosition, rec) &&
CheckCollisionPointRec(mousePosition, (Rectangle){ rec.x + rec.width - MOUSE_SCALE_MARK_SIZE, rec.y + rec.height - MOUSE_SCALE_MARK_SIZE, MOUSE_SCALE_MARK_SIZE, MOUSE_SCALE_MARK_SIZE })) CheckCollisionPointRec(mousePosition, (Rectangle){ rec.x + rec.width - MOUSE_SCALE_MARK_SIZE, rec.y + rec.height - MOUSE_SCALE_MARK_SIZE, MOUSE_SCALE_MARK_SIZE, MOUSE_SCALE_MARK_SIZE }))
{ {
mouseScaleReady = true; mouseScaleReady = true;
if (IsMouseButtonPressed(MOUSE_LEFT_BUTTON)) mouseScaleMode = true; if (IsMouseButtonPressed(MOUSE_LEFT_BUTTON)) mouseScaleMode = true;
} }
else mouseScaleReady = false; else mouseScaleReady = false;
if (mouseScaleMode) if (mouseScaleMode)
{ {
mouseScaleReady = true; mouseScaleReady = true;
rec.width = (mousePosition.x - rec.x); rec.width = (mousePosition.x - rec.x);
rec.height = (mousePosition.y - rec.y); rec.height = (mousePosition.y - rec.y);
if (rec.width < MOUSE_SCALE_MARK_SIZE) rec.width = MOUSE_SCALE_MARK_SIZE; if (rec.width < MOUSE_SCALE_MARK_SIZE) rec.width = MOUSE_SCALE_MARK_SIZE;
if (rec.height < MOUSE_SCALE_MARK_SIZE) rec.height = MOUSE_SCALE_MARK_SIZE; if (rec.height < MOUSE_SCALE_MARK_SIZE) rec.height = MOUSE_SCALE_MARK_SIZE;
if (IsMouseButtonReleased(MOUSE_LEFT_BUTTON)) mouseScaleMode = false; if (IsMouseButtonReleased(MOUSE_LEFT_BUTTON)) mouseScaleMode = false;
} }
//---------------------------------------------------------------------------------- //----------------------------------------------------------------------------------
@ -68,15 +68,15 @@ int main()
BeginDrawing(); BeginDrawing();
ClearBackground(RAYWHITE); ClearBackground(RAYWHITE);
DrawText("Scale rectangle dragging from bottom-right corner!", 10, 10, 20, GRAY); DrawText("Scale rectangle dragging from bottom-right corner!", 10, 10, 20, GRAY);
DrawRectangleRec(rec, Fade(GREEN, 0.5f)); DrawRectangleRec(rec, Fade(GREEN, 0.5f));
if (mouseScaleReady) if (mouseScaleReady)
{ {
DrawRectangleLinesEx(rec, 1, RED); DrawRectangleLinesEx(rec, 1, RED);
DrawTriangle((Vector2){ rec.x + rec.width - MOUSE_SCALE_MARK_SIZE, rec.y + rec.height }, DrawTriangle((Vector2){ rec.x + rec.width - MOUSE_SCALE_MARK_SIZE, rec.y + rec.height },
(Vector2){ rec.x + rec.width, rec.y + rec.height }, (Vector2){ rec.x + rec.width, rec.y + rec.height },
(Vector2){ rec.x + rec.width, rec.y + rec.height - MOUSE_SCALE_MARK_SIZE }, RED); (Vector2){ rec.x + rec.width, rec.y + rec.height - MOUSE_SCALE_MARK_SIZE }, RED);
} }
@ -86,7 +86,7 @@ int main()
} }
// De-Initialization // De-Initialization
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
CloseWindow(); // Close window and OpenGL context CloseWindow(); // Close window and OpenGL context
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------

View file

@ -11,12 +11,12 @@
#include "raylib.h" #include "raylib.h"
int main() int main(void)
{ {
// Initialization // Initialization
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
int screenWidth = 800; const int screenWidth = 800;
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 - bmfont and ttf sprite fonts loading");
@ -25,17 +25,17 @@ int main()
const char msg[256] = "!\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHI\nJKLMNOPQRSTUVWXYZ[]^_`abcdefghijklmn\nopqrstuvwxyz{|}~¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓ\nÔÕÖרÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷\nøùúûüýþÿ"; const char msg[256] = "!\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHI\nJKLMNOPQRSTUVWXYZ[]^_`abcdefghijklmn\nopqrstuvwxyz{|}~¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓ\nÔÕÖרÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷\nøùúûüýþÿ";
// 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)
// BMFont (AngelCode) : Font data and image atlas have been generated using external program // BMFont (AngelCode) : Font data and image atlas have been generated using external program
Font fontBm = LoadFont("resources/pixantiqua.fnt"); Font fontBm = LoadFont("resources/pixantiqua.fnt");
// TTF font : Font data and atlas are generated directly from TTF // TTF font : Font data and atlas are generated directly from TTF
// NOTE: We define a font base size of 32 pixels tall and up-to 250 characters // NOTE: We define a font base size of 32 pixels tall and up-to 250 characters
Font fontTtf = LoadFontEx("resources/pixantiqua.ttf", 32, 0, 250); Font fontTtf = LoadFontEx("resources/pixantiqua.ttf", 32, 0, 250);
bool useTtf = false; bool useTtf = false;
SetTargetFPS(60); SetTargetFPS(60); // Set our game to run at 60 frames-per-second
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
// Main game loop // Main game loop
@ -52,7 +52,7 @@ int main()
BeginDrawing(); BeginDrawing();
ClearBackground(RAYWHITE); ClearBackground(RAYWHITE);
DrawText("Press SPACE to use TTF generated font", 20, 20, 20, LIGHTGRAY); DrawText("Press SPACE to use TTF generated font", 20, 20, 20, LIGHTGRAY);
if (!useTtf) if (!useTtf)

View file

@ -17,17 +17,17 @@
#define GLSL_VERSION 100 #define GLSL_VERSION 100
#endif #endif
int main() int main(void)
{ {
// Initialization // Initialization
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
int screenWidth = 800; const int screenWidth = 800;
int screenHeight = 450; const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [text] example - SDF fonts"); InitWindow(screenWidth, screenHeight, "raylib [text] example - SDF fonts");
// 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)
const char msg[50] = "Signed Distance Fields"; const char msg[50] = "Signed Distance Fields";
// Default font generation from TTF font // Default font generation from TTF font
@ -40,7 +40,7 @@ int main()
Image atlas = GenImageFontAtlas(fontDefault.chars, 95, 16, 4, 0); Image atlas = GenImageFontAtlas(fontDefault.chars, 95, 16, 4, 0);
fontDefault.texture = LoadTextureFromImage(atlas); fontDefault.texture = LoadTextureFromImage(atlas);
UnloadImage(atlas); UnloadImage(atlas);
// SDF font generation from TTF font // SDF font generation from TTF font
Font fontSDF = { 0 }; Font fontSDF = { 0 };
fontSDF.baseSize = 16; fontSDF.baseSize = 16;
@ -51,7 +51,7 @@ int main()
atlas = GenImageFontAtlas(fontSDF.chars, 95, 16, 0, 1); atlas = GenImageFontAtlas(fontSDF.chars, 95, 16, 0, 1);
fontSDF.texture = LoadTextureFromImage(atlas); fontSDF.texture = LoadTextureFromImage(atlas);
UnloadImage(atlas); UnloadImage(atlas);
// Load SDF required shader (we use default vertex shader) // Load SDF required shader (we use default vertex shader)
Shader shader = LoadShader(0, FormatText("resources/shaders/glsl%i/sdf.fs", GLSL_VERSION)); Shader shader = LoadShader(0, FormatText("resources/shaders/glsl%i/sdf.fs", GLSL_VERSION));
SetTextureFilter(fontSDF.texture, FILTER_BILINEAR); // Required for SDF font SetTextureFilter(fontSDF.texture, FILTER_BILINEAR); // Required for SDF font
@ -59,51 +59,51 @@ int main()
Vector2 fontPosition = { 40, screenHeight/2 - 50 }; Vector2 fontPosition = { 40, screenHeight/2 - 50 };
Vector2 textSize = { 0.0f }; Vector2 textSize = { 0.0f };
float fontSize = 16.0f; float fontSize = 16.0f;
int currentFont = 0; // 0 - fontDefault, 1 - fontSDF int currentFont = 0; // 0 - fontDefault, 1 - fontSDF
SetTargetFPS(60);
//--------------------------------------------------------------------------------------
SetTargetFPS(60); // Set our game to run at 60 frames-per-second
//--------------------------------------------------------------------------------------
// Main game loop // Main game loop
while (!WindowShouldClose()) // Detect window close button or ESC key while (!WindowShouldClose()) // Detect window close button or ESC key
{ {
// Update // Update
//---------------------------------------------------------------------------------- //----------------------------------------------------------------------------------
fontSize += GetMouseWheelMove()*8.0f; fontSize += GetMouseWheelMove()*8.0f;
if (fontSize < 6) fontSize = 6; if (fontSize < 6) fontSize = 6;
if (IsKeyDown(KEY_SPACE)) currentFont = 1; if (IsKeyDown(KEY_SPACE)) currentFont = 1;
else currentFont = 0; else currentFont = 0;
if (currentFont == 0) textSize = MeasureTextEx(fontDefault, msg, fontSize, 0); if (currentFont == 0) textSize = MeasureTextEx(fontDefault, msg, fontSize, 0);
else textSize = MeasureTextEx(fontSDF, msg, fontSize, 0); else textSize = MeasureTextEx(fontSDF, msg, fontSize, 0);
fontPosition.x = GetScreenWidth()/2 - textSize.x/2; fontPosition.x = GetScreenWidth()/2 - textSize.x/2;
fontPosition.y = GetScreenHeight()/2 - textSize.y/2 + 80; fontPosition.y = GetScreenHeight()/2 - textSize.y/2 + 80;
//---------------------------------------------------------------------------------- //----------------------------------------------------------------------------------
// Draw // Draw
//---------------------------------------------------------------------------------- //----------------------------------------------------------------------------------
BeginDrawing(); BeginDrawing();
ClearBackground(RAYWHITE); ClearBackground(RAYWHITE);
if (currentFont == 1) if (currentFont == 1)
{ {
// NOTE: SDF fonts require a custom SDf shader to compute fragment color // NOTE: SDF fonts require a custom SDf shader to compute fragment color
BeginShaderMode(shader); // Activate SDF font shader BeginShaderMode(shader); // Activate SDF font shader
DrawTextEx(fontSDF, msg, fontPosition, fontSize, 0, BLACK); DrawTextEx(fontSDF, msg, fontPosition, fontSize, 0, BLACK);
EndShaderMode(); // Activate our default shader for next drawings EndShaderMode(); // Activate our default shader for next drawings
DrawTexture(fontSDF.texture, 10, 10, BLACK); DrawTexture(fontSDF.texture, 10, 10, BLACK);
} }
else else
{ {
DrawTextEx(fontDefault, msg, fontPosition, fontSize, 0, BLACK); DrawTextEx(fontDefault, msg, fontPosition, fontSize, 0, BLACK);
DrawTexture(fontDefault.texture, 10, 10, BLACK); DrawTexture(fontDefault.texture, 10, 10, BLACK);
} }
if (currentFont == 1) DrawText("SDF!", 320, 20, 80, RED); if (currentFont == 1) DrawText("SDF!", 320, 20, 80, RED);
else DrawText("default font", 315, 40, 30, GRAY); else DrawText("default font", 315, 40, 30, GRAY);
@ -112,7 +112,7 @@ int main()
DrawText("Use MOUSE WHEEL to SCALE TEXT!", GetScreenWidth() - 240, 90, 10, DARKGRAY); DrawText("Use MOUSE WHEEL to SCALE TEXT!", GetScreenWidth() - 240, 90, 10, DARKGRAY);
DrawText("PRESS SPACE to USE SDF FONT VERSION!", 340, GetScreenHeight() - 30, 20, MAROON); DrawText("PRESS SPACE to USE SDF FONT VERSION!", 340, GetScreenHeight() - 30, 20, MAROON);
EndDrawing(); EndDrawing();
//---------------------------------------------------------------------------------- //----------------------------------------------------------------------------------
} }
@ -121,11 +121,11 @@ int main()
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
UnloadFont(fontDefault); // Default font unloading UnloadFont(fontDefault); // Default font unloading
UnloadFont(fontSDF); // SDF font unloading UnloadFont(fontSDF); // SDF font unloading
UnloadShader(shader); // Unload SDF shader UnloadShader(shader); // Unload SDF shader
CloseWindow(); // Close window and OpenGL context CloseWindow(); // Close window and OpenGL context
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
return 0; return 0;
} }

View file

@ -11,12 +11,12 @@
#include "raylib.h" #include "raylib.h"
int main() int main(void)
{ {
// Initialization // Initialization
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
int screenWidth = 800; const int screenWidth = 800;
int screenHeight = 450; const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [text] example - text formatting"); InitWindow(screenWidth, screenHeight, "raylib [text] example - text formatting");
@ -24,7 +24,7 @@ int main()
int hiscore = 200450; int hiscore = 200450;
int lives = 5; int lives = 5;
SetTargetFPS(60); SetTargetFPS(60); // Set our game to run at 60 frames-per-second
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
// Main game loop // Main game loop

View file

@ -13,12 +13,12 @@
#define MAX_INPUT_CHARS 9 #define MAX_INPUT_CHARS 9
int main() int main(void)
{ {
// Initialization // Initialization
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
int screenWidth = 800; const int screenWidth = 800;
int screenHeight = 450; const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [text] example - input box"); InitWindow(screenWidth, screenHeight, "raylib [text] example - input box");
@ -30,7 +30,7 @@ int main()
int framesCounter = 0; int framesCounter = 0;
SetTargetFPS(60); SetTargetFPS(60); // Set our game to run at 60 frames-per-second
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
// Main game loop // Main game loop
@ -40,27 +40,27 @@ int main()
//---------------------------------------------------------------------------------- //----------------------------------------------------------------------------------
if (CheckCollisionPointRec(GetMousePosition(), textBox)) mouseOnText = true; if (CheckCollisionPointRec(GetMousePosition(), textBox)) mouseOnText = true;
else mouseOnText = false; else mouseOnText = false;
if (mouseOnText) if (mouseOnText)
{ {
int key = GetKeyPressed(); int key = GetKeyPressed();
// NOTE: Only allow keys in range [32..125] // NOTE: Only allow keys in range [32..125]
if ((key >= 32) && (key <= 125) && (letterCount < MAX_INPUT_CHARS)) if ((key >= 32) && (key <= 125) && (letterCount < MAX_INPUT_CHARS))
{ {
name[letterCount] = (char)key; name[letterCount] = (char)key;
letterCount++; letterCount++;
} }
if (IsKeyPressed(KEY_BACKSPACE)) if (IsKeyPressed(KEY_BACKSPACE))
{ {
letterCount--; letterCount--;
name[letterCount] = '\0'; name[letterCount] = '\0';
if (letterCount < 0) letterCount = 0; if (letterCount < 0) letterCount = 0;
} }
} }
if (mouseOnText) framesCounter++; if (mouseOnText) framesCounter++;
else framesCounter = 0; else framesCounter = 0;
//---------------------------------------------------------------------------------- //----------------------------------------------------------------------------------
@ -70,15 +70,15 @@ int main()
BeginDrawing(); BeginDrawing();
ClearBackground(RAYWHITE); ClearBackground(RAYWHITE);
DrawText("PLACE MOUSE OVER INPUT BOX!", 240, 140, 20, GRAY); DrawText("PLACE MOUSE OVER INPUT BOX!", 240, 140, 20, GRAY);
DrawRectangleRec(textBox, LIGHTGRAY); DrawRectangleRec(textBox, LIGHTGRAY);
if (mouseOnText) DrawRectangleLines(textBox.x, textBox.y, textBox.width, textBox.height, RED); if (mouseOnText) DrawRectangleLines(textBox.x, textBox.y, textBox.width, textBox.height, RED);
else DrawRectangleLines(textBox.x, textBox.y, textBox.width, textBox.height, DARKGRAY); else DrawRectangleLines(textBox.x, textBox.y, textBox.width, textBox.height, DARKGRAY);
DrawText(name, textBox.x + 5, textBox.y + 8, 40, MAROON); DrawText(name, textBox.x + 5, textBox.y + 8, 40, MAROON);
DrawText(FormatText("INPUT CHARS: %i/%i", letterCount, MAX_INPUT_CHARS), 315, 250, 20, DARKGRAY); DrawText(FormatText("INPUT CHARS: %i/%i", letterCount, MAX_INPUT_CHARS), 315, 250, 20, DARKGRAY);
if (mouseOnText) if (mouseOnText)
@ -90,13 +90,13 @@ int main()
} }
else DrawText("Press BACKSPACE to delete chars...", 230, 300, 20, GRAY); else DrawText("Press BACKSPACE to delete chars...", 230, 300, 20, GRAY);
} }
EndDrawing(); EndDrawing();
//---------------------------------------------------------------------------------- //----------------------------------------------------------------------------------
} }
// De-Initialization // De-Initialization
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
CloseWindow(); // Close window and OpenGL context CloseWindow(); // Close window and OpenGL context
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------

View file

@ -16,18 +16,18 @@
#define MAX_FONTS 8 #define MAX_FONTS 8
int main() int main(void)
{ {
// Initialization // Initialization
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
int screenWidth = 800; const int screenWidth = 800;
int screenHeight = 450; const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [text] example - raylib fonts"); InitWindow(screenWidth, screenHeight, "raylib [text] example - raylib fonts");
// NOTE: Textures MUST be loaded after Window initialization (OpenGL context is required) // NOTE: Textures MUST be loaded after Window initialization (OpenGL context is required)
Font fonts[MAX_FONTS]; Font fonts[MAX_FONTS];
fonts[0] = LoadFont("resources/fonts/alagard.png"); fonts[0] = LoadFont("resources/fonts/alagard.png");
fonts[1] = LoadFont("resources/fonts/pixelplay.png"); fonts[1] = LoadFont("resources/fonts/pixelplay.png");
fonts[2] = LoadFont("resources/fonts/mecha.png"); fonts[2] = LoadFont("resources/fonts/mecha.png");
@ -36,32 +36,34 @@ int main()
fonts[5] = LoadFont("resources/fonts/pixantiqua.png"); fonts[5] = LoadFont("resources/fonts/pixantiqua.png");
fonts[6] = LoadFont("resources/fonts/alpha_beta.png"); fonts[6] = LoadFont("resources/fonts/alpha_beta.png");
fonts[7] = LoadFont("resources/fonts/jupiter_crash.png"); fonts[7] = LoadFont("resources/fonts/jupiter_crash.png");
const char *messages[MAX_FONTS] = { "ALAGARD FONT designed by Hewett Tsoi", const char *messages[MAX_FONTS] = { "ALAGARD FONT designed by Hewett Tsoi",
"PIXELPLAY FONT designed by Aleksander Shevchuk", "PIXELPLAY FONT designed by Aleksander Shevchuk",
"MECHA FONT designed by Captain Falcon", "MECHA FONT designed by Captain Falcon",
"SETBACK FONT designed by Brian Kent (AEnigma)", "SETBACK FONT designed by Brian Kent (AEnigma)",
"ROMULUS FONT designed by Hewett Tsoi", "ROMULUS FONT designed by Hewett Tsoi",
"PIXANTIQUA FONT designed by Gerhard Grossmann", "PIXANTIQUA FONT designed by Gerhard Grossmann",
"ALPHA_BETA FONT designed by Brian Kent (AEnigma)", "ALPHA_BETA FONT designed by Brian Kent (AEnigma)",
"JUPITER_CRASH FONT designed by Brian Kent (AEnigma)" }; "JUPITER_CRASH FONT designed by Brian Kent (AEnigma)" };
const int spacings[MAX_FONTS] = { 2, 4, 8, 4, 3, 4, 4, 1 }; const int spacings[MAX_FONTS] = { 2, 4, 8, 4, 3, 4, 4, 1 };
Vector2 positions[MAX_FONTS]; Vector2 positions[MAX_FONTS];
for (int i = 0; i < MAX_FONTS; i++) for (int i = 0; i < MAX_FONTS; i++)
{ {
positions[i].x = screenWidth/2 - MeasureTextEx(fonts[i], messages[i], fonts[i].baseSize*2, spacings[i]).x/2; positions[i].x = screenWidth/2 - MeasureTextEx(fonts[i], messages[i], fonts[i].baseSize*2, spacings[i]).x/2;
positions[i].y = 60 + fonts[i].baseSize + 45*i; positions[i].y = 60 + fonts[i].baseSize + 45*i;
} }
// Small Y position corrections // Small Y position corrections
positions[3].y += 8; positions[3].y += 8;
positions[4].y += 2; positions[4].y += 2;
positions[7].y -= 8; positions[7].y -= 8;
Color colors[MAX_FONTS] = { MAROON, ORANGE, DARKGREEN, DARKBLUE, DARKPURPLE, LIME, GOLD, RED }; Color colors[MAX_FONTS] = { MAROON, ORANGE, DARKGREEN, DARKBLUE, DARKPURPLE, LIME, GOLD, RED };
SetTargetFPS(60); // Set our game to run at 60 frames-per-second
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
// Main game loop // Main game loop
@ -77,10 +79,10 @@ int main()
BeginDrawing(); BeginDrawing();
ClearBackground(RAYWHITE); ClearBackground(RAYWHITE);
DrawText("free fonts included with raylib", 250, 20, 20, DARKGRAY); DrawText("free fonts included with raylib", 250, 20, 20, DARKGRAY);
DrawLine(220, 50, 590, 50, DARKGRAY); DrawLine(220, 50, 590, 50, DARKGRAY);
for (int i = 0; i < MAX_FONTS; i++) for (int i = 0; i < MAX_FONTS; i++)
{ {
DrawTextEx(fonts[i], messages[i], positions[i], fonts[i].baseSize*2, spacings[i], colors[i]); DrawTextEx(fonts[i], messages[i], positions[i], fonts[i].baseSize*2, spacings[i], colors[i]);
@ -92,7 +94,7 @@ int main()
// De-Initialization // De-Initialization
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
// Fonts unloading // Fonts unloading
for (int i = 0; i < MAX_FONTS; i++) UnloadFont(fonts[i]); for (int i = 0; i < MAX_FONTS; i++) UnloadFont(fonts[i]);

View file

@ -13,36 +13,36 @@
#include "raylib.h" #include "raylib.h"
int main() int main(void)
{ {
// Initialization // Initialization
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
int screenWidth = 800; const int screenWidth = 800;
int screenHeight = 450; const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [text] example - draw text inside a rectangle"); InitWindow(screenWidth, screenHeight, "raylib [text] example - draw text inside a rectangle");
char text[] = "Text cannot escape\tthis container\t...word wrap also works when active so here's\ char text[] = "Text cannot escape\tthis container\t...word wrap also works when active so here's\
a long text for testing.\n\nLorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod\ a long text for testing.\n\nLorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod\
tempor incididunt ut labore et dolore magna aliqua. Nec ullamcorper sit amet risus nullam eget felis eget."; tempor incididunt ut labore et dolore magna aliqua. Nec ullamcorper sit amet risus nullam eget felis eget.";
bool resizing = false; bool resizing = false;
bool wordWrap = true; bool wordWrap = true;
Rectangle container = { 25, 25, screenWidth - 50, screenHeight - 250}; Rectangle container = { 25, 25, screenWidth - 50, screenHeight - 250};
Rectangle resizer = { container.x + container.width - 17, container.y + container.height - 17, 14, 14 }; Rectangle resizer = { container.x + container.width - 17, container.y + container.height - 17, 14, 14 };
// Minimum width and heigh for the container rectangle // Minimum width and heigh for the container rectangle
const int minWidth = 60; const int minWidth = 60;
const int minHeight = 60; const int minHeight = 60;
const int maxWidth = screenWidth - 50; const int maxWidth = screenWidth - 50;
const int maxHeight = screenHeight - 160; const int maxHeight = screenHeight - 160;
Vector2 lastMouse = { 0, 0 }; // Stores last mouse coordinates Vector2 lastMouse = { 0, 0 }; // Stores last mouse coordinates
Color borderColor = MAROON; // Container border color Color borderColor = MAROON; // Container border color
Font font = GetFontDefault(); // Get default system font Font font = GetFontDefault(); // Get default system font
SetTargetFPS(60); SetTargetFPS(60); // Set our game to run at 60 frames-per-second
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
// Main game loop // Main game loop
@ -51,34 +51,34 @@ int main()
// Update // Update
//---------------------------------------------------------------------------------- //----------------------------------------------------------------------------------
if (IsKeyPressed(KEY_SPACE)) wordWrap = !wordWrap; if (IsKeyPressed(KEY_SPACE)) wordWrap = !wordWrap;
Vector2 mouse = GetMousePosition(); Vector2 mouse = GetMousePosition();
// Check if the mouse is inside the container and toggle border color // Check if the mouse is inside the container and toggle border color
if (CheckCollisionPointRec(mouse, container)) borderColor = Fade(MAROON, 0.4f); if (CheckCollisionPointRec(mouse, container)) borderColor = Fade(MAROON, 0.4f);
else if (!resizing) borderColor = MAROON; else if (!resizing) borderColor = MAROON;
// Container resizing logic // Container resizing logic
if (resizing) if (resizing)
{ {
if (IsMouseButtonReleased(MOUSE_LEFT_BUTTON)) resizing = false; if (IsMouseButtonReleased(MOUSE_LEFT_BUTTON)) resizing = false;
int width = container.width + (mouse.x - lastMouse.x); int width = container.width + (mouse.x - lastMouse.x);
container.width = (width > minWidth)? ((width < maxWidth)? width : maxWidth) : minWidth; container.width = (width > minWidth)? ((width < maxWidth)? width : maxWidth) : minWidth;
int height = container.height + (mouse.y - lastMouse.y); int height = container.height + (mouse.y - lastMouse.y);
container.height = (height > minHeight)? ((height < maxHeight)? height : maxHeight) : minHeight; container.height = (height > minHeight)? ((height < maxHeight)? height : maxHeight) : minHeight;
} }
else else
{ {
// Check if we're resizing // Check if we're resizing
if (IsMouseButtonDown(MOUSE_LEFT_BUTTON) && CheckCollisionPointRec(mouse, resizer)) resizing = true; if (IsMouseButtonDown(MOUSE_LEFT_BUTTON) && CheckCollisionPointRec(mouse, resizer)) resizing = true;
} }
// Move resizer rectangle properly // Move resizer rectangle properly
resizer.x = container.x + container.width - 17; resizer.x = container.x + container.width - 17;
resizer.y = container.y + container.height - 17; resizer.y = container.y + container.height - 17;
lastMouse = mouse; // Update mouse lastMouse = mouse; // Update mouse
//---------------------------------------------------------------------------------- //----------------------------------------------------------------------------------
@ -89,10 +89,10 @@ int main()
ClearBackground(RAYWHITE); ClearBackground(RAYWHITE);
DrawRectangleLinesEx(container, 3, borderColor); // Draw container border DrawRectangleLinesEx(container, 3, borderColor); // Draw container border
// Draw text in container (add some padding) // Draw text in container (add some padding)
DrawTextRec(font, text, DrawTextRec(font, text,
(Rectangle){ container.x + 4, container.y + 4, container.width - 4, container.height - 4 }, (Rectangle){ container.x + 4, container.y + 4, container.width - 4, container.height - 4 },
20.0f, 2.0f, wordWrap, GRAY); 20.0f, 2.0f, wordWrap, GRAY);
DrawRectangleRec(resizer, borderColor); // Draw the resize box DrawRectangleRec(resizer, borderColor); // Draw the resize box
@ -106,13 +106,13 @@ int main()
DrawRectangle(0, screenHeight - 54, screenWidth, 54, GRAY); DrawRectangle(0, screenHeight - 54, screenWidth, 54, GRAY);
DrawText("Click hold & drag the to resize the container", 155, screenHeight - 38, 20, RAYWHITE); DrawText("Click hold & drag the to resize the container", 155, screenHeight - 38, 20, RAYWHITE);
DrawRectangleRec((Rectangle){ 382, screenHeight - 34, 12, 12 }, MAROON); DrawRectangleRec((Rectangle){ 382, screenHeight - 34, 12, 12 }, MAROON);
EndDrawing(); EndDrawing();
//---------------------------------------------------------------------------------- //----------------------------------------------------------------------------------
} }
// De-Initialization // De-Initialization
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
CloseWindow(); // Close window and OpenGL context CloseWindow(); // Close window and OpenGL context
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------

View file

@ -11,12 +11,12 @@
#include "raylib.h" #include "raylib.h"
int main() int main(void)
{ {
// Initialization // Initialization
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
int screenWidth = 800; const int screenWidth = 800;
int screenHeight = 450; const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [text] example - sprite fonts usage"); InitWindow(screenWidth, screenHeight, "raylib [text] example - sprite fonts usage");
@ -40,6 +40,7 @@ int main()
fontPosition3.x = screenWidth/2 - MeasureTextEx(font3, msg3, font3.baseSize, 2).x/2; fontPosition3.x = screenWidth/2 - MeasureTextEx(font3, msg3, font3.baseSize, 2).x/2;
fontPosition3.y = screenHeight/2 - font3.baseSize/2 + 50; fontPosition3.y = screenHeight/2 - font3.baseSize/2 + 50;
SetTargetFPS(60); // Set our game to run at 60 frames-per-second
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
// Main game loop // Main game loop

View file

@ -11,22 +11,22 @@
#include "raylib.h" #include "raylib.h"
int main() int main(void)
{ {
// Initialization // Initialization
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
int screenWidth = 800; const int screenWidth = 800;
int screenHeight = 450; const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [text] example - ttf loading"); InitWindow(screenWidth, screenHeight, "raylib [text] example - ttf loading");
const char msg[50] = "TTF Font"; const char msg[50] = "TTF 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)
// TTF Font loading with custom generation parameters // TTF Font loading with custom generation parameters
Font font = LoadFontEx("resources/KAISG.ttf", 96, 0, 0); Font font = LoadFontEx("resources/KAISG.ttf", 96, 0, 0);
// Generate mipmap levels to use trilinear filtering // Generate mipmap levels to use trilinear filtering
// NOTE: On 2D drawing it won't be noticeable, it looks like FILTER_BILINEAR // NOTE: On 2D drawing it won't be noticeable, it looks like FILTER_BILINEAR
GenTextureMipmaps(&font.texture); GenTextureMipmaps(&font.texture);
@ -35,25 +35,20 @@ int main()
Vector2 fontPosition = { 40, screenHeight/2 - 80 }; Vector2 fontPosition = { 40, screenHeight/2 - 80 };
Vector2 textSize; Vector2 textSize;
// Setup texture scaling filter
SetTextureFilter(font.texture, FILTER_POINT); SetTextureFilter(font.texture, FILTER_POINT);
int currentFontFilter = 0; // FILTER_POINT int currentFontFilter = 0; // FILTER_POINT
// NOTE: Drag and drop support only available for desktop platforms: Windows, Linux, OSX SetTargetFPS(60); // Set our game to run at 60 frames-per-second
#if defined(PLATFORM_DESKTOP)
int count = 0;
char **droppedFiles;
#endif
SetTargetFPS(60);
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
// Main game loop // Main game loop
while (!WindowShouldClose()) // Detect window close button or ESC key while (!WindowShouldClose()) // Detect window close button or ESC key
{ {
// Update // Update
//---------------------------------------------------------------------------------- //----------------------------------------------------------------------------------
fontSize += GetMouseWheelMove()*4.0f; fontSize += GetMouseWheelMove()*4.0f;
// Choose font texture filter method // Choose font texture filter method
if (IsKeyPressed(KEY_ONE)) if (IsKeyPressed(KEY_ONE))
{ {
@ -71,18 +66,18 @@ int main()
SetTextureFilter(font.texture, FILTER_TRILINEAR); SetTextureFilter(font.texture, FILTER_TRILINEAR);
currentFontFilter = 2; currentFontFilter = 2;
} }
textSize = MeasureTextEx(font, msg, fontSize, 0); textSize = MeasureTextEx(font, msg, fontSize, 0);
if (IsKeyDown(KEY_LEFT)) fontPosition.x -= 10; if (IsKeyDown(KEY_LEFT)) fontPosition.x -= 10;
else if (IsKeyDown(KEY_RIGHT)) fontPosition.x += 10; else if (IsKeyDown(KEY_RIGHT)) fontPosition.x += 10;
#if defined(PLATFORM_DESKTOP)
// Load a dropped TTF file dynamically (at current fontSize) // Load a dropped TTF file dynamically (at current fontSize)
if (IsFileDropped()) if (IsFileDropped())
{ {
droppedFiles = GetDroppedFiles(&count); int count = 0;
char **droppedFiles = GetDroppedFiles(&count);
if (count == 1) // Only support one ttf file dropped if (count == 1) // Only support one ttf file dropped
{ {
UnloadFont(font); UnloadFont(font);
@ -90,47 +85,45 @@ int main()
ClearDroppedFiles(); ClearDroppedFiles();
} }
} }
#endif
//---------------------------------------------------------------------------------- //----------------------------------------------------------------------------------
// Draw // Draw
//---------------------------------------------------------------------------------- //----------------------------------------------------------------------------------
BeginDrawing(); BeginDrawing();
ClearBackground(RAYWHITE); ClearBackground(RAYWHITE);
DrawText("Use mouse wheel to change font size", 20, 20, 10, GRAY); DrawText("Use mouse wheel to change font size", 20, 20, 10, GRAY);
DrawText("Use KEY_RIGHT and KEY_LEFT to move text", 20, 40, 10, GRAY); DrawText("Use KEY_RIGHT and KEY_LEFT to move text", 20, 40, 10, GRAY);
DrawText("Use 1, 2, 3 to change texture filter", 20, 60, 10, GRAY); DrawText("Use 1, 2, 3 to change texture filter", 20, 60, 10, GRAY);
DrawText("Drop a new TTF font for dynamic loading", 20, 80, 10, DARKGRAY); DrawText("Drop a new TTF font for dynamic loading", 20, 80, 10, DARKGRAY);
DrawTextEx(font, msg, fontPosition, fontSize, 0, BLACK); DrawTextEx(font, msg, fontPosition, fontSize, 0, BLACK);
// TODO: It seems texSize measurement is not accurate due to chars offsets... // TODO: It seems texSize measurement is not accurate due to chars offsets...
//DrawRectangleLines(fontPosition.x, fontPosition.y, textSize.x, textSize.y, RED); //DrawRectangleLines(fontPosition.x, fontPosition.y, textSize.x, textSize.y, RED);
DrawRectangle(0, screenHeight - 80, screenWidth, 80, LIGHTGRAY); DrawRectangle(0, screenHeight - 80, screenWidth, 80, LIGHTGRAY);
DrawText(FormatText("Font size: %02.02f", fontSize), 20, screenHeight - 50, 10, DARKGRAY); DrawText(FormatText("Font size: %02.02f", fontSize), 20, screenHeight - 50, 10, DARKGRAY);
DrawText(FormatText("Text size: [%02.02f, %02.02f]", textSize.x, textSize.y), 20, screenHeight - 30, 10, DARKGRAY); DrawText(FormatText("Text size: [%02.02f, %02.02f]", textSize.x, textSize.y), 20, screenHeight - 30, 10, DARKGRAY);
DrawText("CURRENT TEXTURE FILTER:", 250, 400, 20, GRAY); DrawText("CURRENT TEXTURE FILTER:", 250, 400, 20, GRAY);
if (currentFontFilter == 0) DrawText("POINT", 570, 400, 20, BLACK); if (currentFontFilter == 0) DrawText("POINT", 570, 400, 20, BLACK);
else if (currentFontFilter == 1) DrawText("BILINEAR", 570, 400, 20, BLACK); else if (currentFontFilter == 1) DrawText("BILINEAR", 570, 400, 20, BLACK);
else if (currentFontFilter == 2) DrawText("TRILINEAR", 570, 400, 20, BLACK); else if (currentFontFilter == 2) DrawText("TRILINEAR", 570, 400, 20, BLACK);
EndDrawing(); EndDrawing();
//---------------------------------------------------------------------------------- //----------------------------------------------------------------------------------
} }
// De-Initialization // De-Initialization
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
#if defined(PLATFORM_DESKTOP)
ClearDroppedFiles(); // Clear internal buffers ClearDroppedFiles(); // Clear internal buffers
#endif
UnloadFont(font); // Font unloading UnloadFont(font); // Font unloading
CloseWindow(); // Close window and OpenGL context CloseWindow(); // Close window and OpenGL context
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
return 0; return 0;
} }

View file

@ -139,15 +139,12 @@ static void RandomizeEmoji(void); // Fills the emoji array with random emojis
// Arrays that holds the random emojis // Arrays that holds the random emojis
struct { struct {
int index; // Index inside `emojiCodepoints` int index; // Index inside `emojiCodepoints`
int message; // Message index int message; // Message index
Color color; // Emoji color Color color; // Emoji color
} emoji[EMOJI_PER_WIDTH*EMOJI_PER_HEIGHT] = { 0 }; } emoji[EMOJI_PER_WIDTH*EMOJI_PER_HEIGHT] = { 0 };
static int hovered = -1, selected = -1; static int hovered = -1, selected = -1;
//--------------------------------------------------------------------------------------
// Main entry point
//--------------------------------------------------------------------------------------
int main(int argc, char **argv) int main(int argc, char **argv)
{ {
// Initialization // Initialization
@ -159,23 +156,23 @@ int main(int argc, char **argv)
InitWindow(screenWidth, screenHeight, "raylib [text] example - unicode"); InitWindow(screenWidth, screenHeight, "raylib [text] example - unicode");
// Load the font resources // Load the font resources
// NOTE: fontAsian is for asian languages, // NOTE: fontAsian is for asian languages,
// fontEmoji is the emojis and fontDefault is used for everything else // fontEmoji is the emojis and fontDefault is used for everything else
Font fontDefault = LoadFont("resources/dejavu.fnt"); Font fontDefault = LoadFont("resources/dejavu.fnt");
Font fontAsian = LoadFont("resources/notoCJK.fnt"); Font fontAsian = LoadFont("resources/notoCJK.fnt");
Font fontEmoji = LoadFont("resources/emoji.fnt"); Font fontEmoji = LoadFont("resources/emoji.fnt");
Vector2 hoveredPos = { 0.0f, 0.0f }; Vector2 hoveredPos = { 0.0f, 0.0f };
Vector2 selectedPos = { 0.0f, 0.0f }; Vector2 selectedPos = { 0.0f, 0.0f };
// Set a random set of emojis when starting up // Set a random set of emojis when starting up
RandomizeEmoji(); RandomizeEmoji();
SetTargetFPS(60); SetTargetFPS(60); // Set our game to run at 60 frames-per-second
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
// Main loop // Main loop
while (!WindowShouldClose()) while (!WindowShouldClose()) // Detect window close button or ESC key
{ {
// Update // Update
//---------------------------------------------------------------------------------- //----------------------------------------------------------------------------------
@ -189,89 +186,89 @@ int main(int argc, char **argv)
selectedPos = hoveredPos; selectedPos = hoveredPos;
SetClipboardText(messages[emoji[selected].message].text); SetClipboardText(messages[emoji[selected].message].text);
} }
Vector2 mouse = GetMousePosition(); Vector2 mouse = GetMousePosition();
Vector2 pos = { 28.8f, 10.0f }; Vector2 pos = { 28.8f, 10.0f };
hovered = -1; hovered = -1;
//---------------------------------------------------------------------------------- //----------------------------------------------------------------------------------
// Draw // Draw
//---------------------------------------------------------------------------------- //----------------------------------------------------------------------------------
BeginDrawing(); BeginDrawing();
ClearBackground(RAYWHITE); ClearBackground(RAYWHITE);
// Draw random emojis in the background // Draw random emojis in the background
//------------------------------------------------------------------------------ //------------------------------------------------------------------------------
for (int i = 0; i < SIZEOF(emoji); ++i) for (int i = 0; i < SIZEOF(emoji); ++i)
{ {
const char *txt = &emojiCodepoints[emoji[i].index]; const char *txt = &emojiCodepoints[emoji[i].index];
Rectangle emojiRect = { pos.x, pos.y, fontEmoji.baseSize, fontEmoji.baseSize }; Rectangle emojiRect = { pos.x, pos.y, fontEmoji.baseSize, fontEmoji.baseSize };
if (!CheckCollisionPointRec(mouse, emojiRect)) if (!CheckCollisionPointRec(mouse, emojiRect))
{ {
DrawTextEx(fontEmoji, txt, pos, fontEmoji.baseSize, 1.0, selected == i ? emoji[i].color : Fade(LIGHTGRAY, 0.4f)); DrawTextEx(fontEmoji, txt, pos, fontEmoji.baseSize, 1.0, selected == i ? emoji[i].color : Fade(LIGHTGRAY, 0.4f));
} }
else else
{ {
DrawTextEx(fontEmoji, txt, pos, fontEmoji.baseSize, 1.0, emoji[i].color ); DrawTextEx(fontEmoji, txt, pos, fontEmoji.baseSize, 1.0, emoji[i].color );
hovered = i; hovered = i;
hoveredPos = pos; hoveredPos = pos;
} }
if ((i != 0) && (i%EMOJI_PER_WIDTH == 0)) { pos.y += fontEmoji.baseSize + 24.25f; pos.x = 28.8f; } if ((i != 0) && (i%EMOJI_PER_WIDTH == 0)) { pos.y += fontEmoji.baseSize + 24.25f; pos.x = 28.8f; }
else pos.x += fontEmoji.baseSize + 28.8f; else pos.x += fontEmoji.baseSize + 28.8f;
} }
//------------------------------------------------------------------------------ //------------------------------------------------------------------------------
// Draw the message when a emoji is selected // Draw the message when a emoji is selected
//------------------------------------------------------------------------------ //------------------------------------------------------------------------------
if (selected != -1) if (selected != -1)
{ {
const int message = emoji[selected].message; const int message = emoji[selected].message;
const int horizontalPadding = 20, verticalPadding = 30; const int horizontalPadding = 20, verticalPadding = 30;
Font *font = &fontDefault; Font *font = &fontDefault;
// Set correct font for asian languages // Set correct font for asian languages
if (TextIsEqual(messages[message].language, "Chinese") || if (TextIsEqual(messages[message].language, "Chinese") ||
TextIsEqual(messages[message].language, "Korean") || TextIsEqual(messages[message].language, "Korean") ||
TextIsEqual(messages[message].language, "Japanese")) font = &fontAsian; TextIsEqual(messages[message].language, "Japanese")) font = &fontAsian;
// Calculate size for the message box (approximate the height and width) // Calculate size for the message box (approximate the height and width)
Vector2 sz = MeasureTextEx(*font, messages[message].text, font->baseSize, 1.0f); Vector2 sz = MeasureTextEx(*font, messages[message].text, font->baseSize, 1.0f);
if (sz.x > 300) { sz.y *= sz.x/300; sz.x = 300; } if (sz.x > 300) { sz.y *= sz.x/300; sz.x = 300; }
else if (sz.x < 160) sz.x = 160; else if (sz.x < 160) sz.x = 160;
Rectangle msgRect = { selectedPos.x - 38.8f, selectedPos.y, 2 * horizontalPadding + sz.x, 2 * verticalPadding + sz.y }; Rectangle msgRect = { selectedPos.x - 38.8f, selectedPos.y, 2 * horizontalPadding + sz.x, 2 * verticalPadding + sz.y };
msgRect.y -= msgRect.height; msgRect.y -= msgRect.height;
// Coordinates for the chat bubble triangle // Coordinates for the chat bubble triangle
Vector2 a = { selectedPos.x, msgRect.y + msgRect.height }, b = {a.x + 8, a.y + 10}, c= { a.x + 10, a.y }; Vector2 a = { selectedPos.x, msgRect.y + msgRect.height }, b = {a.x + 8, a.y + 10}, c= { a.x + 10, a.y };
// Don't go outside the screen // Don't go outside the screen
if (msgRect.x < 10) msgRect.x += 28; if (msgRect.x < 10) msgRect.x += 28;
if (msgRect.y < 10) if (msgRect.y < 10)
{ {
msgRect.y = selectedPos.y + 84; msgRect.y = selectedPos.y + 84;
a.y = msgRect.y; a.y = msgRect.y;
c.y = a.y; c.y = a.y;
b.y = a.y - 10; b.y = a.y - 10;
// Swap values so we can actually render the triangle :( // Swap values so we can actually render the triangle :(
Vector2 tmp = a; Vector2 tmp = a;
a = b; a = b;
b = tmp; b = tmp;
} }
if (msgRect.x + msgRect.width > screenWidth) msgRect.x -= (msgRect.x + msgRect.width) - screenWidth + 10; if (msgRect.x + msgRect.width > screenWidth) msgRect.x -= (msgRect.x + msgRect.width) - screenWidth + 10;
// Draw chat bubble // Draw chat bubble
DrawRectangleRec(msgRect, emoji[selected].color); DrawRectangleRec(msgRect, emoji[selected].color);
DrawTriangle(a, b, c, emoji[selected].color); DrawTriangle(a, b, c, emoji[selected].color);
// Draw the main text message // Draw the main text message
Rectangle textRect = { msgRect.x + horizontalPadding/2, msgRect.y + verticalPadding/2, msgRect.width - horizontalPadding, msgRect.height }; Rectangle textRect = { msgRect.x + horizontalPadding/2, msgRect.y + verticalPadding/2, msgRect.width - horizontalPadding, msgRect.height };
DrawTextRec(*font, messages[message].text, textRect, font->baseSize, 1.0f, true, WHITE); DrawTextRec(*font, messages[message].text, textRect, font->baseSize, 1.0f, true, WHITE);
// 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); unsigned int len = TextCountCodepoints(messages[message].text);
@ -281,25 +278,25 @@ int main(int argc, char **argv)
DrawText(info, pos.x, pos.y, 10, RAYWHITE); DrawText(info, pos.x, pos.y, 10, RAYWHITE);
} }
//------------------------------------------------------------------------------ //------------------------------------------------------------------------------
// Draw the info text // Draw the info text
DrawText("These emojis have something to tell you, click each to find out!", (screenWidth - 650)/2, screenHeight - 40, 20, GRAY); DrawText("These emojis have something to tell you, click each to find out!", (screenWidth - 650)/2, screenHeight - 40, 20, GRAY);
DrawText("Each emoji is a unicode character from a font, not a texture... Press [SPACEBAR] to refresh", (screenWidth - 484)/2, screenHeight - 16, 10, GRAY); DrawText("Each emoji is a unicode character from a font, not a texture... Press [SPACEBAR] to refresh", (screenWidth - 484)/2, screenHeight - 16, 10, GRAY);
EndDrawing(); EndDrawing();
//---------------------------------------------------------------------------------- //----------------------------------------------------------------------------------
} }
// De-Initialization // De-Initialization
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
UnloadFont(fontDefault); // Unload font resource UnloadFont(fontDefault); // Unload font resource
UnloadFont(fontAsian); // Unload font resource UnloadFont(fontAsian); // Unload font resource
UnloadFont(fontEmoji); // Unload font resource UnloadFont(fontEmoji); // Unload font resource
CloseWindow(); // Close window and OpenGL context
//--------------------------------------------------------------------------------------
return 0; CloseWindow(); // Close window and OpenGL context
//--------------------------------------------------------------------------------------
return 0;
} }
// Fills the emoji array with random emoji (only those emojis present in fontEmoji) // Fills the emoji array with random emoji (only those emojis present in fontEmoji)
@ -307,16 +304,16 @@ static void RandomizeEmoji(void)
{ {
hovered = selected = -1; hovered = selected = -1;
int start = GetRandomValue(45, 360); int start = GetRandomValue(45, 360);
for (int i = 0; i < SIZEOF(emoji); ++i) for (int i = 0; i < SIZEOF(emoji); ++i)
{ {
// 0-179 emoji codepoints (from emoji char array) each 4bytes + null char // 0-179 emoji codepoints (from emoji char array) each 4bytes + null char
emoji[i].index = GetRandomValue(0, 179)*5; emoji[i].index = GetRandomValue(0, 179)*5;
// Generate a random color for this emoji // Generate a random color for this emoji
Vector3 hsv = {(start*(i + 1))%360, 0.6f, 0.85f}; Vector3 hsv = {(start*(i + 1))%360, 0.6f, 0.85f};
emoji[i].color = Fade(ColorFromHSV(hsv), 0.8f); emoji[i].color = Fade(ColorFromHSV(hsv), 0.8f);
// Set a random message for this emoji // Set a random message for this emoji
emoji[i].message = GetRandomValue(0, SIZEOF(messages) - 1); emoji[i].message = GetRandomValue(0, SIZEOF(messages) - 1);
} }

View file

@ -11,20 +11,20 @@
#include "raylib.h" #include "raylib.h"
int main() int main(void)
{ {
// Initialization // Initialization
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
int screenWidth = 800; const int screenWidth = 800;
int screenHeight = 450; const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [text] example - text writing anim"); InitWindow(screenWidth, screenHeight, "raylib [text] example - text writing anim");
const char message[128] = "This sample illustrates a text writing\nanimation effect! Check it out! ;)"; const char message[128] = "This sample illustrates a text writing\nanimation effect! Check it out! ;)";
int framesCounter = 0; int framesCounter = 0;
SetTargetFPS(60); SetTargetFPS(60); // Set our game to run at 60 frames-per-second
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
// Main game loop // Main game loop
@ -34,7 +34,7 @@ int main()
//---------------------------------------------------------------------------------- //----------------------------------------------------------------------------------
if (IsKeyDown(KEY_SPACE)) framesCounter += 8; if (IsKeyDown(KEY_SPACE)) framesCounter += 8;
else framesCounter++; else framesCounter++;
if (IsKeyPressed(KEY_ENTER)) framesCounter = 0; if (IsKeyPressed(KEY_ENTER)) framesCounter = 0;
//---------------------------------------------------------------------------------- //----------------------------------------------------------------------------------
@ -45,7 +45,7 @@ int main()
ClearBackground(RAYWHITE); ClearBackground(RAYWHITE);
DrawText(TextSubtext(message, 0, framesCounter/10), 210, 160, 20, MAROON); DrawText(TextSubtext(message, 0, framesCounter/10), 210, 160, 20, MAROON);
DrawText("PRESS [ENTER] to RESTART!", 240, 260, 20, LIGHTGRAY); DrawText("PRESS [ENTER] to RESTART!", 240, 260, 20, LIGHTGRAY);
DrawText("PRESS [SPACE] to SPEED UP!", 239, 300, 20, LIGHTGRAY); DrawText("PRESS [SPACE] to SPEED UP!", 239, 300, 20, LIGHTGRAY);
@ -54,7 +54,7 @@ int main()
} }
// De-Initialization // De-Initialization
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
CloseWindow(); // Close window and OpenGL context CloseWindow(); // Close window and OpenGL context
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------

View file

@ -11,26 +11,26 @@
#include "raylib.h" #include "raylib.h"
int main() int main(void)
{ {
// Initialization // Initialization
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
int screenWidth = 800; const int screenWidth = 800;
int screenHeight = 450; const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [textures] example - background scrolling"); InitWindow(screenWidth, screenHeight, "raylib [textures] example - background scrolling");
// NOTE: Be careful, background width must be equal or bigger than screen width // NOTE: Be careful, background width must be equal or bigger than screen width
// if not, texture should be draw more than two times for scrolling effect // if not, texture should be draw more than two times for scrolling effect
Texture2D background = LoadTexture("resources/cyberpunk_street_background.png"); Texture2D background = LoadTexture("resources/cyberpunk_street_background.png");
Texture2D midground = LoadTexture("resources/cyberpunk_street_midground.png"); Texture2D midground = LoadTexture("resources/cyberpunk_street_midground.png");
Texture2D foreground = LoadTexture("resources/cyberpunk_street_foreground.png"); Texture2D foreground = LoadTexture("resources/cyberpunk_street_foreground.png");
float scrollingBack = 0; float scrollingBack = 0;
float scrollingMid = 0; float scrollingMid = 0;
float scrollingFore = 0; float scrollingFore = 0;
SetTargetFPS(60); SetTargetFPS(60); // Set our game to run at 60 frames-per-second
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
// Main game loop // Main game loop
@ -41,7 +41,7 @@ int main()
scrollingBack -= 0.1f; scrollingBack -= 0.1f;
scrollingMid -= 0.5f; scrollingMid -= 0.5f;
scrollingFore -= 1.0f; scrollingFore -= 1.0f;
// NOTE: Texture is scaled twice its size, so it sould be considered on scrolling // NOTE: Texture is scaled twice its size, so it sould be considered on scrolling
if (scrollingBack <= -background.width*2) scrollingBack = 0; if (scrollingBack <= -background.width*2) scrollingBack = 0;
if (scrollingMid <= -midground.width*2) scrollingMid = 0; if (scrollingMid <= -midground.width*2) scrollingMid = 0;
@ -58,15 +58,15 @@ int main()
// NOTE: Texture is scaled twice its size // NOTE: Texture is scaled twice its size
DrawTextureEx(background, (Vector2){ scrollingBack, 20 }, 0.0f, 2.0f, WHITE); DrawTextureEx(background, (Vector2){ scrollingBack, 20 }, 0.0f, 2.0f, WHITE);
DrawTextureEx(background, (Vector2){ background.width*2 + scrollingBack, 20 }, 0.0f, 2.0f, WHITE); DrawTextureEx(background, (Vector2){ background.width*2 + scrollingBack, 20 }, 0.0f, 2.0f, WHITE);
// Draw midground image twice // Draw midground image twice
DrawTextureEx(midground, (Vector2){ scrollingMid, 20 }, 0.0f, 2.0f, WHITE); DrawTextureEx(midground, (Vector2){ scrollingMid, 20 }, 0.0f, 2.0f, WHITE);
DrawTextureEx(midground, (Vector2){ midground.width*2 + scrollingMid, 20 }, 0.0f, 2.0f, WHITE); DrawTextureEx(midground, (Vector2){ midground.width*2 + scrollingMid, 20 }, 0.0f, 2.0f, WHITE);
// Draw foreground image twice // Draw foreground image twice
DrawTextureEx(foreground, (Vector2){ scrollingFore, 70 }, 0.0f, 2.0f, WHITE); DrawTextureEx(foreground, (Vector2){ scrollingFore, 70 }, 0.0f, 2.0f, WHITE);
DrawTextureEx(foreground, (Vector2){ foreground.width*2 + scrollingFore, 70 }, 0.0f, 2.0f, WHITE); DrawTextureEx(foreground, (Vector2){ foreground.width*2 + scrollingFore, 70 }, 0.0f, 2.0f, WHITE);
DrawText("BACKGROUND SCROLLING & PARALLAX", 10, 10, 20, RED); DrawText("BACKGROUND SCROLLING & PARALLAX", 10, 10, 20, RED);
DrawText("(c) Cyberpunk Street Environment by Luis Zuno (@ansimuz)", screenWidth - 330, screenHeight - 20, 10, RAYWHITE); DrawText("(c) Cyberpunk Street Environment by Luis Zuno (@ansimuz)", screenWidth - 330, screenHeight - 20, 10, RAYWHITE);

View file

@ -25,7 +25,7 @@ typedef struct Bunny {
Color color; Color color;
} Bunny; } Bunny;
int main() int main(void)
{ {
// Initialization // Initialization
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
@ -34,13 +34,14 @@ int main()
InitWindow(screenWidth, screenHeight, "raylib [textures] example - bunnymark"); InitWindow(screenWidth, screenHeight, "raylib [textures] example - bunnymark");
// Load bunny texture
Texture2D texBunny = LoadTexture("resources/wabbit_alpha.png"); Texture2D texBunny = LoadTexture("resources/wabbit_alpha.png");
Bunny *bunnies = (Bunny *)malloc(MAX_BUNNIES*sizeof(Bunny)); // Bunnies array Bunny *bunnies = (Bunny *)malloc(MAX_BUNNIES*sizeof(Bunny)); // Bunnies array
int bunniesCount = 0; // Bunnies counter int bunniesCount = 0; // Bunnies counter
SetTargetFPS(60); SetTargetFPS(60); // Set our game to run at 60 frames-per-second
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
// Main game loop // Main game loop
@ -56,8 +57,8 @@ int main()
bunnies[bunniesCount].position = GetMousePosition(); bunnies[bunniesCount].position = GetMousePosition();
bunnies[bunniesCount].speed.x = (float)GetRandomValue(-250, 250)/60.0f; bunnies[bunniesCount].speed.x = (float)GetRandomValue(-250, 250)/60.0f;
bunnies[bunniesCount].speed.y = (float)GetRandomValue(-250, 250)/60.0f; bunnies[bunniesCount].speed.y = (float)GetRandomValue(-250, 250)/60.0f;
bunnies[bunniesCount].color = (Color){ GetRandomValue(50, 240), bunnies[bunniesCount].color = (Color){ GetRandomValue(50, 240),
GetRandomValue(80, 240), GetRandomValue(80, 240),
GetRandomValue(100, 240), 255 }; GetRandomValue(100, 240), 255 };
bunniesCount++; bunniesCount++;
} }
@ -69,9 +70,9 @@ int main()
bunnies[i].position.x += bunnies[i].speed.x; bunnies[i].position.x += bunnies[i].speed.x;
bunnies[i].position.y += bunnies[i].speed.y; bunnies[i].position.y += bunnies[i].speed.y;
if (((bunnies[i].position.x + texBunny.width/2) > GetScreenWidth()) || if (((bunnies[i].position.x + texBunny.width/2) > GetScreenWidth()) ||
((bunnies[i].position.x + texBunny.width/2) < 0)) bunnies[i].speed.x *= -1; ((bunnies[i].position.x + texBunny.width/2) < 0)) bunnies[i].speed.x *= -1;
if (((bunnies[i].position.y + texBunny.height/2) > GetScreenHeight()) || if (((bunnies[i].position.y + texBunny.height/2) > GetScreenHeight()) ||
((bunnies[i].position.y + texBunny.height/2 - 40) < 0)) bunnies[i].speed.y *= -1; ((bunnies[i].position.y + texBunny.height/2 - 40) < 0)) bunnies[i].speed.y *= -1;
} }
//---------------------------------------------------------------------------------- //----------------------------------------------------------------------------------
@ -84,9 +85,9 @@ int main()
for (int i = 0; i < bunniesCount; i++) for (int i = 0; i < bunniesCount; i++)
{ {
// NOTE: When internal batch buffer limit is reached (MAX_BATCH_ELEMENTS), // NOTE: When internal batch buffer limit is reached (MAX_BATCH_ELEMENTS),
// a draw call is launched and buffer starts being filled again; // a draw call is launched and buffer starts being filled again;
// before issuing a draw call, updated vertex data from internal CPU buffer is send to GPU... // before issuing a draw call, updated vertex data from internal CPU buffer is send to GPU...
// Process of sending data is costly and it could happen that GPU data has not been completely // Process of sending data is costly and it could happen that GPU data has not been completely
// processed for drawing while new data is tried to be sent (updating current in-use buffers) // processed for drawing while new data is tried to be sent (updating current in-use buffers)
// it could generates a stall and consequently a frame drop, limiting the number of drawn bunnies // it could generates a stall and consequently a frame drop, limiting the number of drawn bunnies
@ -96,7 +97,7 @@ int main()
DrawRectangle(0, 0, screenWidth, 40, BLACK); DrawRectangle(0, 0, screenWidth, 40, BLACK);
DrawText(FormatText("bunnies: %i", bunniesCount), 120, 10, 20, GREEN); DrawText(FormatText("bunnies: %i", bunniesCount), 120, 10, 20, GREEN);
DrawText(FormatText("batched draw calls: %i", 1 + bunniesCount/MAX_BATCH_ELEMENTS), 320, 10, 20, MAROON); DrawText(FormatText("batched draw calls: %i", 1 + bunniesCount/MAX_BATCH_ELEMENTS), 320, 10, 20, MAROON);
DrawFPS(10, 10); DrawFPS(10, 10);
EndDrawing(); EndDrawing();
@ -106,7 +107,7 @@ int main()
// De-Initialization // De-Initialization
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
free(bunnies); // Unload bunnies data array free(bunnies); // Unload bunnies data array
UnloadTexture(texBunny); // Unload bunny texture UnloadTexture(texBunny); // Unload bunny texture
CloseWindow(); // Close window and OpenGL context CloseWindow(); // Close window and OpenGL context

View file

@ -13,12 +13,12 @@
#include "raylib.h" #include "raylib.h"
int main() int main(void)
{ {
// Initialization // Initialization
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
int screenWidth = 800; const int screenWidth = 800;
int screenHeight = 450; const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [textures] example - image drawing"); InitWindow(screenWidth, screenHeight, "raylib [textures] example - image drawing");
@ -28,26 +28,26 @@ int main()
ImageCrop(&cat, (Rectangle){ 100, 10, 280, 380 }); // Crop an image piece ImageCrop(&cat, (Rectangle){ 100, 10, 280, 380 }); // Crop an image piece
ImageFlipHorizontal(&cat); // Flip cropped image horizontally ImageFlipHorizontal(&cat); // Flip cropped image horizontally
ImageResize(&cat, 150, 200); // Resize flipped-cropped image ImageResize(&cat, 150, 200); // Resize flipped-cropped image
Image parrots = LoadImage("resources/parrots.png"); // Load image in CPU memory (RAM) Image parrots = LoadImage("resources/parrots.png"); // Load image in CPU memory (RAM)
// Draw one image over the other with a scaling of 1.5f // Draw one image over the other with a scaling of 1.5f
ImageDraw(&parrots, cat, (Rectangle){ 0, 0, cat.width, cat.height }, (Rectangle){ 30, 40, cat.width*1.5f, cat.height*1.5f }); ImageDraw(&parrots, cat, (Rectangle){ 0, 0, cat.width, cat.height }, (Rectangle){ 30, 40, cat.width*1.5f, cat.height*1.5f });
ImageCrop(&parrots, (Rectangle){ 0, 50, parrots.width, parrots.height - 100 }); // Crop resulting image ImageCrop(&parrots, (Rectangle){ 0, 50, parrots.width, parrots.height - 100 }); // Crop resulting image
UnloadImage(cat); // Unload image from RAM UnloadImage(cat); // Unload image from RAM
// Load custom font for frawing on image // Load custom font for frawing on image
Font font = LoadFont("resources/custom_jupiter_crash.png"); Font font = LoadFont("resources/custom_jupiter_crash.png");
// Draw over image using custom font // Draw over image using custom font
ImageDrawTextEx(&parrots, (Vector2){ 300, 230 }, font, "PARROTS & CAT", font.baseSize, -2, WHITE); ImageDrawTextEx(&parrots, (Vector2){ 300, 230 }, font, "PARROTS & CAT", font.baseSize, -2, WHITE);
UnloadFont(font); // Unload custom spritefont (already drawn used on image) UnloadFont(font); // Unload custom spritefont (already drawn used on image)
Texture2D texture = LoadTextureFromImage(parrots); // Image converted to texture, uploaded to GPU memory (VRAM) Texture2D texture = LoadTextureFromImage(parrots); // Image converted to texture, uploaded to GPU memory (VRAM)
UnloadImage(parrots); // Once image has been converted to texture and uploaded to VRAM, it can be unloaded from RAM UnloadImage(parrots); // Once image has been converted to texture and uploaded to VRAM, it can be unloaded from RAM
SetTargetFPS(60); SetTargetFPS(60);
//--------------------------------------------------------------------------------------- //---------------------------------------------------------------------------------------

View file

@ -13,12 +13,12 @@
#define NUM_TEXTURES 7 // Currently we have 7 generation algorithms #define NUM_TEXTURES 7 // Currently we have 7 generation algorithms
int main() int main(void)
{ {
// Initialization // Initialization
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
int screenWidth = 800; const int screenWidth = 800;
int screenHeight = 450; const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [textures] example - procedural images generation"); InitWindow(screenWidth, screenHeight, "raylib [textures] example - procedural images generation");
@ -38,7 +38,7 @@ int main()
textures[4] = LoadTextureFromImage(whiteNoise); textures[4] = LoadTextureFromImage(whiteNoise);
textures[5] = LoadTextureFromImage(perlinNoise); textures[5] = LoadTextureFromImage(perlinNoise);
textures[6] = LoadTextureFromImage(cellular); textures[6] = LoadTextureFromImage(cellular);
// Unload image data (CPU RAM) // Unload image data (CPU RAM)
UnloadImage(verticalGradient); UnloadImage(verticalGradient);
UnloadImage(horizontalGradient); UnloadImage(horizontalGradient);
@ -49,10 +49,10 @@ int main()
UnloadImage(cellular); UnloadImage(cellular);
int currentTexture = 0; int currentTexture = 0;
SetTargetFPS(60); SetTargetFPS(60);
//--------------------------------------------------------------------------------------- //---------------------------------------------------------------------------------------
// Main game loop // Main game loop
while (!WindowShouldClose()) while (!WindowShouldClose())
{ {
@ -67,15 +67,15 @@ int main()
// Draw // Draw
//---------------------------------------------------------------------------------- //----------------------------------------------------------------------------------
BeginDrawing(); BeginDrawing();
ClearBackground(RAYWHITE); ClearBackground(RAYWHITE);
DrawTexture(textures[currentTexture], 0, 0, WHITE); DrawTexture(textures[currentTexture], 0, 0, WHITE);
DrawRectangle(30, 400, 325, 30, Fade(SKYBLUE, 0.5f)); DrawRectangle(30, 400, 325, 30, Fade(SKYBLUE, 0.5f));
DrawRectangleLines(30, 400, 325, 30, Fade(WHITE, 0.5f)); DrawRectangleLines(30, 400, 325, 30, Fade(WHITE, 0.5f));
DrawText("MOUSE LEFT BUTTON to CYCLE PROCEDURAL TEXTURES", 40, 410, 10, WHITE); DrawText("MOUSE LEFT BUTTON to CYCLE PROCEDURAL TEXTURES", 40, 410, 10, WHITE);
switch(currentTexture) switch(currentTexture)
{ {
case 0: DrawText("VERTICAL GRADIENT", 560, 10, 20, RAYWHITE); break; case 0: DrawText("VERTICAL GRADIENT", 560, 10, 20, RAYWHITE); break;
@ -87,19 +87,19 @@ int main()
case 6: DrawText("CELLULAR", 670, 10, 20, RAYWHITE); break; case 6: DrawText("CELLULAR", 670, 10, 20, RAYWHITE); break;
default: break; default: break;
} }
EndDrawing(); EndDrawing();
//---------------------------------------------------------------------------------- //----------------------------------------------------------------------------------
} }
// De-Initialization // De-Initialization
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
// Unload textures data (GPU VRAM) // Unload textures data (GPU VRAM)
for (int i = 0; i < NUM_TEXTURES; i++) UnloadTexture(textures[i]); for (int i = 0; i < NUM_TEXTURES; i++) UnloadTexture(textures[i]);
CloseWindow(); // Close window and OpenGL context CloseWindow(); // Close window and OpenGL context
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
return 0; return 0;
} }

View file

@ -13,12 +13,12 @@
#include "raylib.h" #include "raylib.h"
int main() int main(void)
{ {
// Initialization // Initialization
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
int screenWidth = 800; const int screenWidth = 800;
int screenHeight = 450; const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [textures] example - image loading"); InitWindow(screenWidth, screenHeight, "raylib [textures] example - image loading");

View file

@ -13,19 +13,19 @@
#include "raylib.h" #include "raylib.h"
#include <stdlib.h> // Required for: free() #include <stdlib.h> // Required for: free()
#define NUM_PROCESSES 8 #define NUM_PROCESSES 8
typedef enum { typedef enum {
NONE = 0, NONE = 0,
COLOR_GRAYSCALE, COLOR_GRAYSCALE,
COLOR_TINT, COLOR_TINT,
COLOR_INVERT, COLOR_INVERT,
COLOR_CONTRAST, COLOR_CONTRAST,
COLOR_BRIGHTNESS, COLOR_BRIGHTNESS,
FLIP_VERTICAL, FLIP_VERTICAL,
FLIP_HORIZONTAL FLIP_HORIZONTAL
} ImageProcess; } ImageProcess;
static const char *processText[] = { static const char *processText[] = {
@ -39,12 +39,12 @@ static const char *processText[] = {
"FLIP HORIZONTAL" "FLIP HORIZONTAL"
}; };
int main() int main(void)
{ {
// Initialization // Initialization
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
int screenWidth = 800; const int screenWidth = 800;
int screenHeight = 450; const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [textures] example - image processing"); InitWindow(screenWidth, screenHeight, "raylib [textures] example - image processing");
@ -58,9 +58,9 @@ int main()
bool textureReload = false; bool textureReload = false;
Rectangle selectRecs[NUM_PROCESSES]; Rectangle selectRecs[NUM_PROCESSES];
for (int i = 0; i < NUM_PROCESSES; i++) selectRecs[i] = (Rectangle){ 40.0f, (float)(50 + 32*i), 150.0f, 30.0f }; for (int i = 0; i < NUM_PROCESSES; i++) selectRecs[i] = (Rectangle){ 40.0f, (float)(50 + 32*i), 150.0f, 30.0f };
SetTargetFPS(60); SetTargetFPS(60);
//--------------------------------------------------------------------------------------- //---------------------------------------------------------------------------------------
@ -81,14 +81,14 @@ int main()
if (currentProcess < 0) currentProcess = 7; if (currentProcess < 0) currentProcess = 7;
textureReload = true; textureReload = true;
} }
if (textureReload) if (textureReload)
{ {
UnloadImage(image); // Unload current image data UnloadImage(image); // Unload current image data
image = LoadImage("resources/parrots.png"); // Re-load image data image = LoadImage("resources/parrots.png"); // Re-load image data
// NOTE: Image processing is a costly CPU process to be done every frame, // NOTE: Image processing is a costly CPU process to be done every frame,
// If image processing is required in a frame-basis, it should be done // If image processing is required in a frame-basis, it should be done
// with a texture and by shaders // with a texture and by shaders
switch (currentProcess) switch (currentProcess)
{ {
@ -101,11 +101,11 @@ int main()
case FLIP_HORIZONTAL: ImageFlipHorizontal(&image); break; case FLIP_HORIZONTAL: ImageFlipHorizontal(&image); break;
default: break; default: break;
} }
Color *pixels = GetImageData(image); // Get pixel data from image (RGBA 32bit) Color *pixels = GetImageData(image); // Get pixel data from image (RGBA 32bit)
UpdateTexture(texture, pixels); // Update texture with new image data UpdateTexture(texture, pixels); // Update texture with new image data
free(pixels); // Unload pixels data from RAM free(pixels); // Unload pixels data from RAM
textureReload = false; textureReload = false;
} }
//---------------------------------------------------------------------------------- //----------------------------------------------------------------------------------
@ -115,9 +115,9 @@ int main()
BeginDrawing(); BeginDrawing();
ClearBackground(RAYWHITE); ClearBackground(RAYWHITE);
DrawText("IMAGE PROCESSING:", 40, 30, 10, DARKGRAY); DrawText("IMAGE PROCESSING:", 40, 30, 10, DARKGRAY);
// Draw rectangles // Draw rectangles
for (int i = 0; i < NUM_PROCESSES; i++) for (int i = 0; i < NUM_PROCESSES; i++)
{ {
@ -128,7 +128,7 @@ int main()
DrawTexture(texture, screenWidth - texture.width - 60, screenHeight/2 - texture.height/2, WHITE); DrawTexture(texture, screenWidth - texture.width - 60, screenHeight/2 - texture.height/2, WHITE);
DrawRectangleLines(screenWidth - texture.width - 60, screenHeight/2 - texture.height/2, texture.width, texture.height, BLACK); DrawRectangleLines(screenWidth - texture.width - 60, screenHeight/2 - texture.height/2, texture.width, texture.height, BLACK);
EndDrawing(); EndDrawing();
//---------------------------------------------------------------------------------- //----------------------------------------------------------------------------------
} }

View file

@ -11,28 +11,28 @@
#include "raylib.h" #include "raylib.h"
int main() int main(void)
{ {
// Initialization // Initialization
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
int screenWidth = 800; const int screenWidth = 800;
int screenHeight = 450; const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [texture] example - image text drawing"); InitWindow(screenWidth, screenHeight, "raylib [texture] example - image text drawing");
Image parrots = LoadImage("resources/parrots.png"); // Load image in CPU memory (RAM)
// TTF Font loading with custom generation parameters // TTF Font loading with custom generation parameters
Font font = LoadFontEx("resources/KAISG.ttf", 64, 0, 0); Font font = LoadFontEx("resources/KAISG.ttf", 64, 0, 0);
Image parrots = LoadImage("resources/parrots.png"); // Load image in CPU memory (RAM)
// Draw over image using custom font // Draw over image using custom font
ImageDrawTextEx(&parrots, (Vector2){ 20.0f, 20.0f }, font, "[Parrots font drawing]", (float)font.baseSize, 0.0f, RED); ImageDrawTextEx(&parrots, (Vector2){ 20.0f, 20.0f }, font, "[Parrots font drawing]", (float)font.baseSize, 0.0f, RED);
Texture2D texture = LoadTextureFromImage(parrots); // Image converted to texture, uploaded to GPU memory (VRAM) Texture2D texture = LoadTextureFromImage(parrots); // Image converted to texture, uploaded to GPU memory (VRAM)
UnloadImage(parrots); // Once image has been converted to texture and uploaded to VRAM, it can be unloaded from RAM UnloadImage(parrots); // Once image has been converted to texture and uploaded to VRAM, it can be unloaded from RAM
Vector2 position = { (float)(screenWidth/2 - texture.width/2), (float)(screenHeight/2 - texture.height/2 - 20) }; Vector2 position = { (float)(screenWidth/2 - texture.width/2), (float)(screenHeight/2 - texture.height/2 - 20) };
bool showFont = false; bool showFont = false;
SetTargetFPS(60); SetTargetFPS(60);
@ -57,15 +57,15 @@ int main()
{ {
// Draw texture with text already drawn inside // Draw texture with text already drawn inside
DrawTextureV(texture, position, WHITE); DrawTextureV(texture, position, WHITE);
// Draw text directly using sprite font // Draw text directly using sprite font
DrawTextEx(font, "[Parrots font drawing]", (Vector2){ position.x + 20, DrawTextEx(font, "[Parrots font drawing]", (Vector2){ position.x + 20,
position.y + 20 + 280 }, (float)font.baseSize, 0.0f, WHITE); position.y + 20 + 280 }, (float)font.baseSize, 0.0f, WHITE);
} }
else DrawTexture(font.texture, screenWidth/2 - font.texture.width/2, 50, BLACK); else DrawTexture(font.texture, screenWidth/2 - font.texture.width/2, 50, BLACK);
DrawText("PRESS SPACE to SEE USED SPRITEFONT ", 290, 420, 10, DARKGRAY); DrawText("PRESS SPACE to SEE USED SPRITEFONT ", 290, 420, 10, DARKGRAY);
EndDrawing(); EndDrawing();
//---------------------------------------------------------------------------------- //----------------------------------------------------------------------------------
} }
@ -73,9 +73,9 @@ int main()
// De-Initialization // De-Initialization
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
UnloadTexture(texture); // Texture unloading UnloadTexture(texture); // Texture unloading
UnloadFont(font); // Unload custom spritefont UnloadFont(font); // Unload custom spritefont
CloseWindow(); // Close window and OpenGL context CloseWindow(); // Close window and OpenGL context
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------

View file

@ -11,12 +11,12 @@
#include "raylib.h" #include "raylib.h"
int main() int main(void)
{ {
// Initialization // Initialization
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
int screenWidth = 800; const int screenWidth = 800;
int screenHeight = 450; const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [textures] example - texture loading and drawing"); InitWindow(screenWidth, screenHeight, "raylib [textures] example - texture loading and drawing");

View file

@ -15,18 +15,18 @@
#include "raylib.h" #include "raylib.h"
int main() int main(void)
{ {
// Initialization // Initialization
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
int screenWidth = 800; const int screenWidth = 800;
int screenHeight = 450; const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [textures] example - N-patch drawing"); InitWindow(screenWidth, screenHeight, "raylib [textures] example - N-patch drawing");
// NOTE: Textures MUST be loaded after Window initialization (OpenGL context is required) // NOTE: Textures MUST be loaded after Window initialization (OpenGL context is required)
Texture2D nPatchTexture = LoadTexture("resources/ninepatch_button.png"); Texture2D nPatchTexture = LoadTexture("resources/ninepatch_button.png");
Vector2 mousePosition = { 0 }; Vector2 mousePosition = { 0 };
Vector2 origin = { 0.0f, 0.0f }; Vector2 origin = { 0.0f, 0.0f };
@ -39,13 +39,13 @@ int main()
// A 9-patch (NPT_9PATCH) changes its sizes in both axis // A 9-patch (NPT_9PATCH) changes its sizes in both axis
NPatchInfo ninePatchInfo1 = { (Rectangle){ 0.0f, 0.0f, 64.0f, 64.0f }, 12, 40, 12, 12, NPT_9PATCH }; NPatchInfo ninePatchInfo1 = { (Rectangle){ 0.0f, 0.0f, 64.0f, 64.0f }, 12, 40, 12, 12, NPT_9PATCH };
NPatchInfo ninePatchInfo2 = { (Rectangle){ 0.0f, 128.0f, 64.0f, 64.0f }, 16, 16, 16, 16, NPT_9PATCH }; NPatchInfo ninePatchInfo2 = { (Rectangle){ 0.0f, 128.0f, 64.0f, 64.0f }, 16, 16, 16, 16, NPT_9PATCH };
// A horizontal 3-patch (NPT_3PATCH_HORIZONTAL) changes its sizes along the x axis only // A horizontal 3-patch (NPT_3PATCH_HORIZONTAL) changes its sizes along the x axis only
NPatchInfo h3PatchInfo = { (Rectangle){ 0.0f, 64.0f, 64.0f, 64.0f }, 8, 8, 8, 8, NPT_3PATCH_HORIZONTAL }; NPatchInfo h3PatchInfo = { (Rectangle){ 0.0f, 64.0f, 64.0f, 64.0f }, 8, 8, 8, 8, NPT_3PATCH_HORIZONTAL };
// A vertical 3-patch (NPT_3PATCH_VERTICAL) changes its sizes along the y axis only // A vertical 3-patch (NPT_3PATCH_VERTICAL) changes its sizes along the y axis only
NPatchInfo v3PatchInfo = { (Rectangle){ 0.0f, 192.0f, 64.0f, 64.0f }, 6, 6, 6, 6, NPT_3PATCH_VERTICAL }; NPatchInfo v3PatchInfo = { (Rectangle){ 0.0f, 192.0f, 64.0f, 64.0f }, 6, 6, 6, 6, NPT_3PATCH_VERTICAL };
SetTargetFPS(60); SetTargetFPS(60);
//--------------------------------------------------------------------------------------- //---------------------------------------------------------------------------------------
@ -55,7 +55,7 @@ int main()
// Update // Update
//---------------------------------------------------------------------------------- //----------------------------------------------------------------------------------
mousePosition = GetMousePosition(); mousePosition = GetMousePosition();
// Resize the n-patches based on mouse position // Resize the n-patches based on mouse position
dstRec1.width = mousePosition.x - dstRec1.x; dstRec1.width = mousePosition.x - dstRec1.x;
dstRec1.height = mousePosition.y - dstRec1.y; dstRec1.height = mousePosition.y - dstRec1.y;
@ -86,7 +86,7 @@ int main()
DrawTextureNPatch(nPatchTexture, ninePatchInfo1, dstRec1, origin, 0.0f, WHITE); DrawTextureNPatch(nPatchTexture, ninePatchInfo1, dstRec1, origin, 0.0f, WHITE);
DrawTextureNPatch(nPatchTexture, h3PatchInfo, dstRecH, origin, 0.0f, WHITE); DrawTextureNPatch(nPatchTexture, h3PatchInfo, dstRecH, origin, 0.0f, WHITE);
DrawTextureNPatch(nPatchTexture, v3PatchInfo, dstRecV, origin, 0.0f, WHITE); DrawTextureNPatch(nPatchTexture, v3PatchInfo, dstRecV, origin, 0.0f, WHITE);
// Draw the source texture // Draw the source texture
DrawRectangleLines(5, 88, 74, 266, BLUE); DrawRectangleLines(5, 88, 74, 266, BLUE);
DrawTexture(nPatchTexture, 10, 93, WHITE); DrawTexture(nPatchTexture, 10, 93, WHITE);

View file

@ -23,18 +23,18 @@ typedef struct {
bool active; // NOTE: Use it to activate/deactive particle bool active; // NOTE: Use it to activate/deactive particle
} Particle; } Particle;
int main() int main(void)
{ {
// Initialization // Initialization
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
int screenWidth = 800; const int screenWidth = 800;
int screenHeight = 450; const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [textures] example - particles blending"); InitWindow(screenWidth, screenHeight, "raylib [textures] example - particles blending");
// Particles pool, reuse them! // Particles pool, reuse them!
Particle mouseTail[MAX_PARTICLES]; Particle mouseTail[MAX_PARTICLES];
// Initialize particles // Initialize particles
for (int i = 0; i < MAX_PARTICLES; i++) for (int i = 0; i < MAX_PARTICLES; i++)
{ {
@ -45,13 +45,13 @@ int main()
mouseTail[i].rotation = (float)GetRandomValue(0, 360); mouseTail[i].rotation = (float)GetRandomValue(0, 360);
mouseTail[i].active = false; mouseTail[i].active = false;
} }
float gravity = 3.0f; float gravity = 3.0f;
Texture2D smoke = LoadTexture("resources/smoke.png"); Texture2D smoke = LoadTexture("resources/smoke.png");
int blending = BLEND_ALPHA; int blending = BLEND_ALPHA;
SetTargetFPS(60); SetTargetFPS(60);
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
@ -60,7 +60,7 @@ int main()
{ {
// Update // Update
//---------------------------------------------------------------------------------- //----------------------------------------------------------------------------------
// Activate one particle every frame and Update active particles // Activate one particle every frame and Update active particles
// NOTE: Particles initial position should be mouse position when activated // NOTE: Particles initial position should be mouse position when activated
// NOTE: Particles fall down with gravity and rotation... and disappear after 2 seconds (alpha = 0) // NOTE: Particles fall down with gravity and rotation... and disappear after 2 seconds (alpha = 0)
@ -82,13 +82,13 @@ int main()
{ {
mouseTail[i].position.y += gravity; mouseTail[i].position.y += gravity;
mouseTail[i].alpha -= 0.01f; mouseTail[i].alpha -= 0.01f;
if (mouseTail[i].alpha <= 0.0f) mouseTail[i].active = false; if (mouseTail[i].alpha <= 0.0f) mouseTail[i].active = false;
mouseTail[i].rotation += 5.0f; mouseTail[i].rotation += 5.0f;
} }
} }
if (IsKeyPressed(KEY_SPACE)) if (IsKeyPressed(KEY_SPACE))
{ {
if (blending == BLEND_ALPHA) blending = BLEND_ADDITIVE; if (blending == BLEND_ALPHA) blending = BLEND_ADDITIVE;
@ -101,25 +101,25 @@ int main()
BeginDrawing(); BeginDrawing();
ClearBackground(DARKGRAY); ClearBackground(DARKGRAY);
BeginBlendMode(blending); BeginBlendMode(blending);
// Draw active particles // Draw active particles
for (int i = 0; i < MAX_PARTICLES; i++) for (int i = 0; i < MAX_PARTICLES; i++)
{ {
if (mouseTail[i].active) DrawTexturePro(smoke, (Rectangle){ 0.0f, 0.0f, (float)smoke.width, (float)smoke.height }, if (mouseTail[i].active) DrawTexturePro(smoke, (Rectangle){ 0.0f, 0.0f, (float)smoke.width, (float)smoke.height },
(Rectangle){ mouseTail[i].position.x, mouseTail[i].position.y, smoke.width*mouseTail[i].size, smoke.height*mouseTail[i].size }, (Rectangle){ mouseTail[i].position.x, mouseTail[i].position.y, smoke.width*mouseTail[i].size, smoke.height*mouseTail[i].size },
(Vector2){ (float)(smoke.width*mouseTail[i].size/2.0f), (float)(smoke.height*mouseTail[i].size/2.0f) }, mouseTail[i].rotation, (Vector2){ (float)(smoke.width*mouseTail[i].size/2.0f), (float)(smoke.height*mouseTail[i].size/2.0f) }, mouseTail[i].rotation,
Fade(mouseTail[i].color, mouseTail[i].alpha)); Fade(mouseTail[i].color, mouseTail[i].alpha));
} }
EndBlendMode(); EndBlendMode();
DrawText("PRESS SPACE to CHANGE BLENDING MODE", 180, 20, 20, BLACK); DrawText("PRESS SPACE to CHANGE BLENDING MODE", 180, 20, 20, BLACK);
if (blending == BLEND_ALPHA) DrawText("ALPHA BLENDING", 290, screenHeight - 40, 20, BLACK); if (blending == BLEND_ALPHA) DrawText("ALPHA BLENDING", 290, screenHeight - 40, 20, BLACK);
else DrawText("ADDITIVE BLENDING", 280, screenHeight - 40, 20, RAYWHITE); else DrawText("ADDITIVE BLENDING", 280, screenHeight - 40, 20, RAYWHITE);
EndDrawing(); EndDrawing();
//---------------------------------------------------------------------------------- //----------------------------------------------------------------------------------
} }
@ -127,7 +127,7 @@ int main()
// De-Initialization // De-Initialization
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
UnloadTexture(smoke); UnloadTexture(smoke);
CloseWindow(); // Close window and OpenGL context CloseWindow(); // Close window and OpenGL context
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------

View file

@ -13,31 +13,31 @@
#include "raylib.h" #include "raylib.h"
#include <stdlib.h> // Required for malloc() and free() #include <stdlib.h> // Required for: malloc() and free()
int main() int main(void)
{ {
// Initialization // Initialization
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
int screenWidth = 800; const int screenWidth = 800;
int screenHeight = 450; const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [textures] example - texture from raw data"); InitWindow(screenWidth, screenHeight, "raylib [textures] example - texture from raw data");
// NOTE: Textures MUST be loaded after Window initialization (OpenGL context is required) // NOTE: Textures MUST be loaded after Window initialization (OpenGL context is required)
// Load RAW image data (512x512, 32bit RGBA, no file header) // Load RAW image data (512x512, 32bit RGBA, no file header)
Image fudesumiRaw = LoadImageRaw("resources/fudesumi.raw", 384, 512, UNCOMPRESSED_R8G8B8A8, 0); Image fudesumiRaw = LoadImageRaw("resources/fudesumi.raw", 384, 512, UNCOMPRESSED_R8G8B8A8, 0);
Texture2D fudesumi = LoadTextureFromImage(fudesumiRaw); // Upload CPU (RAM) image to GPU (VRAM) Texture2D fudesumi = LoadTextureFromImage(fudesumiRaw); // Upload CPU (RAM) image to GPU (VRAM)
UnloadImage(fudesumiRaw); // Unload CPU (RAM) image data UnloadImage(fudesumiRaw); // Unload CPU (RAM) image data
// Generate a checked texture by code (1024x1024 pixels) // Generate a checked texture by code (1024x1024 pixels)
int width = 960; int width = 960;
int height = 480; int height = 480;
// Dynamic memory allocation to store pixels data (Color type) // Dynamic memory allocation to store pixels data (Color type)
Color *pixels = (Color *)malloc(width*height*sizeof(Color)); Color *pixels = (Color *)malloc(width*height*sizeof(Color));
for (int y = 0; y < height; y++) for (int y = 0; y < height; y++)
{ {
for (int x = 0; x < width; x++) for (int x = 0; x < width; x++)
@ -46,14 +46,14 @@ int main()
else pixels[y*width + x] = GOLD; else pixels[y*width + x] = GOLD;
} }
} }
// Load pixels data into an image structure and create texture // Load pixels data into an image structure and create texture
Image checkedIm = LoadImageEx(pixels, width, height); Image checkedIm = LoadImageEx(pixels, width, height);
Texture2D checked = LoadTextureFromImage(checkedIm); Texture2D checked = LoadTextureFromImage(checkedIm);
UnloadImage(checkedIm); // Unload CPU (RAM) image data UnloadImage(checkedIm); // Unload CPU (RAM) image data
// Dynamic memory must be freed after using it // Dynamic memory must be freed after using it
free(pixels); // Unload CPU (RAM) pixels data free(pixels); // Unload CPU (RAM) pixels data
//--------------------------------------------------------------------------------------- //---------------------------------------------------------------------------------------
// Main game loop // Main game loop
@ -76,7 +76,7 @@ int main()
DrawText("CHECKED TEXTURE ", 84, 85, 30, BROWN); DrawText("CHECKED TEXTURE ", 84, 85, 30, BROWN);
DrawText("GENERATED by CODE", 72, 148, 30, BROWN); DrawText("GENERATED by CODE", 72, 148, 30, BROWN);
DrawText("and RAW IMAGE LOADING", 46, 210, 30, BROWN); DrawText("and RAW IMAGE LOADING", 46, 210, 30, BROWN);
DrawText("(c) Fudesumi sprite by Eiden Marsal", 310, screenHeight - 20, 10, BROWN); DrawText("(c) Fudesumi sprite by Eiden Marsal", 310, screenHeight - 20, 10, BROWN);
EndDrawing(); EndDrawing();

View file

@ -14,12 +14,12 @@
#define MAX_FRAME_SPEED 15 #define MAX_FRAME_SPEED 15
#define MIN_FRAME_SPEED 1 #define MIN_FRAME_SPEED 1
int main() int main(void)
{ {
// Initialization // Initialization
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
int screenWidth = 800; const int screenWidth = 800;
int screenHeight = 450; const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [texture] example - texture rectangle"); InitWindow(screenWidth, screenHeight, "raylib [texture] example - texture rectangle");
@ -29,10 +29,10 @@ int main()
Vector2 position = { 350.0f, 280.0f }; Vector2 position = { 350.0f, 280.0f };
Rectangle frameRec = { 0.0f, 0.0f, (float)scarfy.width/6, (float)scarfy.height }; Rectangle frameRec = { 0.0f, 0.0f, (float)scarfy.width/6, (float)scarfy.height };
int currentFrame = 0; int currentFrame = 0;
int framesCounter = 0; int framesCounter = 0;
int framesSpeed = 8; // Number of spritesheet frames shown by second int framesSpeed = 8; // Number of spritesheet frames shown by second
SetTargetFPS(60); // Set our game to run at 60 frames-per-second SetTargetFPS(60); // Set our game to run at 60 frames-per-second
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
@ -42,20 +42,20 @@ int main()
// Update // Update
//---------------------------------------------------------------------------------- //----------------------------------------------------------------------------------
framesCounter++; framesCounter++;
if (framesCounter >= (60/framesSpeed)) if (framesCounter >= (60/framesSpeed))
{ {
framesCounter = 0; framesCounter = 0;
currentFrame++; currentFrame++;
if (currentFrame > 5) currentFrame = 0; if (currentFrame > 5) currentFrame = 0;
frameRec.x = (float)currentFrame*(float)scarfy.width/6; frameRec.x = (float)currentFrame*(float)scarfy.width/6;
} }
if (IsKeyPressed(KEY_RIGHT)) framesSpeed++; if (IsKeyPressed(KEY_RIGHT)) framesSpeed++;
else if (IsKeyPressed(KEY_LEFT)) framesSpeed--; else if (IsKeyPressed(KEY_LEFT)) framesSpeed--;
if (framesSpeed > MAX_FRAME_SPEED) framesSpeed = MAX_FRAME_SPEED; if (framesSpeed > MAX_FRAME_SPEED) framesSpeed = MAX_FRAME_SPEED;
else if (framesSpeed < MIN_FRAME_SPEED) framesSpeed = MIN_FRAME_SPEED; else if (framesSpeed < MIN_FRAME_SPEED) framesSpeed = MIN_FRAME_SPEED;
//---------------------------------------------------------------------------------- //----------------------------------------------------------------------------------
@ -69,17 +69,17 @@ int main()
DrawTexture(scarfy, 15, 40, WHITE); DrawTexture(scarfy, 15, 40, WHITE);
DrawRectangleLines(15, 40, scarfy.width, scarfy.height, LIME); DrawRectangleLines(15, 40, scarfy.width, scarfy.height, LIME);
DrawRectangleLines(15 + frameRec.x, 40 + frameRec.y, frameRec.width, frameRec.height, RED); DrawRectangleLines(15 + frameRec.x, 40 + frameRec.y, frameRec.width, frameRec.height, RED);
DrawText("FRAME SPEED: ", 165, 210, 10, DARKGRAY); DrawText("FRAME SPEED: ", 165, 210, 10, DARKGRAY);
DrawText(FormatText("%02i FPS", framesSpeed), 575, 210, 10, DARKGRAY); DrawText(FormatText("%02i FPS", framesSpeed), 575, 210, 10, DARKGRAY);
DrawText("PRESS RIGHT/LEFT KEYS to CHANGE SPEED!", 290, 240, 10, DARKGRAY); DrawText("PRESS RIGHT/LEFT KEYS to CHANGE SPEED!", 290, 240, 10, DARKGRAY);
for (int i = 0; i < MAX_FRAME_SPEED; i++) for (int i = 0; i < MAX_FRAME_SPEED; i++)
{ {
if (i < framesSpeed) DrawRectangle(250 + 21*i, 205, 20, 20, RED); if (i < framesSpeed) DrawRectangle(250 + 21*i, 205, 20, 20, RED);
DrawRectangleLines(250 + 21*i, 205, 20, 20, MAROON); DrawRectangleLines(250 + 21*i, 205, 20, 20, MAROON);
} }
DrawTextureRec(scarfy, frameRec, position, WHITE); // Draw part of the texture DrawTextureRec(scarfy, frameRec, position, WHITE); // Draw part of the texture
DrawText("(c) Scarfy sprite by Eiden Marsal", screenWidth - 200, screenHeight - 20, 10, GRAY); DrawText("(c) Scarfy sprite by Eiden Marsal", screenWidth - 200, screenHeight - 20, 10, GRAY);

View file

@ -13,35 +13,35 @@
#define NUM_FRAMES 3 // Number of frames (rectangles) for the button sprite texture #define NUM_FRAMES 3 // Number of frames (rectangles) for the button sprite texture
int main() int main(void)
{ {
// Initialization // Initialization
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
const int screenWidth = 800; const int screenWidth = 800;
const int screenHeight = 450; const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [textures] example - sprite button"); InitWindow(screenWidth, screenHeight, "raylib [textures] example - sprite button");
InitAudioDevice(); // Initialize audio device InitAudioDevice(); // Initialize audio device
Sound fxButton = LoadSound("resources/buttonfx.wav"); // Load button sound Sound fxButton = LoadSound("resources/buttonfx.wav"); // Load button sound
Texture2D button = LoadTexture("resources/button.png"); // Load button texture Texture2D button = LoadTexture("resources/button.png"); // Load button texture
// Define frame rectangle for drawing // Define frame rectangle for drawing
int frameHeight = button.height/NUM_FRAMES; int frameHeight = button.height/NUM_FRAMES;
Rectangle sourceRec = { 0, 0, button.width, frameHeight }; Rectangle sourceRec = { 0, 0, button.width, frameHeight };
// Define button bounds on screen // Define button bounds on screen
Rectangle btnBounds = { screenWidth/2 - button.width/2, screenHeight/2 - button.height/NUM_FRAMES/2, button.width, frameHeight }; Rectangle btnBounds = { screenWidth/2 - button.width/2, screenHeight/2 - button.height/NUM_FRAMES/2, button.width, frameHeight };
int btnState = 0; // Button state: 0-NORMAL, 1-MOUSE_HOVER, 2-PRESSED int btnState = 0; // Button state: 0-NORMAL, 1-MOUSE_HOVER, 2-PRESSED
bool btnAction = false; // Button action should be activated bool btnAction = false; // Button action should be activated
Vector2 mousePoint = { 0.0f, 0.0f }; Vector2 mousePoint = { 0.0f, 0.0f };
SetTargetFPS(60); SetTargetFPS(60);
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
// Main game loop // Main game loop
while (!WindowShouldClose()) // Detect window close button or ESC key while (!WindowShouldClose()) // Detect window close button or ESC key
{ {
@ -49,7 +49,7 @@ int main()
//---------------------------------------------------------------------------------- //----------------------------------------------------------------------------------
mousePoint = GetMousePosition(); mousePoint = GetMousePosition();
btnAction = false; btnAction = false;
// Check button state // Check button state
if (CheckCollisionPointRec(mousePoint, btnBounds)) if (CheckCollisionPointRec(mousePoint, btnBounds))
{ {
@ -59,26 +59,26 @@ int main()
if (IsMouseButtonReleased(MOUSE_LEFT_BUTTON)) btnAction = true; if (IsMouseButtonReleased(MOUSE_LEFT_BUTTON)) btnAction = true;
} }
else btnState = 0; else btnState = 0;
if (btnAction) if (btnAction)
{ {
PlaySound(fxButton); PlaySound(fxButton);
// TODO: Any desired action // TODO: Any desired action
} }
// Calculate button frame rectangle to draw depending on button state // Calculate button frame rectangle to draw depending on button state
sourceRec.y = btnState*frameHeight; sourceRec.y = btnState*frameHeight;
//---------------------------------------------------------------------------------- //----------------------------------------------------------------------------------
// Draw // Draw
//---------------------------------------------------------------------------------- //----------------------------------------------------------------------------------
BeginDrawing(); BeginDrawing();
ClearBackground(RAYWHITE); ClearBackground(RAYWHITE);
DrawTextureRec(button, sourceRec, (Vector2){ btnBounds.x, btnBounds.y }, WHITE); // Draw button frame DrawTextureRec(button, sourceRec, (Vector2){ btnBounds.x, btnBounds.y }, WHITE); // Draw button frame
EndDrawing(); EndDrawing();
//---------------------------------------------------------------------------------- //----------------------------------------------------------------------------------
} }
@ -89,9 +89,9 @@ int main()
UnloadSound(fxButton); // Unload sound UnloadSound(fxButton); // Unload sound
CloseAudioDevice(); // Close audio device CloseAudioDevice(); // Close audio device
CloseWindow(); // Close window and OpenGL context CloseWindow(); // Close window and OpenGL context
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
return 0; return 0;
} }

View file

@ -11,23 +11,23 @@
#include "raylib.h" #include "raylib.h"
#define NUM_FRAMES 8 #define NUM_FRAMES 8
#define NUM_LINES 6 #define NUM_LINES 6
int main() int main(void)
{ {
// Initialization // Initialization
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
const int screenWidth = 800; const int screenWidth = 800;
const int screenHeight = 450; const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [textures] example - sprite explosion"); InitWindow(screenWidth, screenHeight, "raylib [textures] example - sprite explosion");
InitAudioDevice(); InitAudioDevice();
// Load explosion sound // Load explosion sound
Sound fxBoom = LoadSound("resources/boom.wav"); Sound fxBoom = LoadSound("resources/boom.wav");
// Load explosion texture // Load explosion texture
Texture2D explosion = LoadTexture("resources/explosion.png"); Texture2D explosion = LoadTexture("resources/explosion.png");
@ -36,72 +36,72 @@ int main()
int frameHeight = explosion.height/NUM_LINES; // Sprite one frame rectangle height int frameHeight = explosion.height/NUM_LINES; // Sprite one frame rectangle height
int currentFrame = 0; int currentFrame = 0;
int currentLine = 0; int currentLine = 0;
Rectangle frameRec = { 0, 0, frameWidth, frameHeight }; Rectangle frameRec = { 0, 0, frameWidth, frameHeight };
Vector2 position = { 0, 0 }; Vector2 position = { 0, 0 };
bool active = false; bool active = false;
int framesCounter = 0; int framesCounter = 0;
SetTargetFPS(120); SetTargetFPS(120);
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
// Main game loop // Main game loop
while (!WindowShouldClose()) // Detect window close button or ESC key while (!WindowShouldClose()) // Detect window close button or ESC key
{ {
// Update // Update
//---------------------------------------------------------------------------------- //----------------------------------------------------------------------------------
// Check for mouse button pressed and activate explosion (if not active) // Check for mouse button pressed and activate explosion (if not active)
if (IsMouseButtonPressed(MOUSE_LEFT_BUTTON) && !active) if (IsMouseButtonPressed(MOUSE_LEFT_BUTTON) && !active)
{ {
position = GetMousePosition(); position = GetMousePosition();
active = true; active = true;
position.x -= frameWidth/2; position.x -= frameWidth/2;
position.y -= frameHeight/2; position.y -= frameHeight/2;
PlaySound(fxBoom); PlaySound(fxBoom);
} }
// Compute explosion animation frames // Compute explosion animation frames
if (active) if (active)
{ {
framesCounter++; framesCounter++;
if (framesCounter > 2) if (framesCounter > 2)
{ {
currentFrame++; currentFrame++;
if (currentFrame >= NUM_FRAMES) if (currentFrame >= NUM_FRAMES)
{ {
currentFrame = 0; currentFrame = 0;
currentLine++; currentLine++;
if (currentLine >= NUM_LINES) if (currentLine >= NUM_LINES)
{ {
currentLine = 0; currentLine = 0;
active = false; active = false;
} }
} }
framesCounter = 0; framesCounter = 0;
} }
} }
frameRec.x = frameWidth*currentFrame; frameRec.x = frameWidth*currentFrame;
frameRec.y = frameHeight*currentLine; frameRec.y = frameHeight*currentLine;
//---------------------------------------------------------------------------------- //----------------------------------------------------------------------------------
// Draw // Draw
//---------------------------------------------------------------------------------- //----------------------------------------------------------------------------------
BeginDrawing(); BeginDrawing();
ClearBackground(RAYWHITE); ClearBackground(RAYWHITE);
// Draw explosion required frame rectangle // Draw explosion required frame rectangle
if (active) DrawTextureRec(explosion, frameRec, position, WHITE); if (active) DrawTextureRec(explosion, frameRec, position, WHITE);
EndDrawing(); EndDrawing();
//---------------------------------------------------------------------------------- //----------------------------------------------------------------------------------
} }
@ -109,12 +109,12 @@ int main()
// De-Initialization // De-Initialization
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
UnloadTexture(explosion); // Unload texture UnloadTexture(explosion); // Unload texture
UnloadSound(fxBoom); // Unload sound UnloadSound(fxBoom); // Unload sound
CloseAudioDevice(); CloseAudioDevice();
CloseWindow(); // Close window and OpenGL context CloseWindow(); // Close window and OpenGL context
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
return 0; return 0;
} }

View file

@ -11,32 +11,33 @@
#include "raylib.h" #include "raylib.h"
int main() int main(void)
{ {
// Initialization // Initialization
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
int screenWidth = 800; const int screenWidth = 800;
int screenHeight = 450; const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [textures] examples - texture source and destination rectangles"); InitWindow(screenWidth, screenHeight, "raylib [textures] examples - texture source and destination rectangles");
// NOTE: Textures MUST be loaded after Window initialization (OpenGL context is required) // NOTE: Textures MUST be loaded after Window initialization (OpenGL context is required)
Texture2D scarfy = LoadTexture("resources/scarfy.png"); // Texture loading Texture2D scarfy = LoadTexture("resources/scarfy.png"); // Texture loading
int frameWidth = scarfy.width/6; int frameWidth = scarfy.width/6;
int frameHeight = scarfy.height; int frameHeight = scarfy.height;
// NOTE: Source rectangle (part of the texture to use for drawing) // Source rectangle (part of the texture to use for drawing)
Rectangle sourceRec = { 0.0f, 0.0f, frameWidth, frameHeight }; Rectangle sourceRec = { 0.0f, 0.0f, frameWidth, frameHeight };
// NOTE: Destination rectangle (screen rectangle where drawing part of texture) // Destination rectangle (screen rectangle where drawing part of texture)
Rectangle destRec = { screenWidth/2, screenHeight/2, frameWidth*2, frameHeight*2 }; Rectangle destRec = { screenWidth/2, screenHeight/2, frameWidth*2, frameHeight*2 };
// NOTE: Origin of the texture (rotation/scale point), it's relative to destination rectangle size // Origin of the texture (rotation/scale point), it's relative to destination rectangle size
Vector2 origin = { frameWidth, frameHeight }; Vector2 origin = { frameWidth, frameHeight };
int rotation = 0; int rotation = 0;
SetTargetFPS(60); SetTargetFPS(60);
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
@ -63,7 +64,7 @@ int main()
DrawLine((int)destRec.x, 0, (int)destRec.x, screenHeight, GRAY); DrawLine((int)destRec.x, 0, (int)destRec.x, screenHeight, GRAY);
DrawLine(0, (int)destRec.y, screenWidth, (int)destRec.y, GRAY); DrawLine(0, (int)destRec.y, screenWidth, (int)destRec.y, GRAY);
DrawText("(c) Scarfy sprite by Eiden Marsal", screenWidth - 200, screenHeight - 20, 10, GRAY); DrawText("(c) Scarfy sprite by Eiden Marsal", screenWidth - 200, screenHeight - 20, 10, GRAY);
EndDrawing(); EndDrawing();

View file

@ -1,6 +1,6 @@
/******************************************************************************************* /*******************************************************************************************
* *
* raylib [textures] example - Retrieve image data from texture: GetTextureData() * raylib [textures] example - Retrieve image data from texture: GetTextureData()
* *
* NOTE: Images are loaded in CPU memory (RAM); textures are loaded in GPU memory (VRAM) * NOTE: Images are loaded in CPU memory (RAM); textures are loaded in GPU memory (VRAM)
* *
@ -13,12 +13,12 @@
#include "raylib.h" #include "raylib.h"
int main() int main(void)
{ {
// Initialization // Initialization
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
int screenWidth = 800; const int screenWidth = 800;
int screenHeight = 450; const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [textures] example - texture to image"); InitWindow(screenWidth, screenHeight, "raylib [textures] example - texture to image");
@ -27,10 +27,10 @@ int main()
Image image = LoadImage("resources/raylib_logo.png"); // Load image data into CPU memory (RAM) Image image = LoadImage("resources/raylib_logo.png"); // Load image data into CPU memory (RAM)
Texture2D texture = LoadTextureFromImage(image); // Image converted to texture, GPU memory (RAM -> VRAM) Texture2D texture = LoadTextureFromImage(image); // Image converted to texture, GPU memory (RAM -> VRAM)
UnloadImage(image); // Unload image data from CPU memory (RAM) UnloadImage(image); // Unload image data from CPU memory (RAM)
image = GetTextureData(texture); // Retrieve image data from GPU memory (VRAM -> RAM) image = GetTextureData(texture); // Retrieve image data from GPU memory (VRAM -> RAM)
UnloadTexture(texture); // Unload texture from GPU memory (VRAM) UnloadTexture(texture); // Unload texture from GPU memory (VRAM)
texture = LoadTextureFromImage(image); // Recreate texture from retrieved image data (RAM -> VRAM) texture = LoadTextureFromImage(image); // Recreate texture from retrieved image data (RAM -> VRAM)
UnloadImage(image); // Unload retrieved image data from CPU memory (RAM) UnloadImage(image); // Unload retrieved image data from CPU memory (RAM)
//--------------------------------------------------------------------------------------- //---------------------------------------------------------------------------------------