Watch
2
0
Fork
You've already forked raylib-cs
0

chore: clean recommit

This commit is contained in:
tiger tiger tiger 2026-07-07 23:29:25 +02:00
commit 8739e3b347
134 changed files with 15442 additions and 10648 deletions

View file

@ -7,4 +7,20 @@
<PropertyGroup Condition="'$(MSBuildProjectName)' == 'Raylib-cs' And '$(RuntimeIdentifier)' == 'browser-wasm'">
<OutputType>Library</OutputType>
</PropertyGroup>
<!-- Raylib-cs 8.1.0 is not on nuget.org yet; pack locally so Examples and tests resolve the package with native runtimes. -->
<Target Name="_EnsureLocalRaylibCsPackage"
BeforeTargets="Restore"
Condition="'$(MSBuildProjectName)' != 'Raylib-cs' And Exists('$(MSBuildThisFileDirectory)Raylib-cs/Raylib-cs.csproj')">
<PropertyGroup>
<_LocalNuGetDir>$(MSBuildThisFileDirectory)nuget</_LocalNuGetDir>
<_LocalRaylibCsNupkg>$(_LocalNuGetDir)/Raylib-cs.$(RaylibCsVersion).nupkg</_LocalRaylibCsNupkg>
</PropertyGroup>
<MakeDir Directories="$(_LocalNuGetDir)" Condition="!Exists('$(_LocalNuGetDir)')"/>
<MSBuild Projects="$(MSBuildThisFileDirectory)Raylib-cs/Raylib-cs.csproj"
Targets="Restore;Pack"
Properties="Configuration=Release;PackageOutputPath=$(_LocalNuGetDir)"
RemoveProperties="RuntimeIdentifier;RuntimeIdentifiers;SelfContained;_IsPublishing"
Condition="!Exists('$(_LocalRaylibCsNupkg)') Or '$(ForceRaylibCsPack)' == 'true'"/>
</Target>
</Project>

View file

@ -1,13 +1,15 @@
/*******************************************************************************************
*
* raylib [audio] example - Module playing (streaming)
* raylib [audio] example - module playing
*
* NOTE: This example requires OpenAL Soft library installed
* Example complexity rating: [] 1/4
*
* This example has been created using raylib 1.5 (www.raylib.com)
* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details)
* Example originally created with raylib 1.5, last time updated with raylib 3.5
*
* Copyright (c) 2016 Ramon Santamaria (@raysan5)
* Example licensed under an unmodified zlib/libpng license, which is an OSI-certified,
* BSD-like license that allows static linking with closed source software
*
* Copyright (c) 2016-2025 Ramon Santamaria (@raysan5)
*
********************************************************************************************/
@ -16,11 +18,20 @@ using static Raylib_cs.Raylib;
namespace Examples.Audio;
public class ModulePlaying
public partial class ModulePlaying : IExample
{
const int MaxCircles = 64;
private const int screenWidth = 800;
private const int screenHeight = 450;
struct CircleWave
private const int MaxCircles = 64;
public string Name => "Audio / Module Playing";
public string Title => "raylib [audio] example - module playing";
public ConfigFlags ConfigFlags => ConfigFlags.Msaa4xHint;
private struct CircleWave
{
public Vector2 Position;
public float Radius;
@ -29,20 +40,18 @@ public class ModulePlaying
public Color Color;
}
public static int Main()
private Color[] colors;
private CircleWave[] circles;
private Music music;
private float pitch;
private float timePlayed;
private bool pause;
public void Init()
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
InitAudioDevice(); // Initialize audio device
SetConfigFlags(ConfigFlags.Msaa4xHint); // NOTE: Try to enable MSAA 4X
InitWindow(screenWidth, screenHeight, "raylib [audio] example - module playing (streaming)");
InitAudioDevice();
Color[] colors = new Color[14] {
colors = new Color[14] {
Color.Orange,
Color.Red,
Color.Gold,
@ -59,33 +68,30 @@ public class ModulePlaying
Color.Beige
};
// Creates ome circles for visual effect
CircleWave[] circles = new CircleWave[MaxCircles];
// Creates some circles for visual effect
circles = new CircleWave[MaxCircles];
for (int i = MaxCircles - 1; i >= 0; i--)
for (var i = MaxCircles - 1; i >= 0; i--)
{
circles[i].Alpha = 0.0f;
circles[i].Radius = GetRandomValue(10, 40);
circles[i].Position.X = GetRandomValue((int)circles[i].Radius, screenWidth - (int)circles[i].Radius);
circles[i].Position.Y = GetRandomValue((int)circles[i].Radius, screenHeight - (int)circles[i].Radius);
circles[i].Speed = (float)GetRandomValue(1, 100) / 20000.0f;
circles[i].Speed = (float)GetRandomValue(1, 100) / 2000.0f;
circles[i].Color = colors[GetRandomValue(0, 13)];
}
Music music = LoadMusicStream("resources/audio/mini1111.xm");
music = LoadMusicStream("resources/audio/mini1111.xm");
music.Looping = false;
float pitch = 1.0f;
pitch = 1.0f;
PlayMusicStream(music);
float timePlayed = 0.0f;
bool pause = false;
timePlayed = 0.0f;
pause = false;
}
SetTargetFPS(60);
//--------------------------------------------------------------------------------------
// Main game loop
while (!WindowShouldClose())
public void Update()
{
// Update
//----------------------------------------------------------------------------------
@ -128,7 +134,7 @@ public class ModulePlaying
timePlayed = GetMusicTimePlayed(music) / GetMusicTimeLength(music) * (screenWidth - 40);
// Color circles animation
for (int i = MaxCircles - 1; (i >= 0) && !pause; i--)
for (var i = MaxCircles - 1; (i >= 0) && !pause; i--)
{
circles[i].Alpha += circles[i].Speed;
circles[i].Radius += circles[i].Speed * 10.0f;
@ -161,12 +167,12 @@ public class ModulePlaying
BeginDrawing();
ClearBackground(Color.RayWhite);
for (int i = MaxCircles - 1; i >= 0; i--)
for (var i = MaxCircles - 1; i >= 0; i--)
{
DrawCircleV(
circles[i].Position,
circles[i].Radius,
ColorAlpha(circles[i].Color, circles[i].Alpha)
Fade(circles[i].Color, circles[i].Alpha)
);
}
@ -175,17 +181,50 @@ public class ModulePlaying
DrawRectangle(20, screenHeight - 20 - 12, (int)timePlayed, 12, Color.Maroon);
DrawRectangleLines(20, screenHeight - 20 - 12, screenWidth - 40, 12, Color.Gray);
// Draw help instructions
DrawRectangle(20, 20, 425, 145, Color.White);
DrawRectangleLines(20, 20, 425, 145, Color.Gray);
DrawText("PRESS SPACE TO RESTART MUSIC", 40, 40, 20, Color.Black);
DrawText("PRESS P TO PAUSE/RESUME", 40, 70, 20, Color.Black);
DrawText("PRESS UP/DOWN TO CHANGE SPEED", 40, 100, 20, Color.Black);
DrawText($"SPEED: {pitch:F6}", 40, 130, 20, Color.Maroon);
EndDrawing();
//----------------------------------------------------------------------------------
}
public void Unload()
{
UnloadMusicStream(music); // Unload music stream buffers from RAM
CloseAudioDevice(); // Close audio device (music streaming is automatically stopped)
}
public static int Main()
{
// Initialization
//--------------------------------------------------------------------------------------
SetConfigFlags(ConfigFlags.Msaa4xHint); // NOTE: Try to enable MSAA 4X
InitWindow(screenWidth, screenHeight, "raylib [audio] example - module playing");
SetTargetFPS(60); // Set our game to run at 60 frames-per-second
//--------------------------------------------------------------------------------------
var game = new ModulePlaying();
game.Init();
// Main game loop
while (!WindowShouldClose()) // Detect window close button or ESC key
{
game.Update();
}
game.Unload();
// De-Initialization
//--------------------------------------------------------------------------------------
UnloadMusicStream(music);
CloseAudioDevice();
CloseWindow();
CloseWindow(); // Close window and OpenGL context
//--------------------------------------------------------------------------------------
return 0;

View file

@ -1,13 +1,15 @@
/*******************************************************************************************
*
* raylib [audio] example - IntPtr playing (streaming)
* raylib [audio] example - music stream
*
* NOTE: This example requires OpenAL Soft library installed
* Example complexity rating: [] 1/4
*
* 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)
* Example originally created with raylib 1.3, last time updated with raylib 4.2
*
* Copyright (c) 2015 Ramon Santamaria (@raysan5)
* Example licensed under an unmodified zlib/libpng license, which is an OSI-certified,
* BSD-like license that allows static linking with closed source software
*
* Copyright (c) 2015-2025 Ramon Santamaria (@raysan5)
*
********************************************************************************************/
@ -15,29 +17,42 @@ using static Raylib_cs.Raylib;
namespace Examples.Audio;
public class MusicStreamDemo
public partial class MusicStreamDemo : IExample
{
public static int Main()
private const int screenWidth = 800;
private const int screenHeight = 450;
public string Name => "Audio / Music Stream Demo";
public string Title => "raylib [audio] example - music stream";
public int TargetFps => 30;
private Music music;
private float timePlayed;
private bool pause;
private float pan;
private float volume;
public void Init()
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
InitAudioDevice(); // Initialize audio device
InitWindow(screenWidth, screenHeight, "raylib [audio] example - music playing (streaming)");
InitAudioDevice();
music = LoadMusicStream("resources/audio/country.mp3");
Music music = LoadMusicStream("resources/audio/country.mp3");
PlayMusicStream(music);
float timePlayed = 0.0f;
bool pause = false;
timePlayed = 0.0f; // Time played normalized [0.0f..1.0f]
pause = false; // Music playing paused
SetTargetFPS(60);
//--------------------------------------------------------------------------------------
pan = 0.0f; // Default audio pan center [-1.0f..1.0f]
SetMusicPan(music, pan);
// Main game loop
while (!WindowShouldClose())
volume = 0.8f; // Default audio volume [0.0f..1.0f]
SetMusicVolume(music, volume);
}
public void Update()
{
// Update
//----------------------------------------------------------------------------------
@ -65,12 +80,52 @@ public class MusicStreamDemo
}
}
// Get timePlayed scaled to bar dimensions (400 pixels)
timePlayed = GetMusicTimePlayed(music) / GetMusicTimeLength(music) * 400;
if (timePlayed > 400)
// Set audio pan
if (IsKeyDown(KeyboardKey.Left))
{
StopMusicStream(music);
pan -= 0.05f;
if (pan < -1.0f)
{
pan = -1.0f;
}
SetMusicPan(music, pan);
}
else if (IsKeyDown(KeyboardKey.Right))
{
pan += 0.05f;
if (pan > 1.0f)
{
pan = 1.0f;
}
SetMusicPan(music, pan);
}
// Set audio volume
if (IsKeyDown(KeyboardKey.Down))
{
volume -= 0.05f;
if (volume < 0.0f)
{
volume = 0.0f;
}
SetMusicVolume(music, volume);
}
else if (IsKeyDown(KeyboardKey.Up))
{
volume += 0.05f;
if (volume > 1.0f)
{
volume = 1.0f;
}
SetMusicVolume(music, volume);
}
// Get normalized time played for current music stream
timePlayed = GetMusicTimePlayed(music) / GetMusicTimeLength(music);
if (timePlayed > 1.0f)
{
timePlayed = 1.0f; // Make sure time played is no longer than music
}
//----------------------------------------------------------------------------------
@ -81,24 +136,57 @@ public class MusicStreamDemo
DrawText("MUSIC SHOULD BE PLAYING!", 255, 150, 20, Color.LightGray);
DrawText("LEFT-RIGHT for PAN CONTROL", 320, 74, 10, Color.DarkBlue);
DrawRectangle(300, 100, 200, 12, Color.LightGray);
DrawRectangleLines(300, 100, 200, 12, Color.Gray);
DrawRectangle((int)(300 + (pan + 1.0f) / 2.0f * 200 - 5), 92, 10, 28, Color.DarkGray);
DrawRectangle(200, 200, 400, 12, Color.LightGray);
DrawRectangle(200, 200, (int)timePlayed, 12, Color.Maroon);
DrawRectangle(200, 200, (int)(timePlayed * 400.0f), 12, Color.Maroon);
DrawRectangleLines(200, 200, 400, 12, Color.Gray);
DrawText("PRESS SPACE TO RESTART MUSIC", 215, 250, 20, Color.LightGray);
DrawText("PRESS P TO PAUSE/RESUME MUSIC", 208, 280, 20, Color.LightGray);
DrawText("UP-DOWN for VOLUME CONTROL", 320, 334, 10, Color.DarkGreen);
DrawRectangle(300, 360, 200, 12, Color.LightGray);
DrawRectangleLines(300, 360, 200, 12, Color.Gray);
DrawRectangle((int)(300 + volume * 200 - 5), 352, 10, 28, Color.DarkGray);
EndDrawing();
//----------------------------------------------------------------------------------
}
public void Unload()
{
UnloadMusicStream(music); // Unload music stream buffers from RAM
CloseAudioDevice(); // Close audio device (music streaming is automatically stopped)
}
public static int Main()
{
// Initialization
//--------------------------------------------------------------------------------------
InitWindow(screenWidth, screenHeight, "raylib [audio] example - music stream");
SetTargetFPS(30); // Set our game to run at 30 frames-per-second
//--------------------------------------------------------------------------------------
var game = new MusicStreamDemo();
game.Init();
// Main game loop
while (!WindowShouldClose()) // Detect window close button or ESC key
{
game.Update();
}
game.Unload();
// De-Initialization
//--------------------------------------------------------------------------------------
UnloadMusicStream(music);
CloseAudioDevice();
CloseWindow();
CloseWindow(); // Close window and OpenGL context
//--------------------------------------------------------------------------------------
return 0;

View file

@ -1,13 +1,15 @@
/*******************************************************************************************
*
* raylib [audio] example - Sound loading and playing
* raylib [audio] example - sound loading
*
* NOTE: This example requires OpenAL Soft library installed
* Example complexity rating: [] 1/4
*
* 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)
* Example originally created with raylib 1.1, last time updated with raylib 3.5
*
* Copyright (c) 2014 Ramon Santamaria (@raysan5)
* Example licensed under an unmodified zlib/libpng license, which is an OSI-certified,
* BSD-like license that allows static linking with closed source software
*
* Copyright (c) 2014-2025 Ramon Santamaria (@raysan5)
*
********************************************************************************************/
@ -15,37 +17,38 @@ using static Raylib_cs.Raylib;
namespace Examples.Audio;
public class SoundLoading
public partial class SoundLoading : IExample
{
public static int Main()
private const int screenWidth = 800;
private const int screenHeight = 450;
public string Name => "Audio / Sound Loading";
public string Title => "raylib [audio] example - sound loading";
private Sound fxWav;
private Sound fxOgg;
public void Init()
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
InitAudioDevice(); // Initialize audio device
InitWindow(screenWidth, screenHeight, "raylib [audio] example - sound loading and playing");
InitAudioDevice();
fxWav = LoadSound("resources/audio/sound.wav"); // Load WAV audio file
fxOgg = LoadSound("resources/audio/target.ogg"); // Load OGG audio file
}
Sound fxWav = LoadSound("resources/audio/sound.wav");
Sound fxOgg = LoadSound("resources/audio/target.ogg");
SetTargetFPS(60);
//--------------------------------------------------------------------------------------
// Main game loop
while (!WindowShouldClose())
public void Update()
{
// Update
//----------------------------------------------------------------------------------
if (IsKeyPressed(KeyboardKey.Space))
{
PlaySound(fxWav);
PlaySound(fxWav); // Play WAV sound
}
if (IsKeyPressed(KeyboardKey.Enter))
{
PlaySound(fxOgg);
PlaySound(fxOgg); // Play OGG sound
}
//----------------------------------------------------------------------------------
@ -61,14 +64,37 @@ public class SoundLoading
//----------------------------------------------------------------------------------
}
public void Unload()
{
UnloadSound(fxWav); // Unload sound data
UnloadSound(fxOgg); // Unload sound data
CloseAudioDevice(); // Close audio device
}
public static int Main()
{
// Initialization
//--------------------------------------------------------------------------------------
InitWindow(screenWidth, screenHeight, "raylib [audio] example - sound loading");
SetTargetFPS(60); // Set our game to run at 60 frames-per-second
//--------------------------------------------------------------------------------------
var game = new SoundLoading();
game.Init();
// Main game loop
while (!WindowShouldClose()) // Detect window close button or ESC key
{
game.Update();
}
game.Unload();
// De-Initialization
//--------------------------------------------------------------------------------------
UnloadSound(fxWav);
UnloadSound(fxOgg);
CloseAudioDevice();
CloseWindow();
CloseWindow(); // Close window and OpenGL context
//--------------------------------------------------------------------------------------
return 0;

View file

@ -1,21 +1,17 @@
/*******************************************************************************************
*
* raylib [core] example - Basic window
* raylib [core] example - basic screen manager
*
* Welcome to raylib!
* Example complexity rating: [] 1/4
*
* To test examples, just press F6 and execute raylib_compile_execute script
* Note that compiled executable is placed in the same folder as .c file
* NOTE: This example illustrates a very simple screen manager based on a states machines
*
* You can find all basic examples on C:\raylib\raylib\examples folder or
* raylib official webpage: www.raylib.com
* Example originally created with raylib 4.0, last time updated with raylib 4.0
*
* Enjoy using raylib. :)
* Example licensed under an unmodified zlib/libpng license, which is an OSI-certified,
* BSD-like license that allows static linking with closed source software
*
* 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)
*
* Copyright (c) 2013-2016 Ramon Santamaria (@raysan5)
* Copyright (c) 2021-2025 Ramon Santamaria (@raysan5)
*
********************************************************************************************/
@ -23,7 +19,7 @@ using static Raylib_cs.Raylib;
namespace Examples.Core;
enum GameScreen
internal enum GameScreen
{
Logo = 0,
Title,
@ -31,29 +27,28 @@ enum GameScreen
Ending
}
public class BasicScreenManager
public partial class BasicScreenManager : IExample
{
public static int Main()
private const int screenWidth = 800;
private const int screenHeight = 450;
public string Name => "Core / Basic Screen Manager";
public string Title => "raylib [core] example - basic screen manager";
private GameScreen currentScreen;
private int framesCounter;
public void Init()
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [core] example - basic screen manager");
GameScreen currentScreen = GameScreen.Logo;
currentScreen = GameScreen.Logo;
// TODO: Initialize all required variables and load all required data here!
// Useful to count frames
int framesCounter = 0;
framesCounter = 0; // Useful to count frames
}
SetTargetFPS(60); // Set desired framerate (frames-per-second)
//--------------------------------------------------------------------------------------
// Main game loop
while (!WindowShouldClose())
public void Update()
{
// Update
//----------------------------------------------------------------------------------
@ -63,8 +58,7 @@ public class BasicScreenManager
{
// TODO: Update LOGO screen variables here!
// Count frames
framesCounter++;
framesCounter++; // Count frames
// Wait for 2 seconds (120 frames) before jumping to TITLE screen
if (framesCounter > 120)
@ -124,7 +118,6 @@ public class BasicScreenManager
// TODO: Draw LOGO screen here!
DrawText("LOGO SCREEN", 20, 20, 40, Color.LightGray);
DrawText("WAIT for 2 SECONDS...", 290, 220, 20, Color.Gray);
}
break;
case GameScreen.Title:
@ -133,7 +126,6 @@ public class BasicScreenManager
DrawRectangle(0, 0, screenWidth, screenHeight, Color.Green);
DrawText("TITLE SCREEN", 20, 20, 40, Color.DarkGreen);
DrawText("PRESS ENTER or TAP to JUMP to GAMEPLAY SCREEN", 120, 220, 20, Color.DarkGreen);
}
break;
case GameScreen.Gameplay:
@ -151,7 +143,6 @@ public class BasicScreenManager
DrawRectangle(0, 0, screenWidth, screenHeight, Color.Blue);
DrawText("ENDING SCREEN", 20, 20, 40, Color.DarkBlue);
DrawText("PRESS ENTER or TAP to RETURN to TITLE SCREEN", 120, 220, 20, Color.DarkBlue);
}
break;
default:
@ -162,12 +153,34 @@ public class BasicScreenManager
//----------------------------------------------------------------------------------
}
// De-Initialization
public void Unload()
{
// TODO: Unload all loaded data (textures, fonts, audio) here!
}
public static int Main()
{
// Initialization
//--------------------------------------------------------------------------------------
InitWindow(screenWidth, screenHeight, "raylib [core] example - basic screen manager");
SetTargetFPS(60); // Set desired framerate (frames-per-second)
//--------------------------------------------------------------------------------------
// TODO: Unload all loaded data (textures, fonts, audio) here!
var game = new BasicScreenManager();
game.Init();
CloseWindow();
// Main game loop
while (!WindowShouldClose()) // Detect window close button or ESC key
{
game.Update();
}
game.Unload();
// De-Initialization
//--------------------------------------------------------------------------------------
CloseWindow(); // Close window and OpenGL context
//--------------------------------------------------------------------------------------
return 0;

View file

@ -33,43 +33,56 @@ using static Raylib_cs.Raylib;
namespace Examples.Core;
public class BasicWindow
public partial class BasicWindow : IExample
{
public static int Main()
private const int screenWidth = 800;
private const int screenHeight = 450;
public string Name => "Core / Basic Window";
public string Title => "raylib [core] example - basic window";
public void Init()
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
}
InitWindow(screenWidth, screenHeight, "raylib [core] example - basic window");
SetTargetFPS(60);
//--------------------------------------------------------------------------------------
// Main game loop
while (!WindowShouldClose())
public void Update()
{
// Update
//----------------------------------------------------------------------------------
// TODO: Update your variables here
//----------------------------------------------------------------------------------
// Draw
//----------------------------------------------------------------------------------
BeginDrawing();
ClearBackground(Color.RayWhite);
DrawText("Congrats! You created your first window!", 190, 200, 20, Color.LightGray);
EndDrawing();
//----------------------------------------------------------------------------------
}
public void Unload()
{
}
public static int Main()
{
// Initialization
//--------------------------------------------------------------------------------------
InitWindow(screenWidth, screenHeight, "raylib [core] example - basic window");
SetTargetFPS(60); // Set our game to run at 60 frames-per-second
var game = new BasicWindow();
game.Init();
// Main game loop
while (!WindowShouldClose()) // Detect window close button or ESC key
{
game.Update();
}
game.Unload();
// De-Initialization
//--------------------------------------------------------------------------------------
CloseWindow();
//--------------------------------------------------------------------------------------
CloseWindow(); // Close window and OpenGL context
return 0;
}

View file

@ -13,31 +13,37 @@
*
********************************************************************************************/
using System;
using System.Numerics;
using static Raylib_cs.Raylib;
namespace Examples.Core;
public class Camera2dDemo
public partial class Camera2dDemo : IExample
{
public const int MaxBuildings = 100;
public static int Main()
private const int screenWidth = 800;
private const int screenHeight = 450;
public string Name => "Core / Camera 2D Demo";
public string Title => "raylib [core] example - 2d camera";
private Rectangle player;
private Rectangle[] buildings;
private Color[] buildColors;
private Camera2D camera;
public void Init()
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
player = new(400, 280, 40, 40);
buildings = new Rectangle[MaxBuildings];
buildColors = new Color[MaxBuildings];
InitWindow(screenWidth, screenHeight, "raylib [core] example - 2d camera");
var spacing = 0;
Rectangle player = new(400, 280, 40, 40);
Rectangle[] buildings = new Rectangle[MaxBuildings];
Color[] buildColors = new Color[MaxBuildings];
int spacing = 0;
for (int i = 0; i < MaxBuildings; i++)
for (var i = 0; i < MaxBuildings; i++)
{
buildings[i].Width = GetRandomValue(50, 200);
buildings[i].Height = GetRandomValue(100, 800);
@ -54,21 +60,17 @@ public class Camera2dDemo
);
}
Camera2D camera = new();
camera = new();
camera.Target = new Vector2(player.X + 20, player.Y + 20);
camera.Offset = new Vector2(screenWidth / 2, screenHeight / 2);
camera.Offset = new Vector2(screenWidth / 2.0f, screenHeight / 2.0f);
camera.Rotation = 0.0f;
camera.Zoom = 1.0f;
}
SetTargetFPS(60);
//--------------------------------------------------------------------------------------
// Main game loop
while (!WindowShouldClose())
public void Update()
{
// Update
//----------------------------------------------------------------------------------
// Player movement
if (IsKeyDown(KeyboardKey.Right))
{
@ -79,10 +81,10 @@ public class Camera2dDemo
player.X -= 2;
}
// Camera3D target follows player
// Camera target follows player
camera.Target = new Vector2(player.X + 20, player.Y + 20);
// Camera3D rotation controls
// Camera rotation controls
if (IsKeyDown(KeyboardKey.A))
{
camera.Rotation--;
@ -102,8 +104,9 @@ public class Camera2dDemo
camera.Rotation = -40;
}
// Camera3D zoom controls
camera.Zoom += ((float)GetMouseWheelMove() * 0.05f);
// Camera zoom controls
// Uses log scaling to provide consistent zoom speed
camera.Zoom = MathF.Exp(MathF.Log(camera.Zoom) + ((float)GetMouseWheelMove() * 0.1f));
if (camera.Zoom > 3.0f)
{
@ -114,7 +117,7 @@ public class Camera2dDemo
camera.Zoom = 0.1f;
}
// Camera3D reset (zoom and rotation)
// Camera reset (zoom and rotation)
if (IsKeyPressed(KeyboardKey.R))
{
camera.Zoom = 1.0f;
@ -131,36 +134,30 @@ public class Camera2dDemo
DrawRectangle(-6000, 320, 13000, 8000, Color.DarkGray);
for (int i = 0; i < MaxBuildings; i++)
for (var i = 0; i < MaxBuildings; i++)
{
DrawRectangleRec(buildings[i], buildColors[i]);
}
DrawRectangleRec(player, Color.Red);
DrawRectangle((int)camera.Target.X, -500, 1, (int)(screenHeight * 4), Color.Green);
DrawLine(
(int)(-screenWidth * 10),
(int)camera.Target.Y,
(int)(screenWidth * 10),
(int)camera.Target.Y,
Color.Green
);
DrawLine((int)camera.Target.X, -screenHeight * 10, (int)camera.Target.X, screenHeight * 10, Color.Green);
DrawLine(-screenWidth * 10, (int)camera.Target.Y, screenWidth * 10, (int)camera.Target.Y, Color.Green);
EndMode2D();
DrawText("SCREEN AREA", 640, 10, 20, Color.Red);
DrawRectangle(0, 0, (int)screenWidth, 5, Color.Red);
DrawRectangle(0, 5, 5, (int)screenHeight - 10, Color.Red);
DrawRectangle((int)screenWidth - 5, 5, 5, (int)screenHeight - 10, Color.Red);
DrawRectangle(0, (int)screenHeight - 5, (int)screenWidth, 5, Color.Red);
DrawRectangle(0, 0, screenWidth, 5, Color.Red);
DrawRectangle(0, 5, 5, screenHeight - 10, Color.Red);
DrawRectangle(screenWidth - 5, 5, 5, screenHeight - 10, Color.Red);
DrawRectangle(0, screenHeight - 5, screenWidth, 5, Color.Red);
DrawRectangle(10, 10, 250, 113, ColorAlpha(Color.SkyBlue, 0.5f));
DrawRectangle(10, 10, 250, 113, Fade(Color.SkyBlue, 0.5f));
DrawRectangleLines(10, 10, 250, 113, Color.Blue);
DrawText("Free 2d camera controls:", 20, 20, 10, Color.Black);
DrawText("- Right/Left to move Offset", 40, 40, 10, Color.DarkGray);
DrawText("Free 2D camera controls:", 20, 20, 10, Color.Black);
DrawText("- Right/Left to move player", 40, 40, 10, Color.DarkGray);
DrawText("- Mouse Wheel to Zoom in-out", 40, 60, 10, Color.DarkGray);
DrawText("- A / S to Rotate", 40, 80, 10, Color.DarkGray);
DrawText("- R to reset Zoom and Rotation", 40, 100, 10, Color.DarkGray);
@ -169,9 +166,33 @@ public class Camera2dDemo
//----------------------------------------------------------------------------------
}
public void Unload()
{
}
public static int Main()
{
// Initialization
//--------------------------------------------------------------------------------------
InitWindow(screenWidth, screenHeight, "raylib [core] example - 2d camera");
SetTargetFPS(60); // Set our game to run at 60 frames-per-second
//--------------------------------------------------------------------------------------
var game = new Camera2dDemo();
game.Init();
// Main game loop
while (!WindowShouldClose()) // Detect window close button or ESC key
{
game.Update();
}
game.Unload();
// De-Initialization
//--------------------------------------------------------------------------------------
CloseWindow();
CloseWindow(); // Close window and OpenGL context
//--------------------------------------------------------------------------------------
return 0;

View file

@ -2,12 +2,16 @@
*
* raylib [core] example - 2d camera platformer
*
* This example has been created using raylib 2.5 (www.raylib.com)
* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details)
* Example complexity rating: [] 3/4
*
* Example originally created with raylib 2.5, last time updated with raylib 3.0
*
* Example contributed by arvyy (@arvyy) and reviewed by Ramon Santamaria (@raysan5)
*
* Copyright (c) 2019 arvyy (@arvyy)
* Example licensed under an unmodified zlib/libpng license, which is an OSI-certified,
* BSD-like license that allows static linking with closed source software
*
* Copyright (c) 2019-2025 arvyy (@arvyy)
*
********************************************************************************************/
@ -18,20 +22,27 @@ using static Raylib_cs.Raymath;
namespace Examples.Core;
public class Camera2dPlatformer
public partial class Camera2dPlatformer : IExample
{
const int G = 400;
const float PlayerJumpSpeed = 350.0f;
const float PlayerHorSpeed = 200.0f;
private const int screenWidth = 800;
private const int screenHeight = 450;
struct Player
private const int G = 400;
private const float PlayerJumpSpeed = 350.0f;
private const float PlayerHorSpeed = 200.0f;
public string Name => "Core / 2D Camera Platformer";
public string Title => "raylib [core] example - 2d camera platformer";
private struct Player
{
public Vector2 Position;
public float Speed;
public bool CanJump;
}
struct EnvItem
private struct EnvItem
{
public Rectangle Rect;
public int Blocking;
@ -45,7 +56,7 @@ public class Camera2dPlatformer
}
}
delegate void CameraUpdaterCallback(
private delegate void CameraUpdaterCallback(
ref Camera2D camera,
ref Player player,
EnvItem[] envItems,
@ -54,21 +65,22 @@ public class Camera2dPlatformer
int height
);
public static int Main()
private Player player;
private EnvItem[] envItems;
private Camera2D camera;
private CameraUpdaterCallback[] cameraUpdaters;
private int cameraOption;
private int cameraUpdatersLength;
private string[] cameraDescriptions;
public void Init()
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [core] example - 2d camera");
Player player = new();
player = new();
player.Position = new Vector2(400, 280);
player.Speed = 0;
player.CanJump = false;
EnvItem[] envItems = new EnvItem[]
envItems = new EnvItem[]
{
new EnvItem(new Rectangle(0, 0, 1000, 400), 0, Color.LightGray),
new EnvItem(new Rectangle(0, 400, 1000, 200), 1, Color.Gray),
@ -77,14 +89,14 @@ public class Camera2dPlatformer
new EnvItem(new Rectangle(650, 300, 100, 10), 1, Color.Gray)
};
Camera2D camera = new();
camera = new();
camera.Target = player.Position;
camera.Offset = new Vector2(screenWidth / 2, screenHeight / 2);
camera.Offset = new Vector2(screenWidth / 2.0f, screenHeight / 2.0f);
camera.Rotation = 0.0f;
camera.Zoom = 1.0f;
// Store callbacks to the multiple update camera functions
CameraUpdaterCallback[] cameraUpdaters = new CameraUpdaterCallback[]
// Store pointers to the multiple update camera functions
cameraUpdaters = new CameraUpdaterCallback[]
{
UpdateCameraCenter,
UpdateCameraCenterInsideMap,
@ -93,26 +105,23 @@ public class Camera2dPlatformer
UpdateCameraPlayerBoundsPush
};
int cameraOption = 0;
int cameraUpdatersLength = cameraUpdaters.Length;
cameraOption = 0;
cameraUpdatersLength = cameraUpdaters.Length;
string[] cameraDescriptions = new string[]{
cameraDescriptions = new string[]{
"Follow player center",
"Follow player center, but clamp to map edges",
"Follow player center; smoothed",
"Follow player center horizontally; update player center vertically after landing",
"Player push camera on getting too close to screen edge"
};
}
SetTargetFPS(60);
//--------------------------------------------------------------------------------------
// Main game loop
while (!WindowShouldClose())
public void Update()
{
// Update
//----------------------------------------------------------------------------------
float deltaTime = GetFrameTime();
var deltaTime = GetFrameTime();
UpdatePlayer(ref player, envItems, deltaTime);
@ -149,37 +158,36 @@ public class Camera2dPlatformer
BeginMode2D(camera);
for (int i = 0; i < envItems.Length; i++)
for (var i = 0; i < envItems.Length; i++)
{
DrawRectangleRec(envItems[i].Rect, envItems[i].Color);
}
Rectangle playerRect = new(player.Position.X - 20, player.Position.Y - 40, 40, 40);
Rectangle playerRect = new(player.Position.X - 20, player.Position.Y - 40, 40.0f, 40.0f);
DrawRectangleRec(playerRect, Color.Red);
DrawCircleV(player.Position, 5.0f, Color.Gold);
EndMode2D();
DrawText("Controls:", 20, 20, 10, Color.Black);
DrawText("- Right/Left to move", 40, 40, 10, Color.DarkGray);
DrawText("- Space to jump", 40, 60, 10, Color.DarkGray);
DrawText("- Mouse Wheel to Zoom in-out, R to reset zoom", 40, 80, 10, Color.DarkGray);
DrawText("- C to change camera mode", 40, 100, 10, Color.DarkGray);
DrawText("Current camera mode:", 20, 120, 10, Color.Black);
DrawText(cameraDescriptions[cameraOption], 40, 140, 10, Color.DarkGray);
DrawText("- Mouse Wheel to Zoom in-out", 40, 80, 10, Color.DarkGray);
DrawText("- R to reset position + zoom", 40, 100, 10, Color.DarkGray);
DrawText("- C to change camera mode", 40, 120, 10, Color.DarkGray);
DrawText("Current camera mode:", 20, 140, 10, Color.Black);
DrawText(cameraDescriptions[cameraOption], 40, 160, 10, Color.DarkGray);
EndDrawing();
//----------------------------------------------------------------------------------
}
// De-Initialization
//--------------------------------------------------------------------------------------
CloseWindow();
//--------------------------------------------------------------------------------------
return 0;
public void Unload()
{
}
static void UpdatePlayer(ref Player player, EnvItem[] envItems, float delta)
private static void UpdatePlayer(ref Player player, EnvItem[] envItems, float delta)
{
if (IsKeyDown(KeyboardKey.Left))
{
@ -197,11 +205,11 @@ public class Camera2dPlatformer
player.CanJump = false;
}
int hitObstacle = 0;
for (int i = 0; i < envItems.Length; i++)
var hitObstacle = 0;
for (var i = 0; i < envItems.Length; i++)
{
EnvItem ei = envItems[i];
Vector2 p = player.Position;
var ei = envItems[i];
var p = player.Position;
if (ei.Blocking != 0 &&
ei.Rect.X <= p.X &&
ei.Rect.X + ei.Rect.Width >= p.X &&
@ -211,6 +219,7 @@ public class Camera2dPlatformer
hitObstacle = 1;
player.Speed = 0.0f;
player.Position.Y = ei.Rect.Y;
break;
}
}
@ -226,7 +235,7 @@ public class Camera2dPlatformer
}
}
static void UpdateCameraCenter(
private static void UpdateCameraCenter(
ref Camera2D camera,
ref Player player,
EnvItem[] envItems,
@ -235,11 +244,11 @@ public class Camera2dPlatformer
int height
)
{
camera.Offset = new Vector2(width / 2, height / 2);
camera.Offset = new Vector2(width / 2.0f, height / 2.0f);
camera.Target = player.Position;
}
static void UpdateCameraCenterInsideMap(
private static void UpdateCameraCenterInsideMap(
ref Camera2D camera,
ref Player player,
EnvItem[] envItems,
@ -248,43 +257,43 @@ public class Camera2dPlatformer
int height)
{
camera.Target = player.Position;
camera.Offset = new Vector2(width / 2, height / 2);
camera.Offset = new Vector2(width / 2.0f, height / 2.0f);
float minX = 1000, minY = 1000, maxX = -1000, maxY = -1000;
for (int i = 0; i < envItems.Length; i++)
for (var i = 0; i < envItems.Length; i++)
{
EnvItem ei = envItems[i];
var ei = envItems[i];
minX = Math.Min(ei.Rect.X, minX);
maxX = Math.Max(ei.Rect.X + ei.Rect.Width, maxX);
minY = Math.Min(ei.Rect.Y, minY);
maxY = Math.Max(ei.Rect.Y + ei.Rect.Height, maxY);
}
Vector2 max = GetWorldToScreen2D(new Vector2(maxX, maxY), camera);
Vector2 min = GetWorldToScreen2D(new Vector2(minX, minY), camera);
var max = GetWorldToScreen2D(new Vector2(maxX, maxY), camera);
var min = GetWorldToScreen2D(new Vector2(minX, minY), camera);
if (max.X < width)
{
camera.Offset.X = width - (max.X - width / 2);
camera.Offset.X = width - (max.X - width / 2.0f);
}
if (max.Y < height)
{
camera.Offset.Y = height - (max.Y - height / 2);
camera.Offset.Y = height - (max.Y - height / 2.0f);
}
if (min.X > 0)
{
camera.Offset.X = width / 2 - min.X;
camera.Offset.X = width / 2.0f - min.X;
}
if (min.Y > 0)
{
camera.Offset.Y = height / 2 - min.Y;
camera.Offset.Y = height / 2.0f - min.Y;
}
}
static void UpdateCameraCenterSmoothFollow(
private static void UpdateCameraCenterSmoothFollow(
ref Camera2D camera,
ref Player player,
EnvItem[] envItems,
@ -297,18 +306,18 @@ public class Camera2dPlatformer
const float minEffectLength = 10;
const float fractionSpeed = 0.8f;
camera.Offset = new Vector2(width / 2, height / 2);
Vector2 diff = Vector2Subtract(player.Position, camera.Target);
float length = Vector2Length(diff);
camera.Offset = new Vector2(width / 2.0f, height / 2.0f);
var diff = Vector2Subtract(player.Position, camera.Target);
var length = Vector2Length(diff);
if (length > minEffectLength)
{
float speed = Math.Max(fractionSpeed * length, minSpeed);
var speed = Math.Max(fractionSpeed * length, minSpeed);
camera.Target = Vector2Add(camera.Target, Vector2Scale(diff, speed * delta / length));
}
}
static void UpdateCameraEvenOutOnLanding(
private static void UpdateCameraEvenOutOnLanding(
ref Camera2D camera,
ref Player player,
EnvItem[] envItems,
@ -318,10 +327,10 @@ public class Camera2dPlatformer
)
{
float evenOutSpeed = 700;
int eveningOut = 0;
float evenOutTarget = 0.0f;
var eveningOut = 0;
var evenOutTarget = 0.0f;
camera.Offset = new Vector2(width / 2, height / 2);
camera.Offset = new Vector2(width / 2.0f, height / 2.0f);
camera.Target.X = player.Position.X;
if (eveningOut != 0)
@ -357,7 +366,7 @@ public class Camera2dPlatformer
}
}
static void UpdateCameraPlayerBoundsPush(
private static void UpdateCameraPlayerBoundsPush(
ref Camera2D camera,
ref Player player,
EnvItem[] envItems,
@ -368,11 +377,11 @@ public class Camera2dPlatformer
{
Vector2 bbox = new(0.2f, 0.2f);
Vector2 bboxWorldMin = GetScreenToWorld2D(
var bboxWorldMin = GetScreenToWorld2D(
new Vector2((1 - bbox.X) * 0.5f * width, (1 - bbox.Y) * 0.5f * height),
camera
);
Vector2 bboxWorldMax = GetScreenToWorld2D(
var bboxWorldMax = GetScreenToWorld2D(
new Vector2((1 + bbox.X) * 0.5f * width,
(1 + bbox.Y) * 0.5f * height),
camera
@ -399,4 +408,32 @@ public class Camera2dPlatformer
camera.Target.Y = bboxWorldMin.Y + (player.Position.Y - bboxWorldMax.Y);
}
}
public static int Main()
{
// Initialization
//--------------------------------------------------------------------------------------
InitWindow(screenWidth, screenHeight, "raylib [core] example - 2d camera platformer");
SetTargetFPS(60);
//--------------------------------------------------------------------------------------
var game = new Camera2dPlatformer();
game.Init();
// Main game loop
while (!WindowShouldClose())
{
game.Update();
}
game.Unload();
// De-Initialization
//--------------------------------------------------------------------------------------
CloseWindow(); // Close window and OpenGL context
//--------------------------------------------------------------------------------------
return 0;
}
}

View file

@ -2,10 +2,14 @@
*
* raylib [core] example - 3d camera first person
*
* 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)
* Example complexity rating: [] 2/4
*
* Copyright (c) 2015 Ramon Santamaria (@raysan5)
* Example originally created with raylib 1.3, last time updated with raylib 1.3
*
* Example licensed under an unmodified zlib/libpng license, which is an OSI-certified,
* BSD-like license that allows static linking with closed source software
*
* Copyright (c) 2015-2025 Ramon Santamaria (@raysan5)
*
********************************************************************************************/
@ -14,46 +18,51 @@ using static Raylib_cs.Raylib;
namespace Examples.Core;
public class Camera3dFirstPerson
public partial class Camera3dFirstPerson : IExample
{
public const int MaxColumns = 20;
public static int Main()
private const int screenWidth = 800;
private const int screenHeight = 450;
public string Name => "Core / Camera 3D First Person";
public string Title => "raylib [core] example - 3d camera first person";
public bool CursorDisabled => true;
private Camera3D camera;
private CameraMode cameraMode;
private float[] heights;
private Vector3[] positions;
private Color[] colors;
public void Init()
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [core] example - 3d camera first person");
// Define the camera to look into our 3d world (position, target, up vector)
Camera3D camera = new();
camera.Position = new Vector3(4.0f, 2.0f, 4.0f);
camera.Target = new Vector3(0.0f, 1.8f, 0.0f);
camera.Up = new Vector3(0.0f, 1.0f, 0.0f);
camera.FovY = 60.0f;
camera.Projection = CameraProjection.Perspective;
camera = new();
camera.Position = new Vector3(0.0f, 2.0f, 4.0f); // Camera position
camera.Target = new Vector3(0.0f, 2.0f, 0.0f); // Camera looking at point
camera.Up = new Vector3(0.0f, 1.0f, 0.0f); // Camera up vector (rotation towards target)
camera.FovY = 60.0f; // Camera field-of-view Y
camera.Projection = CameraProjection.Perspective; // Camera projection type
cameraMode = CameraMode.FirstPerson;
// Generates some random columns
float[] heights = new float[MaxColumns];
Vector3[] positions = new Vector3[MaxColumns];
Color[] colors = new Color[MaxColumns];
heights = new float[MaxColumns];
positions = new Vector3[MaxColumns];
colors = new Color[MaxColumns];
for (int i = 0; i < MaxColumns; i++)
for (var i = 0; i < MaxColumns; i++)
{
heights[i] = (float)GetRandomValue(1, 12);
positions[i] = new Vector3(GetRandomValue(-15, 15), heights[i] / 2, GetRandomValue(-15, 15));
positions[i] = new Vector3(GetRandomValue(-15, 15), heights[i] / 2.0f, GetRandomValue(-15, 15));
colors[i] = new Color(GetRandomValue(20, 255), GetRandomValue(10, 55), 30, 255);
}
}
CameraMode cameraMode = CameraMode.FirstPerson;
SetTargetFPS(60);
//--------------------------------------------------------------------------------------
// Main game loop
while (!WindowShouldClose())
public void Update()
{
// Update
//----------------------------------------------------------------------------------
@ -112,8 +121,8 @@ public class Camera3dFirstPerson
// Update camera computes movement internally depending on the camera mode
// Some default standard keyboard/mouse inputs are hardcoded to simplify use
// For advance camera controls, it's reecommended to compute camera movement manually
UpdateCamera(ref camera, cameraMode);
// For advanced camera controls, it's recommended to compute camera movement manually
UpdateCamera(ref camera, cameraMode); // Update camera
//----------------------------------------------------------------------------------
// Draw
@ -136,7 +145,7 @@ public class Camera3dFirstPerson
DrawCube(new Vector3(0.0f, 2.5f, 16.0f), 32.0f, 5.0f, 1.0f, Color.Gold);
// Draw some cubes around
for (int i = 0; i < MaxColumns; i++)
for (var i = 0; i < MaxColumns; i++)
{
DrawCube(positions[i], 2.0f, heights[i], 2.0f, colors[i]);
DrawCubeWires(positions[i], 2.0f, heights[i], 2.0f, Color.Maroon);
@ -152,8 +161,8 @@ public class Camera3dFirstPerson
EndMode3D();
// Draw info boxes
DrawRectangle(5, 5, 330, 100, ColorAlpha(Color.SkyBlue, 0.5f));
DrawRectangleLines(10, 10, 330, 100, Color.Blue);
DrawRectangle(5, 5, 330, 100, Fade(Color.SkyBlue, 0.5f));
DrawRectangleLines(5, 5, 330, 100, Color.Blue);
DrawText("Camera controls:", 15, 15, 10, Color.Black);
DrawText("- Move keys: W, A, S, D, Space, Left-Ctrl", 15, 30, 10, Color.Black);
@ -176,9 +185,35 @@ public class Camera3dFirstPerson
//----------------------------------------------------------------------------------
}
public void Unload()
{
}
public static int Main()
{
// Initialization
//--------------------------------------------------------------------------------------
InitWindow(screenWidth, screenHeight, "raylib [core] example - 3d camera first person");
DisableCursor(); // Limit cursor to relative movement inside the window
SetTargetFPS(60); // Set our game to run at 60 frames-per-second
//--------------------------------------------------------------------------------------
var game = new Camera3dFirstPerson();
game.Init();
// Main game loop
while (!WindowShouldClose()) // Detect window close button or ESC key
{
game.Update();
}
game.Unload();
// De-Initialization
//--------------------------------------------------------------------------------------
CloseWindow();
CloseWindow(); // Close window and OpenGL context
//--------------------------------------------------------------------------------------
return 0;

View file

@ -1,11 +1,15 @@
/*******************************************************************************************
*
* raylib [core] example - Initialize 3d camera free
* raylib [core] example - 3d camera free
*
* 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)
* Example complexity rating: [] 1/4
*
* Copyright (c) 2015 Ramon Santamaria (@raysan5)
* Example originally created with raylib 1.3, last time updated with raylib 1.3
*
* Example licensed under an unmodified zlib/libpng license, which is an OSI-certified,
* BSD-like license that allows static linking with closed source software
*
* Copyright (c) 2015-2025 Ramon Santamaria (@raysan5)
*
********************************************************************************************/
@ -14,38 +18,40 @@ using static Raylib_cs.Raylib;
namespace Examples.Core;
public class Camera3dFree
public partial class Camera3dFree : IExample
{
public static int Main()
private const int screenWidth = 800;
private const int screenHeight = 450;
public string Name => "Core / Camera 3D Free";
public string Title => "raylib [core] example - 3d camera free";
public bool CursorDisabled => true;
private Camera3D camera;
private Vector3 cubePosition;
public void Init()
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [core] example - 3d camera free");
// Define the camera to look into our 3d world
Camera3D camera;
camera.Position = new Vector3(10.0f, 10.0f, 10.0f);
camera.Target = new Vector3(0.0f, 0.0f, 0.0f);
camera.Up = new Vector3(0.0f, 1.0f, 0.0f);
camera.FovY = 45.0f;
camera.Projection = CameraProjection.Perspective;
camera = new();
camera.Position = new Vector3(10.0f, 10.0f, 10.0f); // Camera position
camera.Target = new Vector3(0.0f, 0.0f, 0.0f); // Camera looking at point
camera.Up = new Vector3(0.0f, 1.0f, 0.0f); // Camera up vector (rotation towards target)
camera.FovY = 45.0f; // Camera field-of-view Y
camera.Projection = CameraProjection.Perspective; // Camera projection type
Vector3 cubePosition = new(0.0f, 0.0f, 0.0f);
cubePosition = new(0.0f, 0.0f, 0.0f);
}
SetTargetFPS(60);
//--------------------------------------------------------------------------------------
// Main game loop
while (!WindowShouldClose())
public void Update()
{
// Update
//----------------------------------------------------------------------------------
UpdateCamera(ref camera, CameraMode.Free);
if (IsKeyDown(KeyboardKey.Z))
if (IsKeyPressed(KeyboardKey.Z))
{
camera.Target = new Vector3(0.0f, 0.0f, 0.0f);
}
@ -65,23 +71,47 @@ public class Camera3dFree
EndMode3D();
DrawRectangle(10, 10, 320, 133, ColorAlpha(Color.SkyBlue, 0.5f));
DrawRectangleLines(10, 10, 320, 133, Color.Blue);
DrawRectangle(10, 10, 320, 93, Fade(Color.SkyBlue, 0.5f));
DrawRectangleLines(10, 10, 320, 93, Color.Blue);
DrawText("Free camera default controls:", 20, 20, 10, Color.Black);
DrawText("- Mouse Wheel to Zoom in-out", 40, 40, 10, Color.DarkGray);
DrawText("- Mouse Wheel Pressed to Pan", 40, 60, 10, Color.DarkGray);
DrawText("- Alt + Mouse Wheel Pressed to Rotate", 40, 80, 10, Color.DarkGray);
DrawText("- Alt + Ctrl + Mouse Wheel Pressed for Smooth Zoom", 40, 100, 10, Color.DarkGray);
DrawText("- Z to zoom to (0, 0, 0)", 40, 120, 10, Color.DarkGray);
DrawText("- Z to zoom to (0, 0, 0)", 40, 80, 10, Color.DarkGray);
EndDrawing();
//----------------------------------------------------------------------------------
}
public void Unload()
{
}
public static int Main()
{
// Initialization
//--------------------------------------------------------------------------------------
InitWindow(screenWidth, screenHeight, "raylib [core] example - 3d camera free");
DisableCursor(); // Limit cursor to relative movement inside the window
SetTargetFPS(60); // Set our game to run at 60 frames-per-second
//--------------------------------------------------------------------------------------
var game = new Camera3dFree();
game.Init();
// Main game loop
while (!WindowShouldClose()) // Detect window close button or ESC key
{
game.Update();
}
game.Unload();
// De-Initialization
//--------------------------------------------------------------------------------------
CloseWindow();
CloseWindow(); // Close window and OpenGL context
//--------------------------------------------------------------------------------------
return 0;

View file

@ -1,11 +1,15 @@
/*******************************************************************************************
*
* raylib [core] example - Initialize 3d camera mode
* raylib [core] example - 3d camera mode
*
* 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)
* Example complexity rating: [] 1/4
*
* Copyright (c) 2014 Ramon Santamaria (@raysan5)
* Example originally created with raylib 1.0, last time updated with raylib 1.0
*
* Example licensed under an unmodified zlib/libpng license, which is an OSI-certified,
* BSD-like license that allows static linking with closed source software
*
* Copyright (c) 2014-2025 Ramon Santamaria (@raysan5)
*
********************************************************************************************/
@ -14,38 +18,33 @@ using static Raylib_cs.Raylib;
namespace Examples.Core;
public class Camera3dMode
public partial class Camera3dMode : IExample
{
public static int Main()
private const int screenWidth = 800;
private const int screenHeight = 450;
private Camera3D camera;
private Vector3 cubePosition;
public string Name => "Core / Camera 3D Mode";
public string Title => "raylib [core] example - 3d camera mode";
public void Init()
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [core] example - 3d camera mode");
// Define the camera to look into our 3d world
Camera3D camera = new();
camera.Position = new Vector3(0.0f, 10.0f, 10.0f);
camera.Target = new Vector3(0.0f, 0.0f, 0.0f);
camera.Up = new Vector3(0.0f, 1.0f, 0.0f);
camera.FovY = 45.0f;
camera.Projection = CameraProjection.Perspective;
camera = new();
camera.Position = new Vector3(0.0f, 10.0f, 10.0f); // Camera position
camera.Target = new Vector3(0.0f, 0.0f, 0.0f); // Camera looking at point
camera.Up = new Vector3(0.0f, 1.0f, 0.0f); // Camera up vector (rotation towards target)
camera.FovY = 45.0f; // Camera field-of-view Y
camera.Projection = CameraProjection.Perspective; // Camera mode type
Vector3 cubePosition = new(0.0f, 0.0f, 0.0f);
cubePosition = new(0.0f, 0.0f, 0.0f);
}
SetTargetFPS(60);
//--------------------------------------------------------------------------------------
// Main game loop
while (!WindowShouldClose())
public void Update()
{
// Update
//----------------------------------------------------------------------------------
// TODO: Update your variables here
//----------------------------------------------------------------------------------
// Draw
//----------------------------------------------------------------------------------
BeginDrawing();
@ -68,9 +67,33 @@ public class Camera3dMode
//----------------------------------------------------------------------------------
}
public void Unload()
{
}
public static int Main()
{
// Initialization
//--------------------------------------------------------------------------------------
InitWindow(screenWidth, screenHeight, "raylib [core] example - 3d camera mode");
SetTargetFPS(60); // Set our game to run at 60 frames-per-second
//--------------------------------------------------------------------------------------
var game = new Camera3dMode();
game.Init();
// Main game loop
while (!WindowShouldClose()) // Detect window close button or ESC key
{
game.Update();
}
game.Unload();
// De-Initialization
//--------------------------------------------------------------------------------------
CloseWindow();
CloseWindow(); // Close window and OpenGL context
//--------------------------------------------------------------------------------------
return 0;

View file

@ -1,13 +1,17 @@
/*******************************************************************************************
*
* raylib [core] example - Custom logging
* raylib [core] example - custom logging
*
* This example has been created using raylib 2.1 (www.raylib.com)
* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details)
* Example complexity rating: [] 3/4
*
* Example originally created with raylib 2.5, last time updated with raylib 2.5
*
* Example contributed by Pablo Marcos Oltra (@pamarcos) and reviewed by Ramon Santamaria (@raysan5)
*
* Copyright (c) 2018 Pablo Marcos Oltra (@pamarcos) and Ramon Santamaria (@raysan5)
* Example licensed under an unmodified zlib/libpng license, which is an OSI-certified,
* BSD-like license that allows static linking with closed source software
*
* Copyright (c) 2018-2025 Pablo Marcos Oltra (@pamarcos) and Ramon Santamaria (@raysan5)
*
********************************************************************************************/
@ -17,11 +21,23 @@ using static Raylib_cs.Raylib;
namespace Examples.Core;
public unsafe class CustomLogging
public unsafe partial class CustomLogging : IExample
{
private const int screenWidth = 800;
private const int screenHeight = 450;
public string Name => "Core / Custom Logging";
public string Title => "raylib [core] example - custom logging";
[UnmanagedCallersOnly(CallConvs = new[] { typeof(System.Runtime.CompilerServices.CallConvCdecl) })]
private static void LogCustom(int logLevel, sbyte* text, sbyte* args)
{
#if BROWSER
// WebAssembly can't invoke the C varargs vsprintf/vsnprintf that Logging.GetLogMessage relies on
// (the wasm runtime traps with "function signature mismatch"), so log the raw, unformatted text.
string message = Marshal.PtrToStringUTF8(new IntPtr(text)) ?? string.Empty;
#else
var message = Logging.GetLogMessage(new IntPtr(text), new IntPtr(args));
/*Console.ForegroundColor = (TraceLogLevel)logLevel switch
@ -36,35 +52,21 @@ public unsafe class CustomLogging
TraceLogLevel.LOG_NONE => ConsoleColor.White,
_ => throw new ArgumentOutOfRangeException(nameof(logLevel), logLevel, null)
};*/
#endif
Console.WriteLine($"Custom " + message);
// Console.ResetColor();
}
public static int Main()
public void Init()
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
// First thing we do is setting our custom logger to ensure everything raylib logs
// will use our own logger instead of its internal one
SetTraceLogCallback(&LogCustom);
}
InitWindow(screenWidth, screenHeight, "raylib [core] example - custom logging");
SetTargetFPS(60);
//--------------------------------------------------------------------------------------
// Main game loop
while (!WindowShouldClose())
public void Update()
{
// Update
//----------------------------------------------------------------------------------
// TODO: Update your variables here
//----------------------------------------------------------------------------------
// Draw
//----------------------------------------------------------------------------------
BeginDrawing();
@ -76,10 +78,38 @@ public unsafe class CustomLogging
//----------------------------------------------------------------------------------
}
public void Unload()
{
#if !BROWSER
// Restore the default formatting logger on desktop. On WebAssembly we leave the (wasm-safe)
// custom logger in place — Logging.LogConsole formats via vsprintf, which traps on wasm.
SetTraceLogCallback(&Logging.LogConsole);
#endif
}
public static int Main()
{
// Initialization
//--------------------------------------------------------------------------------------
InitWindow(screenWidth, screenHeight, "raylib [core] example - custom logging");
SetTargetFPS(60); // Set our game to run at 60 frames-per-second
//--------------------------------------------------------------------------------------
var game = new CustomLogging();
game.Init();
// Main game loop
while (!WindowShouldClose()) // Detect window close button or ESC key
{
game.Update();
}
game.Unload();
// De-Initialization
//--------------------------------------------------------------------------------------
CloseWindow();
SetTraceLogCallback(&Logging.LogConsole);
CloseWindow(); // Close window and OpenGL context
//--------------------------------------------------------------------------------------
return 0;

View file

@ -21,35 +21,40 @@ namespace Examples.Core;
using static Raylib_cs.Raylib;
public class DeltaTime
public partial class DeltaTime : IExample
{
public static int Main()
private const int screenWidth = 800;
private const int screenHeight = 450;
// The speed applied to both circles
private const float speed = 10.0f;
private const float circleRadius = 32.0f;
private int currentFps;
// Store the position for the both of the circles
private Vector2 deltaCircle;
private Vector2 frameCircle;
public string Name => "Core / Delta Time";
public string Title => "raylib [core] example - delta time";
public void Init()
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
currentFps = 60;
InitWindow(screenWidth, screenHeight, "raylib [core] example - delta time");
// Store the position for the both of the circles
deltaCircle = new Vector2(0, (float)screenHeight / 3.0f);
frameCircle = new Vector2(0, (float)screenHeight * (2.0f / 3.0f));
}
int currentFps = 60;
Vector2 deltaCircle = new Vector2(0, (float)screenHeight / 3.0f);
Vector2 frameCircle = new Vector2(0, (float)screenHeight * (2.0f / 3.0f));
SetTargetFPS(60);
//--------------------------------------------------------------------------------------
const float speed = 10.0f;
const float circleRadius = 32.0f;
// Main game loop
while (!WindowShouldClose())
public void Update()
{
// Update
//----------------------------------------------------------------------------------
// Adjust the FPS target based on the mouse wheel
float mouseWheel = GetMouseWheelMove();
var mouseWheel = GetMouseWheelMove();
if (mouseWheel != 0)
{
currentFps += (int)mouseWheel;
@ -120,9 +125,33 @@ public class DeltaTime
//----------------------------------------------------------------------------------
}
public void Unload()
{
}
public static int Main()
{
// Initialization
//--------------------------------------------------------------------------------------
InitWindow(screenWidth, screenHeight, "raylib [core] example - delta time");
SetTargetFPS(60);
//--------------------------------------------------------------------------------------
var game = new DeltaTime();
game.Init();
// Main game loop
while (!WindowShouldClose()) // Detect window close button or ESC key
{
game.Update();
}
game.Unload();
// De-Initialization
//--------------------------------------------------------------------------------------
CloseWindow();
CloseWindow(); // Close window and OpenGL context
//--------------------------------------------------------------------------------------
return 0;

View file

@ -1,53 +1,69 @@
/*******************************************************************************************
*
* raylib [core] example - Windows drop files
* raylib [core] example - drop files
*
* This example only works on platforms that support drag ref drop (Windows, Linux, OSX, Html5?)
* Example complexity rating: [] 2/4
*
* 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)
* NOTE: This example only works on platforms that support drag & drop (Windows, Linux, OSX, Html5?)
*
* Copyright (c) 2015 Ramon Santamaria (@raysan5)
* Example originally created with raylib 1.3, last time updated with raylib 4.2
*
* Example licensed under an unmodified zlib/libpng license, which is an OSI-certified,
* BSD-like license that allows static linking with closed source software
*
* Copyright (c) 2015-2025 Ramon Santamaria (@raysan5)
*
********************************************************************************************/
using System.Collections.Generic;
using static Raylib_cs.Raylib;
namespace Examples.Core;
public class DropFiles
public partial class DropFiles : IExample
{
public static int Main()
private const int screenWidth = 800;
private const int screenHeight = 450;
public const int MaxFilepathRecorded = 4096;
public string Name => "Core / Drop Files";
public string Title => "raylib [core] example - drop files";
private List<string> filePaths;
public void Init()
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
// We will register a maximum of filepaths
filePaths = new();
}
InitWindow(screenWidth, screenHeight, "raylib [core] example - drop files");
string[] files = new string[0];
SetTargetFPS(60);
//--------------------------------------------------------------------------------------
// Main game loop
while (!WindowShouldClose())
public void Update()
{
// Update
//----------------------------------------------------------------------------------
if (IsFileDropped())
{
files = Raylib.GetDroppedFiles();
var droppedFiles = GetDroppedFiles();
for (var i = 0; i < droppedFiles.Length; i++)
{
if (filePaths.Count < (MaxFilepathRecorded - 1))
{
filePaths.Add(droppedFiles[i]);
}
}
}
//----------------------------------------------------------------------------------
// Draw
//----------------------------------------------------------------------------------
BeginDrawing();
ClearBackground(Color.RayWhite);
if (files.Length == 0)
if (filePaths.Count == 0)
{
DrawText("Drop your files to this window!", 100, 40, 20, Color.DarkGray);
}
@ -55,29 +71,54 @@ public class DropFiles
{
DrawText("Dropped files:", 100, 40, 20, Color.DarkGray);
for (int i = 0; i < files.Length; i++)
for (var i = 0; i < filePaths.Count; i++)
{
if (i % 2 == 0)
{
DrawRectangle(0, 85 + 40 * i, screenWidth, 40, ColorAlpha(Color.LightGray, 0.5f));
DrawRectangle(0, 85 + 40 * i, screenWidth, 40, Fade(Color.LightGray, 0.5f));
}
else
{
DrawRectangle(0, 85 + 40 * i, screenWidth, 40, ColorAlpha(Color.LightGray, 0.3f));
}
DrawText(files[i], 120, 100 + 40 * i, 10, Color.Gray);
DrawRectangle(0, 85 + 40 * i, screenWidth, 40, Fade(Color.LightGray, 0.3f));
}
DrawText("Drop new files...", 100, 110 + 40 * files.Length, 20, Color.DarkGray);
DrawText(filePaths[i], 120, 100 + 40 * i, 10, Color.Gray);
}
DrawText("Drop new files...", 100, 110 + 40 * filePaths.Count, 20, Color.DarkGray);
}
EndDrawing();
//----------------------------------------------------------------------------------
}
public void Unload()
{
}
public static int Main()
{
// Initialization
//--------------------------------------------------------------------------------------
InitWindow(screenWidth, screenHeight, "raylib [core] example - drop files");
SetTargetFPS(60); // Set our game to run at 60 frames-per-second
//--------------------------------------------------------------------------------------
var game = new DropFiles();
game.Init();
// Main game loop
while (!WindowShouldClose()) // Detect window close button or ESC key
{
game.Update();
}
game.Unload();
// De-Initialization
//--------------------------------------------------------------------------------------
CloseWindow();
CloseWindow(); // Close window and OpenGL context
//--------------------------------------------------------------------------------------
return 0;

View file

@ -1,32 +1,34 @@
/*******************************************************************************************
*
* raylib [core] example - input gamepad
*
* Example complexity rating: [] 1/4
*
* NOTE: This example requires a Gamepad connected to the system
* raylib is configured to work with the following gamepads:
* - Xbox 360 Controller (Xbox 360, Xbox One)
* - PLAYSTATION(R)3 Controller
* Check raylib.h for buttons configuration
*
* Example originally created with raylib 1.1, last time updated with raylib 4.2
*
* Example licensed under an unmodified zlib/libpng license, which is an OSI-certified,
* BSD-like license that allows static linking with closed source software
*
* Copyright (c) 2013-2025 Ramon Santamaria (@raysan5)
*
********************************************************************************************/
*
* raylib [core] example - input gamepad
*
* Example complexity rating: [] 1/4
*
* NOTE: This example requires a Gamepad connected to the system
* raylib is configured to work with the following gamepads:
* - Xbox 360 Controller (Xbox 360, Xbox One)
* - PLAYSTATION(R)3 Controller
* Check raylib.h for buttons configuration
*
* Example originally created with raylib 1.1, last time updated with raylib 4.2
*
* Example licensed under an unmodified zlib/libpng license, which is an OSI-certified,
* BSD-like license that allows static linking with closed source software
*
* Copyright (c) 2013-2025 Ramon Santamaria (@raysan5)
*
********************************************************************************************/
using System.Numerics;
using static Raylib_cs.Raylib;
namespace Examples.Core;
public class InputGamepad
public partial class InputGamepad : IExample
{
private const int screenWidth = 800;
private const int screenHeight = 450;
// NOTE: Gamepad name ID depends on drivers and OS
// These are some possible names the gamepads could have.
public const string XBOX_ALIAS_1 = "xbox";
@ -34,28 +36,38 @@ public class InputGamepad
public const string PS_ALIAS_1 = "playstation";
public const string PS_ALIAS_2 = "sony";
public static int Main()
// Set axis deadzones
private const float leftStickDeadzoneX = 0.1f;
private const float leftStickDeadzoneY = 0.1f;
private const float rightStickDeadzoneX = 0.1f;
private const float rightStickDeadzoneY = 0.1f;
private const float leftTriggerDeadzone = -0.9f;
private const float rightTriggerDeadzone = -0.9f;
private Texture2D texPs3Pad;
private Texture2D texXboxPad;
private Rectangle vibrateButton;
private int gamepad; // which gamepad to display
public string Name => "Core / Input Gamepad";
public string Title => "raylib [core] example - input gamepad";
public ConfigFlags ConfigFlags => ConfigFlags.Msaa4xHint;
public void Init()
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
texPs3Pad = LoadTexture("resources/ps3.png");
texXboxPad = LoadTexture("resources/xbox.png");
// Set MSAA 4X hint before windows creation
SetConfigFlags(ConfigFlags.Msaa4xHint);
InitWindow(screenWidth, screenHeight, "raylib [core] example - gamepad input");
vibrateButton = new Rectangle();
Texture2D texPs3Pad = LoadTexture("resources/ps3.png");
Texture2D texXboxPad = LoadTexture("resources/xbox.png");
gamepad = 0; // which gamepad to display
}
SetTargetFPS(60);
//--------------------------------------------------------------------------------------
int gamepad = 0;
Rectangle vibrateButton = new Rectangle();
// Main game loop
while (!WindowShouldClose())
public void Update()
{
// Update
//----------------------------------------------------------------------------------
@ -69,14 +81,13 @@ public class InputGamepad
gamepad++;
}
Vector2 mousePosition = GetMousePosition();
var mousePosition = GetMousePosition();
vibrateButton = new Rectangle(10, 70.0f + 20 * GetGamepadAxisCount(gamepad) + 20, 75, 24);
if (IsMouseButtonPressed(MouseButton.Left) && CheckCollisionPointRec(mousePosition, vibrateButton))
{
SetGamepadVibration(gamepad, 1.0f, 1.0f, 1.0f);
}
//----------------------------------------------------------------------------------
// Draw
@ -86,9 +97,48 @@ public class InputGamepad
if (IsGamepadAvailable(gamepad))
{
string gamepadName = GetGamepadName_(gamepad);
var gamepadName = GetGamepadName_(gamepad);
DrawText($"GP{gamepad}: {gamepadName}", 10, 10, 10, Color.Black);
// Get axis values
var leftStickX = GetGamepadAxisMovement(gamepad, GamepadAxis.LeftX);
var leftStickY = GetGamepadAxisMovement(gamepad, GamepadAxis.LeftY);
var rightStickX = GetGamepadAxisMovement(gamepad, GamepadAxis.RightX);
var rightStickY = GetGamepadAxisMovement(gamepad, GamepadAxis.RightY);
var leftTrigger = GetGamepadAxisMovement(gamepad, GamepadAxis.LeftTrigger);
var rightTrigger = GetGamepadAxisMovement(gamepad, GamepadAxis.RightTrigger);
// Calculate deadzones
if (leftStickX > -leftStickDeadzoneX && leftStickX < leftStickDeadzoneX)
{
leftStickX = 0.0f;
}
if (leftStickY > -leftStickDeadzoneY && leftStickY < leftStickDeadzoneY)
{
leftStickY = 0.0f;
}
if (rightStickX > -rightStickDeadzoneX && rightStickX < rightStickDeadzoneX)
{
rightStickX = 0.0f;
}
if (rightStickY > -rightStickDeadzoneY && rightStickY < rightStickDeadzoneY)
{
rightStickY = 0.0f;
}
if (leftTrigger < leftTriggerDeadzone)
{
leftTrigger = -1.0f;
}
if (rightTrigger < rightTriggerDeadzone)
{
rightTrigger = -1.0f;
}
if (gamepadName.Contains(XBOX_ALIAS_1, StringComparison.OrdinalIgnoreCase) ||
gamepadName.Contains(XBOX_ALIAS_2, StringComparison.OrdinalIgnoreCase))
{
@ -166,31 +216,32 @@ public class InputGamepad
}
// Draw axis: left joystick
var leftGamepadColor = Color.Black;
if (IsGamepadButtonDown(gamepad, GamepadButton.LeftThumb))
{
leftGamepadColor = Color.Red;
}
DrawCircle(259, 152, 39, Color.Black);
DrawCircle(259, 152, 34, Color.LightGray);
DrawCircle(
259 + (int)(GetGamepadAxisMovement(gamepad, GamepadAxis.LeftX) * 20),
152 + (int)(GetGamepadAxisMovement(gamepad, GamepadAxis.LeftY) * 20),
25,
Color.Black
);
DrawCircle(259 + (int)(leftStickX * 20), 152 + (int)(leftStickY * 20), 25, leftGamepadColor);
// Draw axis: right joystick
var rightGamepadColor = Color.Black;
if (IsGamepadButtonDown(gamepad, GamepadButton.RightThumb))
{
rightGamepadColor = Color.Red;
}
DrawCircle(461, 237, 38, Color.Black);
DrawCircle(461, 237, 33, Color.LightGray);
DrawCircle(
461 + (int)(GetGamepadAxisMovement(gamepad, GamepadAxis.RightX) * 20),
237 + (int)(GetGamepadAxisMovement(gamepad, GamepadAxis.RightY) * 20),
25, Color.Black
);
DrawCircle(461 + (int)(rightStickX * 20), 237 + (int)(rightStickY * 20), 25, rightGamepadColor);
// Draw axis: left-right triggers
float leftTriggerX = GetGamepadAxisMovement(gamepad, GamepadAxis.LeftTrigger);
float rightTriggerX = GetGamepadAxisMovement(gamepad, GamepadAxis.RightTrigger);
DrawRectangle(170, 30, 15, 70, Color.Gray);
DrawRectangle(604, 30, 15, 70, Color.Gray);
DrawRectangle(170, 30, 15, (int)(((1.0f + leftTriggerX) / 2.0f) * 70), Color.Red);
DrawRectangle(604, 30, 15, (int)(((1.0f + rightTriggerX) / 2.0f) * 70), Color.Red);
DrawRectangle(170, 30, 15, (int)(((1 + leftTrigger) / 2) * 70), Color.Red);
DrawRectangle(604, 30, 15, (int)(((1 + rightTrigger) / 2) * 70), Color.Red);
}
else if (gamepadName.Contains(PS_ALIAS_1, StringComparison.OrdinalIgnoreCase) || gamepadName.Contains(PS_ALIAS_2, StringComparison.OrdinalIgnoreCase))
{
@ -273,45 +324,154 @@ public class InputGamepad
}
// Draw axis: left joystick
var leftGamepadColor = Color.Black;
if (IsGamepadButtonDown(gamepad, GamepadButton.LeftThumb))
{
leftGamepadColor = Color.Red;
}
DrawCircle(319, 255, 35, Color.Black);
DrawCircle(319, 255, 31, Color.LightGray);
DrawCircle(
319 + (int)(GetGamepadAxisMovement(gamepad, GamepadAxis.LeftX) * 20),
255 + (int)(GetGamepadAxisMovement(gamepad, GamepadAxis.LeftY) * 20),
25,
Color.Black
);
DrawCircle(319 + (int)(leftStickX * 20), 255 + (int)(leftStickY * 20), 25, leftGamepadColor);
// Draw axis: right joystick
var rightGamepadColor = Color.Black;
if (IsGamepadButtonDown(gamepad, GamepadButton.RightThumb))
{
rightGamepadColor = Color.Red;
}
DrawCircle(475, 255, 35, Color.Black);
DrawCircle(475, 255, 31, Color.LightGray);
DrawCircle(
475 + (int)(GetGamepadAxisMovement(gamepad, GamepadAxis.RightX) * 20),
255 + (int)(GetGamepadAxisMovement(gamepad, GamepadAxis.RightY) * 20),
25,
Color.Black
);
DrawCircle(475 + (int)(rightStickX * 20), 255 + (int)(rightStickY * 20), 25, rightGamepadColor);
// Draw axis: left-right triggers
float leftTriggerX = GetGamepadAxisMovement(gamepad, GamepadAxis.LeftTrigger);
float rightTriggerX = GetGamepadAxisMovement(gamepad, GamepadAxis.RightTrigger);
DrawRectangle(169, 48, 15, 70, Color.Gray);
DrawRectangle(611, 48, 15, 70, Color.Gray);
DrawRectangle(169, 48, 15, (int)(((1.0f - leftTriggerX) / 2.0f) * 70), Color.Red);
DrawRectangle(611, 48, 15, (int)(((1.0f - rightTriggerX) / 2.0f) * 70), Color.Red);
DrawRectangle(169, 48, 15, (int)(((1 + leftTrigger) / 2) * 70), Color.Red);
DrawRectangle(611, 48, 15, (int)(((1 + rightTrigger) / 2) * 70), Color.Red);
}
else
{
DrawText("- GENERIC GAMEPAD -", 280, 180, 20, Color.Gray);
// TODO: Draw generic gamepad
// Draw background: generic
DrawRectangleRounded(new Rectangle(175, 110, 460, 220), 0.3f, 16, Color.DarkGray);
// Draw buttons: basic
DrawCircle(365, 170, 12, Color.RayWhite);
DrawCircle(405, 170, 12, Color.RayWhite);
DrawCircle(445, 170, 12, Color.RayWhite);
DrawCircle(516, 191, 17, Color.RayWhite);
DrawCircle(551, 227, 17, Color.RayWhite);
DrawCircle(587, 191, 17, Color.RayWhite);
DrawCircle(551, 155, 17, Color.RayWhite);
if (IsGamepadButtonDown(gamepad, GamepadButton.MiddleLeft))
{
DrawCircle(365, 170, 10, Color.Red);
}
if (IsGamepadButtonDown(gamepad, GamepadButton.Middle))
{
DrawCircle(405, 170, 10, Color.Green);
}
if (IsGamepadButtonDown(gamepad, GamepadButton.MiddleRight))
{
DrawCircle(445, 170, 10, Color.Blue);
}
if (IsGamepadButtonDown(gamepad, GamepadButton.RightFaceLeft))
{
DrawCircle(516, 191, 15, Color.Gold);
}
if (IsGamepadButtonDown(gamepad, GamepadButton.RightFaceDown))
{
DrawCircle(551, 227, 15, Color.Blue);
}
if (IsGamepadButtonDown(gamepad, GamepadButton.RightFaceRight))
{
DrawCircle(587, 191, 15, Color.Green);
}
if (IsGamepadButtonDown(gamepad, GamepadButton.RightFaceUp))
{
DrawCircle(551, 155, 15, Color.Red);
}
// Draw buttons: d-pad
DrawRectangle(245, 145, 28, 88, Color.RayWhite);
DrawRectangle(215, 174, 88, 29, Color.RayWhite);
DrawRectangle(247, 147, 24, 84, Color.Black);
DrawRectangle(217, 176, 84, 25, Color.Black);
if (IsGamepadButtonDown(gamepad, GamepadButton.LeftFaceUp))
{
DrawRectangle(247, 147, 24, 29, Color.Red);
}
if (IsGamepadButtonDown(gamepad, GamepadButton.LeftFaceDown))
{
DrawRectangle(247, 147 + 54, 24, 30, Color.Red);
}
if (IsGamepadButtonDown(gamepad, GamepadButton.LeftFaceLeft))
{
DrawRectangle(217, 176, 30, 25, Color.Red);
}
if (IsGamepadButtonDown(gamepad, GamepadButton.LeftFaceRight))
{
DrawRectangle(217 + 54, 176, 30, 25, Color.Red);
}
// Draw buttons: left-right back
DrawRectangleRounded(new Rectangle(215, 98, 100, 10), 0.5f, 16, Color.DarkGray);
DrawRectangleRounded(new Rectangle(495, 98, 100, 10), 0.5f, 16, Color.DarkGray);
if (IsGamepadButtonDown(gamepad, GamepadButton.LeftTrigger1))
{
DrawRectangleRounded(new Rectangle(215, 98, 100, 10), 0.5f, 16, Color.Red);
}
if (IsGamepadButtonDown(gamepad, GamepadButton.RightTrigger1))
{
DrawRectangleRounded(new Rectangle(495, 98, 100, 10), 0.5f, 16, Color.Red);
}
// Draw axis: left joystick
var leftGamepadColor = Color.Black;
if (IsGamepadButtonDown(gamepad, GamepadButton.LeftThumb))
{
leftGamepadColor = Color.Red;
}
DrawCircle(345, 260, 40, Color.Black);
DrawCircle(345, 260, 35, Color.LightGray);
DrawCircle(345 + (int)(leftStickX * 20), 260 + (int)(leftStickY * 20), 25, leftGamepadColor);
// Draw axis: right joystick
var rightGamepadColor = Color.Black;
if (IsGamepadButtonDown(gamepad, GamepadButton.RightThumb))
{
rightGamepadColor = Color.Red;
}
DrawCircle(465, 260, 40, Color.Black);
DrawCircle(465, 260, 35, Color.LightGray);
DrawCircle(465 + (int)(rightStickX * 20), 260 + (int)(rightStickY * 20), 25, rightGamepadColor);
// Draw axis: left-right triggers
DrawRectangle(151, 110, 15, 70, Color.Gray);
DrawRectangle(644, 110, 15, 70, Color.Gray);
DrawRectangle(151, 110, 15, (int)(((1 + leftTrigger) / 2) * 70), Color.Red);
DrawRectangle(644, 110, 15, (int)(((1 + rightTrigger) / 2) * 70), Color.Red);
}
DrawText($"DETECTED AXIS [{GetGamepadAxisCount(gamepad)}]:", 10, 50, 10, Color.Maroon);
for (int i = 0; i < GetGamepadAxisCount(gamepad); i++)
for (var i = 0; i < GetGamepadAxisCount(gamepad); i++)
{
DrawText(
$"AXIS {i}: {GetGamepadAxisMovement(gamepad, (GamepadAxis)i)}",
$"AXIS {i}: {GetGamepadAxisMovement(gamepad, (GamepadAxis)i):F2}",
20,
70 + 20 * i,
10,
@ -319,10 +479,10 @@ public class InputGamepad
);
}
// Draw vibrate button
DrawRectangleRec(vibrateButton, Color.SkyBlue);
DrawText("VIBRATE", (int)(vibrateButton.X + 14), (int)(vibrateButton.Y + 1), 10, Color.DarkGray);
if (GetGamepadButtonPressed() != (int)GamepadButton.Unknown)
{
DrawText($"DETECTED BUTTON: {GetGamepadButtonPressed()}", 10, 430, 10, Color.Red);
@ -342,12 +502,37 @@ public class InputGamepad
//----------------------------------------------------------------------------------
}
// De-Initialization
//--------------------------------------------------------------------------------------
public void Unload()
{
UnloadTexture(texPs3Pad);
UnloadTexture(texXboxPad);
}
CloseWindow();
public static int Main()
{
// Initialization
//--------------------------------------------------------------------------------------
SetConfigFlags(ConfigFlags.Msaa4xHint); // Set MSAA 4X hint before windows creation
InitWindow(screenWidth, screenHeight, "raylib [core] example - input gamepad");
SetTargetFPS(60); // Set our game to run at 60 frames-per-second
//--------------------------------------------------------------------------------------
var game = new InputGamepad();
game.Init();
// Main game loop
while (!WindowShouldClose()) // Detect window close button or ESC key
{
game.Update();
}
game.Unload();
// De-Initialization
//--------------------------------------------------------------------------------------
CloseWindow(); // Close window and OpenGL context
//--------------------------------------------------------------------------------------
return 0;

View file

@ -18,35 +18,41 @@ using static Raylib_cs.Raylib;
namespace Examples.Core;
public class InputGestures
public partial class InputGestures : IExample
{
public const int MaxGestureStrings = 20;
public static int Main()
private const int screenWidth = 800;
private const int screenHeight = 450;
private Vector2 touchPosition;
private Rectangle touchArea;
private int gesturesCount;
private string[] gestureStrings;
private Gesture currentGesture;
private Gesture lastGesture;
public string Name => "Core / Input Gestures";
public string Title => "raylib [core] example - input gestures";
public void Init()
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
touchPosition = new(0, 0);
touchArea = new(220, 10, screenWidth - 230, screenHeight - 20);
InitWindow(screenWidth, screenHeight, "raylib [core] example - input gestures");
gesturesCount = 0;
gestureStrings = new string[MaxGestureStrings];
Vector2 touchPosition = new(0, 0);
Rectangle touchArea = new(220, 10, screenWidth - 230, screenHeight - 20);
int gesturesCount = 0;
string[] gestureStrings = new string[MaxGestureStrings];
Gesture currentGesture = Gesture.None;
Gesture lastGesture = Gesture.None;
currentGesture = Gesture.None;
lastGesture = Gesture.None;
// SetGesturesEnabled(0b0000000000001001); // Enable only some gestures to be detected
}
SetTargetFPS(60);
//--------------------------------------------------------------------------------------
// Main game loop
while (!WindowShouldClose())
public void Update()
{
// Update
//----------------------------------------------------------------------------------
@ -100,7 +106,7 @@ public class InputGestures
// Reset gestures strings
if (gesturesCount >= MaxGestureStrings)
{
for (int i = 0; i < MaxGestureStrings; i++)
for (var i = 0; i < MaxGestureStrings; i++)
{
gestureStrings[i] = " ";
}
@ -118,17 +124,17 @@ public class InputGestures
DrawRectangleRec(touchArea, Color.Gray);
DrawRectangle(225, 15, screenWidth - 240, screenHeight - 30, Color.RayWhite);
DrawText("GESTURES TEST AREA", screenWidth - 270, screenHeight - 40, 20, ColorAlpha(Color.Gray, 0.5f));
DrawText("GESTURES TEST AREA", screenWidth - 270, screenHeight - 40, 20, Fade(Color.Gray, 0.5f));
for (int i = 0; i < gesturesCount; i++)
for (var i = 0; i < gesturesCount; i++)
{
if (i % 2 == 0)
{
DrawRectangle(10, 30 + 20 * i, 200, 20, ColorAlpha(Color.LightGray, 0.5f));
DrawRectangle(10, 30 + 20 * i, 200, 20, Fade(Color.LightGray, 0.5f));
}
else
{
DrawRectangle(10, 30 + 20 * i, 200, 20, ColorAlpha(Color.LightGray, 0.3f));
DrawRectangle(10, 30 + 20 * i, 200, 20, Fade(Color.LightGray, 0.3f));
}
if (i < gesturesCount - 1)
@ -153,10 +159,35 @@ public class InputGestures
//----------------------------------------------------------------------------------
}
public void Unload()
{
}
public static int Main()
{
// Initialization
//--------------------------------------------------------------------------------------
InitWindow(screenWidth, screenHeight, "raylib [core] example - input gestures");
SetTargetFPS(60); // Set our game to run at 60 frames-per-second
//--------------------------------------------------------------------------------------
var game = new InputGestures();
game.Init();
// Main game loop
while (!WindowShouldClose()) // Detect window close button or ESC key
{
game.Update();
}
game.Unload();
// De-Initialization
//--------------------------------------------------------------------------------------
CloseWindow();
CloseWindow(); // Close window and OpenGL context
//--------------------------------------------------------------------------------------
return 0;
}
}

View file

@ -1,94 +1,119 @@
/*******************************************************************************************
*
* raylib [core] example - input gestures testbed
*
* Example complexity rating: [] 3/4
*
* Example originally created with raylib 5.0, last time updated with raylib 6.0
*
* Example contributed by ubkp (@ubkp) and reviewed by Ramon Santamaria (@raysan5)
*
* Example licensed under an unmodified zlib/libpng license, which is an OSI-certified,
* BSD-like license that allows static linking with closed source software
*
* Copyright (c) 2023-2025 ubkp (@ubkp)
*
********************************************************************************************/
*
* raylib [core] example - input gestures testbed
*
* Example complexity rating: [] 3/4
*
* Example originally created with raylib 5.0, last time updated with raylib 6.0
*
* Example contributed by ubkp (@ubkp) and reviewed by Ramon Santamaria (@raysan5)
*
* Example licensed under an unmodified zlib/libpng license, which is an OSI-certified,
* BSD-like license that allows static linking with closed source software
*
* Copyright (c) 2023-2025 ubkp (@ubkp)
*
********************************************************************************************/
using System;
using System.Numerics;
using static Raylib_cs.Raylib;
namespace Examples.Core;
using static Raylib_cs.Raylib;
public class InputGesturesTestBed
public partial class InputGesturesTestBed : IExample
{
private const int screenWidth = 800;
private const int screenHeight = 450;
public const int GESTURE_LOG_SIZE = 20;
public const int MAX_TOUCH_COUNT = 32;
//------------------------------------------------------------------------------------
// Program main entry point
//------------------------------------------------------------------------------------
public string Name => "Core / Input Gestures Test Bed";
public static int Main()
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
public string Title => "raylib [core] example - input gestures testbed";
InitWindow(screenWidth, screenHeight, "raylib [core] example - input gestures testbed");
Vector2 messagePosition = new Vector2(160, 7);
private Vector2 messagePosition;
// Last gesture variables definitions
Gesture lastGesture = 0;
Vector2 lastGesturePosition = new Vector2(165, 130);
private Gesture lastGesture;
private Vector2 lastGesturePosition;
// Gesture log variables definitions
// NOTE: The gesture log uses an array (as an inverted circular queue) to store the performed gestures
string[] gestureLog = new string[GESTURE_LOG_SIZE + 1];
for (int i = 0; i < GESTURE_LOG_SIZE; i++)
{
gestureLog[i] = new string(new char[12]);
}
;
private string[] gestureLog;
// NOTE: The index for the inverted circular queue (moving from last to first direction, then looping around)
int gestureLogIndex = GESTURE_LOG_SIZE;
Gesture previousGesture = 0;
private int gestureLogIndex;
private Gesture previousGesture;
// Log mode values:
// - 0 shows repeated events
// - 1 hides repeated events
// - 2 shows repeated events but hide hold events
// - 3 hides repeated events and hide hold events
int logMode = 1;
private int logMode;
Color gestureColor = new Color(0, 0, 0, 255);
Rectangle logButton1 = new Rectangle(53, 7, 48, 26);
Rectangle logButton2 = new Rectangle(108, 7, 36, 26);
Vector2 gestureLogPosition = new Vector2(10, 10);
private Color gestureColor;
private Rectangle logButton1;
private Rectangle logButton2;
private Vector2 gestureLogPosition;
// Protractor variables definitions
float angleLength = 90.0f;
float currentAngleDegrees = 0.0f;
Vector2 finalVector = new Vector2(0.0f, 0.0f);
Vector2 protractorPosition = new Vector2(266.0f, 315.0f);
private float angleLength;
private float currentAngleDegrees;
private Vector2 finalVector;
private Vector2 protractorPosition;
SetTargetFPS(60); // Set our game to run at 60 frames-per-second
//--------------------------------------------------------------------------------------
public void Init()
{
messagePosition = new Vector2(160, 7);
// Main game loop
while (!WindowShouldClose()) // Detect window close button or ESC key
// Last gesture variables definitions
lastGesture = 0;
lastGesturePosition = new Vector2(165, 130);
// Gesture log variables definitions
// NOTE: The gesture log uses an array (as an inverted circular queue) to store the performed gestures
gestureLog = new string[GESTURE_LOG_SIZE + 1];
for (var i = 0; i < GESTURE_LOG_SIZE; i++)
{
gestureLog[i] = new string(new char[12]);
}
// NOTE: The index for the inverted circular queue (moving from last to first direction, then looping around)
gestureLogIndex = GESTURE_LOG_SIZE;
previousGesture = 0;
// Log mode values:
// - 0 shows repeated events
// - 1 hides repeated events
// - 2 shows repeated events but hide hold events
// - 3 hides repeated events and hide hold events
logMode = 1;
gestureColor = new Color(0, 0, 0, 255);
logButton1 = new Rectangle(53, 7, 48, 26);
logButton2 = new Rectangle(108, 7, 36, 26);
gestureLogPosition = new Vector2(10, 10);
// Protractor variables definitions
angleLength = 90.0f;
currentAngleDegrees = 0.0f;
finalVector = new Vector2(0.0f, 0.0f);
protractorPosition = new Vector2(266.0f, 315.0f);
}
public void Update()
{
// Update
//--------------------------------------------------------------------------------------
// Handle common gestures data
int i, ii; // Iterators that will be reused by all for loops
Gesture currentGesture = GetGestureDetected();
float currentDragDegrees = GetGestureDragAngle();
float currentPitchDegrees = GetGesturePinchAngle();
int touchCount = GetTouchPointCount();
var currentGesture = GetGestureDetected();
var currentDragDegrees = GetGestureDragAngle();
var currentPitchDegrees = GetGesturePinchAngle();
var touchCount = GetTouchPointCount();
// Handle last gesture
if ((currentGesture != 0) && ((int)currentGesture != 4) && (currentGesture != previousGesture))
@ -137,7 +162,7 @@ public class InputGesturesTestBed
}
}
int fillLog = 0; // Gate variable to be used to allow or not the gesture log to be filled
var fillLog = 0; // Gate variable to be used to allow or not the gesture log to be filled
if (currentGesture != 0)
{
if (logMode == 3) // 3 hides repeated events and hide hold events
@ -195,19 +220,18 @@ public class InputGesturesTestBed
currentAngleDegrees = 0.0f; // Tap, Doubletap, Hold and Grab
}
float currentAngleRadians =
var currentAngleRadians =
((currentAngleDegrees + 90.0f) * MathF.PI / 180); // Convert the current angle to Radians
// Calculate the final vector for display
finalVector = new Vector2(
(angleLength * MathF.Sin(currentAngleRadians)) + protractorPosition.X,
(angleLength * MathF.Cos(currentAngleRadians)) + protractorPosition.Y
)
;
);
// Handle touch and mouse pointer points
Vector2[] touchPosition = new Vector2[MAX_TOUCH_COUNT];
var touchPosition = new Vector2[MAX_TOUCH_COUNT];
Vector2 mousePosition = Vector2.Zero;
var mousePosition = Vector2.Zero;
if (currentGesture != Gesture.None)
{
if (touchCount != 0)
@ -334,9 +358,9 @@ public class InputGesturesTestBed
DrawText("Angle", (int)protractorPosition.X + 55, (int)protractorPosition.Y + 76, 10, Color.Black);
// Note: Official it's using raylibs functions for string manipulation. But in C# it will end up in an unsafe handling.
string angleString = currentAngleDegrees.ToString("F3");
int angleStringDot = angleString.IndexOf('.');
string angleStringTrim = angleString.Substring(0, angleStringDot + 3);
var angleString = currentAngleDegrees.ToString("F3");
var angleStringDot = angleString.IndexOf('.');
var angleStringTrim = angleString[..(angleStringDot + 3)];
DrawText(angleStringTrim, (int)protractorPosition.X + 55, (int)protractorPosition.Y + 92, 20, gestureColor);
DrawCircleV(protractorPosition, 80.0f, Color.White);
@ -401,6 +425,30 @@ public class InputGesturesTestBed
//--------------------------------------------------------------------------------------
}
public void Unload()
{
}
public static int Main()
{
// Initialization
//--------------------------------------------------------------------------------------
InitWindow(screenWidth, screenHeight, "raylib [core] example - input gestures testbed");
SetTargetFPS(60); // Set our game to run at 60 frames-per-second
//--------------------------------------------------------------------------------------
var game = new InputGesturesTestBed();
game.Init();
// Main game loop
while (!WindowShouldClose()) // Detect window close button or ESC key
{
game.Update();
}
game.Unload();
// De-Initialization
//--------------------------------------------------------------------------------------
CloseWindow(); // Close window and OpenGL context
@ -409,7 +457,8 @@ public class InputGesturesTestBed
return 0;
}
static string GetGestureName(int gesture)
// Get text string for gesture value
private static string GetGestureName(int gesture)
{
switch (gesture)
{
@ -441,7 +490,7 @@ public class InputGesturesTestBed
}
// Get color for gesture value
static Color GetGestureColor(int gesture)
private static Color GetGestureColor(int gesture)
{
switch (gesture)
{

View file

@ -18,24 +18,23 @@ using static Raylib_cs.Raylib;
namespace Examples.Core;
public class InputKeys
public partial class InputKeys : IExample
{
public static int Main()
private const int screenWidth = 800;
private const int screenHeight = 450;
public string Name => "Core / Input Keys";
public string Title => "raylib [core] example - input keys";
private Vector2 ballPosition;
public void Init()
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
ballPosition = new((float)screenWidth / 2, (float)screenHeight / 2);
}
InitWindow(screenWidth, screenHeight, "raylib [core] example - keyboard input");
Vector2 ballPosition = new((float)screenWidth / 2, (float)screenHeight / 2);
SetTargetFPS(60); // Set target frames-per-second
//--------------------------------------------------------------------------------------
// Main game loop
while (!WindowShouldClose())
public void Update()
{
// Update
//----------------------------------------------------------------------------------
@ -73,9 +72,33 @@ public class InputKeys
//----------------------------------------------------------------------------------
}
public void Unload()
{
}
public static int Main()
{
// Initialization
//--------------------------------------------------------------------------------------
InitWindow(screenWidth, screenHeight, "raylib [core] example - input keys");
SetTargetFPS(60); // Set our game to run at 60 frames-per-second
//--------------------------------------------------------------------------------------
var game = new InputKeys();
game.Init();
// Main game loop
while (!WindowShouldClose()) // Detect window close button or ESC key
{
game.Update();
}
game.Unload();
// De-Initialization
//--------------------------------------------------------------------------------------
CloseWindow();
CloseWindow(); // Close window and OpenGL context
//--------------------------------------------------------------------------------------
return 0;

View file

@ -19,29 +19,28 @@ using static Raylib_cs.Raylib;
namespace Examples.Core;
public class InputMouse
public partial class InputMouse : IExample
{
public static int Main()
private const int screenWidth = 800;
private const int screenHeight = 450;
public string Name => "Core / Input Mouse";
public string Title => "raylib [core] example - input mouse";
private Vector2 ballPosition;
private Color ballColor;
public void Init()
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
ballPosition = new(-100.0f, -100.0f);
ballColor = Color.DarkBlue;
}
InitWindow(screenWidth, screenHeight, "raylib [core] example - mouse input");
Vector2 ballPosition = new(-100.0f, -100.0f);
Color ballColor = Color.DarkBlue;
SetTargetFPS(60);
//---------------------------------------------------------------------------------------
// Main game loop
while (!WindowShouldClose())
public void Update()
{
// Update
//----------------------------------------------------------------------------------
if (IsKeyPressed(KeyboardKey.H))
{
if (IsCursorHidden())
@ -68,6 +67,10 @@ public class InputMouse
{
ballColor = Color.DarkBlue;
}
else if (IsMouseButtonPressed(MouseButton.Side))
{
ballColor = Color.Purple;
}
else if (IsMouseButtonPressed(MouseButton.Extra))
{
ballColor = Color.Yellow;
@ -105,9 +108,33 @@ public class InputMouse
//----------------------------------------------------------------------------------
}
public void Unload()
{
}
public static int Main()
{
// Initialization
//--------------------------------------------------------------------------------------
InitWindow(screenWidth, screenHeight, "raylib [core] example - input mouse");
SetTargetFPS(60); // Set our game to run at 60 frames-per-second
//---------------------------------------------------------------------------------------
var game = new InputMouse();
game.Init();
// Main game loop
while (!WindowShouldClose()) // Detect window close button or ESC key
{
game.Update();
}
game.Unload();
// De-Initialization
//--------------------------------------------------------------------------------------
CloseWindow();
CloseWindow(); // Close window and OpenGL context
//--------------------------------------------------------------------------------------
return 0;

View file

@ -17,25 +17,25 @@ using static Raylib_cs.Raylib;
namespace Examples.Core;
public class InputMouseWheel
public partial class InputMouseWheel : IExample
{
public static int Main()
private const int screenWidth = 800;
private const int screenHeight = 450;
public string Name => "Core / Mouse Wheel";
public string Title => "raylib [core] example - input mouse wheel";
private int boxPositionY;
private int scrollSpeed; // Scrolling speed in pixels
public void Init()
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
boxPositionY = screenHeight / 2 - 40;
scrollSpeed = 4; // Scrolling speed in pixels
}
InitWindow(screenWidth, screenHeight, "raylib [core] example - input mouse wheel");
int boxPositionY = screenHeight / 2 - 40;
int scrollSpeed = 4; // Scrolling speed in pixels
SetTargetFPS(60);
//--------------------------------------------------------------------------------------
// Main game loop
while (!WindowShouldClose())
public void Update()
{
// Update
//----------------------------------------------------------------------------------
@ -50,15 +50,39 @@ public class InputMouseWheel
DrawRectangle(screenWidth / 2 - 40, boxPositionY, 80, 80, Color.Maroon);
DrawText("Use mouse wheel to move the cube up and down!", 10, 10, 20, Color.Gray);
DrawText($"Box position Y: {boxPositionY}", 10, 40, 20, Color.LightGray);
DrawText($"Box position Y: {boxPositionY:000}", 10, 40, 20, Color.LightGray);
EndDrawing();
//----------------------------------------------------------------------------------
}
public void Unload()
{
}
public static int Main()
{
// Initialization
//--------------------------------------------------------------------------------------
InitWindow(screenWidth, screenHeight, "raylib [core] example - input mouse wheel");
SetTargetFPS(60); // Set our game to run at 60 frames-per-second
//--------------------------------------------------------------------------------------
var game = new InputMouseWheel();
game.Init();
// Main game loop
while (!WindowShouldClose()) // Detect window close button or ESC key
{
game.Update();
}
game.Unload();
// De-Initialization
//--------------------------------------------------------------------------------------
CloseWindow();
CloseWindow(); // Close window and OpenGL context
//--------------------------------------------------------------------------------------
return 0;

View file

@ -20,39 +20,39 @@ using static Raylib_cs.Raylib;
namespace Examples.Core;
public class InputMultitouch
public partial class InputMultitouch : IExample
{
public static int Main()
private const int screenWidth = 800;
private const int screenHeight = 450;
private const int MaxTouchPoints = 10;
public string Name => "Core / Input Multitouch";
public string Title => "raylib [core] example - input multitouch";
private Vector2[] touchPositions;
public void Init()
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
touchPositions = new Vector2[MaxTouchPoints];
}
InitWindow(screenWidth, screenHeight, "raylib [core] example - input multitouch");
const int MaxTouchPoints = 10;
Vector2[] touchPositions = new Vector2[MaxTouchPoints];
SetTargetFPS(60);
//---------------------------------------------------------------------------------------
// Main game loop
while (!WindowShouldClose())
public void Update()
{
// Update
//----------------------------------------------------------------------------------
// Get the touch point count (how many fingers are touching the screen )
int tCount = GetTouchPointCount();
// Get the touch point count ( how many fingers are touching the screen )
var tCount = GetTouchPointCount();
// Clamp touch points available (set the maximum touch points allowed )
// Clamp touch points available ( set the maximum touch points allowed )
if (tCount > MaxTouchPoints)
{
tCount = MaxTouchPoints;
}
// Get touch points positions
for (int i = 0; i < tCount; i++)
for (var i = 0; i < tCount; i++)
{
touchPositions[i] = GetTouchPosition(i);
}
@ -63,7 +63,7 @@ public class InputMultitouch
BeginDrawing();
ClearBackground(Color.RayWhite);
for (int i = 0; i < tCount; i++)
for (var i = 0; i < tCount; i++)
{
// Make sure point is not (0, 0) as this means there is no touch for it
if ((touchPositions[i].X > 0) && (touchPositions[i].Y > 0))
@ -85,9 +85,33 @@ public class InputMultitouch
//----------------------------------------------------------------------------------
}
public void Unload()
{
}
public static int Main()
{
// Initialization
//--------------------------------------------------------------------------------------
InitWindow(screenWidth, screenHeight, "raylib [core] example - input multitouch");
SetTargetFPS(60); // Set our game to run at 60 frames-per-second
//---------------------------------------------------------------------------------------
var game = new InputMultitouch();
game.Init();
// Main game loop
while (!WindowShouldClose()) // Detect window close button or ESC key
{
game.Update();
}
game.Unload();
// De-Initialization
//--------------------------------------------------------------------------------------
CloseWindow();
CloseWindow(); // Close window and OpenGL context
//--------------------------------------------------------------------------------------
return 0;

View file

@ -1,27 +1,27 @@
/*******************************************************************************************
*
* raylib [core] example - input virtual controls
*
* Example complexity rating: [] 2/4
*
* Example originally created with raylib 5.0, last time updated with raylib 5.0
*
* Example contributed by GreenSnakeLinux (@GreenSnakeLinux),
* reviewed by Ramon Santamaria (@raysan5), oblerion (@oblerion) and danilwhale (@danilwhale)
*
* Example licensed under an unmodified zlib/libpng license, which is an OSI-certified,
* BSD-like license that allows static linking with closed source software
*
* Copyright (c) 2024-2025 GreenSnakeLinux (@GreenSnakeLinux) and Ramon Santamaria (@raysan5)
*
********************************************************************************************/
*
* raylib [core] example - input virtual controls
*
* Example complexity rating: [] 2/4
*
* Example originally created with raylib 5.0, last time updated with raylib 5.0
*
* Example contributed by GreenSnakeLinux (@GreenSnakeLinux),
* reviewed by Ramon Santamaria (@raysan5), oblerion (@oblerion) and danilwhale (@danilwhale)
*
* Example licensed under an unmodified zlib/libpng license, which is an OSI-certified,
* BSD-like license that allows static linking with closed source software
*
* Copyright (c) 2024-2025 GreenSnakeLinux (@GreenSnakeLinux) and Ramon Santamaria (@raysan5)
*
********************************************************************************************/
using System;
using System.Numerics;
using static Raylib_cs.Raylib;
namespace Examples.Core;
using static Raylib_cs.Raylib;
public enum PadButton
{
BUTTON_NONE = -1,
@ -32,21 +32,31 @@ public enum PadButton
BUTTON_MAX
}
public class InputVirtualControls
public partial class InputVirtualControls : IExample
{
public static int Main()
private const int screenWidth = 800;
private const int screenHeight = 450;
public string Name => "Core / Input Virtual Controls";
public string Title => "raylib [core] example - input virtual controls";
private Vector2 padPosition;
private float buttonRadius;
private Vector2[] buttonPositions;
private Vector2[][] arrowTris;
private Color[] buttonLabelColors;
private int pressedButton;
private Vector2 inputPosition;
private Vector2 playerPosition;
private float playerSpeed;
public void Init()
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
padPosition = new Vector2(100, 350);
buttonRadius = 30;
InitWindow(screenWidth, screenHeight, "raylib [core] example - input virtual controls");
Vector2 padPosition = new Vector2(100, 350);
float buttonRadius = 30;
Vector2[] buttonPositions =
buttonPositions =
[
new Vector2(
padPosition.X,padPosition.Y - buttonRadius * 1.5f
@ -62,7 +72,7 @@ public class InputVirtualControls
) // Down
];
Vector2[][] arrowTris = [
arrowTris = [
// Up
[
new Vector2(
@ -114,24 +124,21 @@ public class InputVirtualControls
]
;
Color[] buttonLabelColors = [
buttonLabelColors = [
Color.Yellow, // Up
Color.Blue, // Left
Color.Red, // Right
Color.Green // Down
];
int pressedButton = (int)PadButton.BUTTON_NONE;
Vector2 inputPosition = new Vector2(0, 0);
pressedButton = (int)PadButton.BUTTON_NONE;
inputPosition = new Vector2(0, 0);
Vector2 playerPosition = new Vector2((float)screenWidth / 2, (float)screenHeight / 2);
float playerSpeed = 75f;
playerPosition = new Vector2((float)screenWidth / 2, (float)screenHeight / 2);
playerSpeed = 75f;
}
SetTargetFPS(60);
//--------------------------------------------------------------------------------------
// Main game loop
while (!WindowShouldClose()) // Detect window close button or ESC key
public void Update()
{
// Update
//--------------------------------------------------------------------------
@ -152,10 +159,10 @@ public class InputVirtualControls
((GetTouchPointCount() == 0) && IsMouseButtonDown(MouseButton.Left)))
{
// Find nearest D-Pad button to the input position
for (int i = 0; i < (int)PadButton.BUTTON_MAX; i++)
for (var i = 0; i < (int)PadButton.BUTTON_MAX; i++)
{
float distX = MathF.Abs(buttonPositions[i].X - inputPosition.X);
float distY = MathF.Abs(buttonPositions[i].Y - inputPosition.Y);
var distX = MathF.Abs(buttonPositions[i].X - inputPosition.X);
var distY = MathF.Abs(buttonPositions[i].Y - inputPosition.Y);
if ((distX + distY < buttonRadius))
{
@ -183,8 +190,6 @@ public class InputVirtualControls
default:
break;
}
;
//--------------------------------------------------------------------------
// Draw
@ -197,7 +202,7 @@ public class InputVirtualControls
DrawCircleV(playerPosition, 50, Color.Maroon);
// Draw GUI
for (int i = 0; i < (int)PadButton.BUTTON_MAX; i++)
for (var i = 0; i < (int)PadButton.BUTTON_MAX; i++)
{
DrawCircleV(buttonPositions[i], buttonRadius, (i == pressedButton) ? Color.DarkGray : Color.Black);
@ -215,6 +220,30 @@ public class InputVirtualControls
//--------------------------------------------------------------------------
}
public void Unload()
{
}
public static int Main()
{
// Initialization
//--------------------------------------------------------------------------------------
InitWindow(screenWidth, screenHeight, "raylib [core] example - input virtual controls");
SetTargetFPS(60);
//--------------------------------------------------------------------------------------
var game = new InputVirtualControls();
game.Init();
// Main game loop
while (!WindowShouldClose()) // Detect window close button or ESC key
{
game.Update();
}
game.Unload();
// De-Initialization
//--------------------------------------------------------------------------------------
CloseWindow(); // Close window and OpenGL context

View file

@ -1,133 +1,166 @@
/*******************************************************************************************
*
* raylib example - loading thread
* raylib [core] example - loading thread
*
* This example has been created using raylib 2.5 (www.raylib.com)
* NOTE: raylib is NOT thread-safe: the loading thread only updates plain data
* (progress counter and loaded flag); all raylib calls happen on the main thread.
*
* Example originally created with raylib 2.5 (www.raylib.com)
* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details)
*
* Copyright (c) 2014-2019 Ramon Santamaria (@raysan5)
* Copyright (c) 2014-2025 Ramon Santamaria (@raysan5)
*
********************************************************************************************/
using System.Diagnostics;
using System.Threading;
using static Raylib_cs.Raylib;
using static Raylib_cs.Color;
using static Raylib_cs.KeyboardKey;
namespace Examples.Core;
enum State
public partial class LoadingThread : IExample
{
STATE_WAITING,
STATE_LOADING,
STATE_FINISHED
}
public class LoadingThread
{
// C# bool is atomic. Used for synchronization
// https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/variables#atomicity-of-variable-references
// Data Loaded completion indicator
static bool dataLoaded = false;
// Data progress accumulator
static int dataProgress = 0;
public static int Main()
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [core] example - loading thread");
public string Name => "Core / Loading Thread";
// Loading data thread id
Thread thread = new(new ThreadStart(LoadDataThread));
public string Title => "raylib [core] example - loading thread";
State state = State.STATE_WAITING;
int framesCounter = 0;
enum State
{
Waiting,
Loading,
Finished
}
SetTargetFPS(60);
//--------------------------------------------------------------------------------------
// Loading data thread; a Thread can only be started once, so a fresh one
// is created for every load
Thread loadingThread;
// Main game loop
while (!WindowShouldClose()) // Detect window close button or ESC key
// Data loaded completion indicator; volatile so the main thread sees the
// background thread's writes
volatile bool dataLoaded;
// Data progress accumulator (0..500, the progress bar width in pixels)
volatile int dataProgress;
State state;
int framesCounter;
public void Init()
{
loadingThread = null;
dataLoaded = false;
dataProgress = 0;
state = State.Waiting;
framesCounter = 0;
}
public void Update()
{
// Update
//----------------------------------------------------------------------------------
switch (state)
{
case State.STATE_WAITING:
case State.Waiting:
if (IsKeyPressed(KeyboardKey.Enter))
{
if (IsKeyPressed(KEY_ENTER))
{
thread.Start();
//int error = pthread_create(ref, NULL, ref, NULL);
//if (error != 0) TraceLog(TraceLogLevel.LOG_ERROR, "Error creating loading thread");
//else TraceLog(TraceLogLevel.LOG_INFO, "Loading thread initialized successfully");
loadingThread = new Thread(LoadDataThread) { IsBackground = true };
loadingThread.Start();
TraceLog(TraceLogLevel.Info, "Loading thread initialized successfully");
state = State.STATE_LOADING;
}
state = State.Loading;
}
break;
case State.STATE_LOADING:
{
case State.Loading:
framesCounter++;
if (dataLoaded)
{
framesCounter = 0;
state = State.STATE_FINISHED;
}
loadingThread.Join();
TraceLog(TraceLogLevel.Info, "Loading thread terminated");
state = State.Finished;
}
break;
case State.STATE_FINISHED:
{
if (IsKeyPressed(KEY_ENTER))
case State.Finished:
if (IsKeyPressed(KeyboardKey.Enter))
{
// Reset everything to launch again
// atomic_store(ref, false);
dataLoaded = false;
dataProgress = 0;
state = State.STATE_WAITING;
}
state = State.Waiting;
}
break;
default: break;
}
default:
break;
}
//----------------------------------------------------------------------------------
// Draw
//----------------------------------------------------------------------------------
BeginDrawing();
ClearBackground(RAYWHITE);
ClearBackground(Color.RayWhite);
switch (state)
{
case State.STATE_WAITING:
DrawText("PRESS ENTER to START LOADING DATA", 150, 170, 20, DARKGRAY);
case State.Waiting:
DrawText("PRESS ENTER to START LOADING DATA", 150, 170, 20, Color.DarkGray);
break;
case State.STATE_LOADING:
case State.Loading:
DrawRectangle(150, 200, dataProgress, 60, Color.SkyBlue);
if ((framesCounter / 15) % 2 == 0)
{
DrawRectangle(150, 200, dataProgress, 60, SKYBLUE);
if ((framesCounter / 15) % 2 == 0) DrawText("LOADING DATA...", 240, 210, 40, DARKBLUE);
DrawText("LOADING DATA...", 240, 210, 40, Color.DarkBlue);
}
break;
case State.STATE_FINISHED:
{
DrawRectangle(150, 200, 500, 60, LIME);
DrawText("DATA LOADED!", 250, 210, 40, GREEN);
}
case State.Finished:
DrawRectangle(150, 200, 500, 60, Color.Lime);
DrawText("DATA LOADED!", 250, 210, 40, Color.Green);
break;
default:
break;
default: break;
}
DrawRectangleLines(150, 200, 500, 60, DARKGRAY);
DrawRectangleLines(150, 200, 500, 60, Color.DarkGray);
EndDrawing();
//----------------------------------------------------------------------------------
}
public void Unload()
{
}
public static int Main()
{
// Initialization
//--------------------------------------------------------------------------------------
InitWindow(screenWidth, screenHeight, "raylib [core] example - loading thread");
SetTargetFPS(60); // Set our game to run at 60 frames-per-second
//--------------------------------------------------------------------------------------
var game = new LoadingThread();
game.Init();
// Main game loop
while (!WindowShouldClose()) // Detect window close button or ESC key
{
game.Update();
}
game.Unload();
// De-Initialization
//--------------------------------------------------------------------------------------
CloseWindow(); // Close window and OpenGL context
@ -137,17 +170,15 @@ public class LoadingThread
}
// Loading data thread function definition
static void LoadDataThread()
void LoadDataThread()
{
int timeCounter = 0; // Time counted in ms
// clock_t prevTime = clock(); // Previous time
var stopwatch = Stopwatch.StartNew();
// We simulate data loading with a time counter for 5 seconds
while (timeCounter < 5000)
{
//clock_t currentTime = clock() - prevTime;
//timeCounter = currentTime*1000/CLOCKS_PER_SEC;
timeCounter += 1;
timeCounter = (int)stopwatch.ElapsedMilliseconds;
// We accumulate time over a global variable to be used in
// main thread as a progress bar
@ -158,4 +189,3 @@ public class LoadingThread
dataLoaded = true;
}
}

View file

@ -1,11 +1,15 @@
/*******************************************************************************************
*
* raylib [core] example - Picking in 3d mode
* raylib [core] example - 3d picking
*
* 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)
* Example complexity rating: [] 2/4
*
* Copyright (c) 2015 Ramon Santamaria (@raysan5)
* Example originally created with raylib 1.3, last time updated with raylib 4.0
*
* Example licensed under an unmodified zlib/libpng license, which is an OSI-certified,
* BSD-like license that allows static linking with closed source software
*
* Copyright (c) 2015-2025 Ramon Santamaria (@raysan5)
*
********************************************************************************************/
@ -14,41 +18,61 @@ using static Raylib_cs.Raylib;
namespace Examples.Core;
public class Picking3d
public partial class Picking3d : IExample
{
public static int Main()
private const int screenWidth = 800;
private const int screenHeight = 450;
public string Name => "Core / Picking 3D";
public string Title => "raylib [core] example - 3d picking";
public bool CursorDisabled => true;
private Camera3D camera;
private Vector3 cubePosition;
private Vector3 cubeSize;
private Ray ray; // Picking line ray
private RayCollision collision; // Ray collision hit info
public void Init()
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [core] example - 3d picking");
// Define the camera to look into our 3d world
Camera3D camera;
camera.Position = new Vector3(10.0f, 10.0f, 10.0f);
camera.Target = new Vector3(0.0f, 0.0f, 0.0f);
camera.Up = new Vector3(0.0f, 1.0f, 0.0f);
camera.FovY = 45.0f;
camera.Projection = CameraProjection.Perspective;
camera = new Camera3D();
camera.Position = new Vector3(10.0f, 10.0f, 10.0f); // Camera position
camera.Target = new Vector3(0.0f, 0.0f, 0.0f); // Camera looking at point
camera.Up = new Vector3(0.0f, 1.0f, 0.0f); // Camera up vector (rotation towards target)
camera.FovY = 45.0f; // Camera field-of-view Y
camera.Projection = CameraProjection.Perspective; // Camera projection type
Vector3 cubePosition = new(0.0f, 1.0f, 0.0f);
Vector3 cubeSize = new(2.0f, 2.0f, 2.0f);
cubePosition = new(0.0f, 1.0f, 0.0f);
cubeSize = new(2.0f, 2.0f, 2.0f);
// Picking line ray
Ray ray = new(new Vector3(0.0f, 0.0f, 0.0f), Vector3.Zero);
RayCollision collision = new();
ray = new(); // Picking line ray
collision = new(); // Ray collision hit info
}
SetTargetFPS(60);
//--------------------------------------------------------------------------------------
// Main game loop
while (!WindowShouldClose())
public void Update()
{
// Update
//----------------------------------------------------------------------------------
UpdateCamera(ref camera, CameraMode.Free);
if (IsCursorHidden())
{
UpdateCamera(ref camera, CameraMode.FirstPerson);
}
// Toggle camera controls
if (IsMouseButtonPressed(MouseButton.Right))
{
if (IsCursorHidden())
{
EnableCursor();
}
else
{
DisableCursor();
}
}
if (IsMouseButtonPressed(MouseButton.Left))
{
@ -67,8 +91,6 @@ public class Picking3d
{
collision.Hit = false;
}
ray = GetScreenToWorldRay(GetMousePosition(), camera);
}
//----------------------------------------------------------------------------------
@ -97,23 +119,49 @@ public class Picking3d
EndMode3D();
DrawText("Try selecting the box with mouse!", 240, 10, 20, Color.DarkGray);
DrawText("Try clicking on the box with your mouse!", 240, 10, 20, Color.DarkGray);
if (collision.Hit)
{
int posX = (screenWidth - MeasureText("BOX SELECTED", 30)) / 2;
var posX = (screenWidth - MeasureText("BOX SELECTED", 30)) / 2;
DrawText("BOX SELECTED", posX, (int)(screenHeight * 0.1f), 30, Color.Green);
}
DrawText("Right click mouse to toggle camera controls", 10, 430, 10, Color.Gray);
DrawFPS(10, 10);
EndDrawing();
//----------------------------------------------------------------------------------
}
public void Unload()
{
}
public static int Main()
{
// Initialization
//--------------------------------------------------------------------------------------
InitWindow(screenWidth, screenHeight, "raylib [core] example - 3d picking");
SetTargetFPS(60); // Set our game to run at 60 frames-per-second
//--------------------------------------------------------------------------------------
var game = new Picking3d();
game.Init();
// Main game loop
while (!WindowShouldClose()) // Detect window close button or ESC key
{
game.Update();
}
game.Unload();
// De-Initialization
//--------------------------------------------------------------------------------------
CloseWindow();
CloseWindow(); // Close window and OpenGL context
//--------------------------------------------------------------------------------------
return 0;

View file

@ -1,11 +1,15 @@
/*******************************************************************************************
*
* raylib [core] example - Generate random values
* raylib [core] example - random values
*
* This example has been created using raylib 1.1 (www.raylib.com)
* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details)
* Example complexity rating: [] 1/4
*
* Copyright (c) 2014 Ramon Santamaria (@raysan5)
* Example originally created with raylib 1.1, last time updated with raylib 1.1
*
* Example licensed under an unmodified zlib/libpng license, which is an OSI-certified,
* BSD-like license that allows static linking with closed source software
*
* Copyright (c) 2014-2025 Ramon Santamaria (@raysan5)
*
********************************************************************************************/
@ -13,28 +17,28 @@ using static Raylib_cs.Raylib;
namespace Examples.Core;
public class RandomValues
public partial class RandomValues : IExample
{
public static int Main()
private const int screenWidth = 800;
private const int screenHeight = 450;
public string Name => "Core / Random Values";
public string Title => "raylib [core] example - random values";
private int randValue; // Get a random integer number between -8 and 5 (both included)
private int framesCounter; // Variable used to count frames
public void Init()
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
// SetRandomSeed(0xaabbccff); // Set a custom random seed if desired, by default: "time(NULL)"
InitWindow(screenWidth, screenHeight, "raylib [core] example - generate random values");
randValue = GetRandomValue(-8, 5); // Get a random integer number between -8 and 5 (both included)
// Variable used to count frames
int framesCounter = 0;
framesCounter = 0; // Variable used to count frames
}
// Get a random integer number between -8 and 5 (both included)
int randValue = GetRandomValue(-8, 5);
SetTargetFPS(60); // Set our game to run at 60 frames-per-second
//--------------------------------------------------------------------------------------
// Main game loop
while (!WindowShouldClose())
public void Update()
{
// Update
//----------------------------------------------------------------------------------
@ -61,9 +65,33 @@ public class RandomValues
//----------------------------------------------------------------------------------
}
public void Unload()
{
}
public static int Main()
{
// Initialization
//--------------------------------------------------------------------------------------
InitWindow(screenWidth, screenHeight, "raylib [core] example - random values");
SetTargetFPS(60); // Set our game to run at 60 frames-per-second
//--------------------------------------------------------------------------------------
var game = new RandomValues();
game.Init();
// Main game loop
while (!WindowShouldClose()) // Detect window close button or ESC key
{
game.Update();
}
game.Unload();
// De-Initialization
//--------------------------------------------------------------------------------------
CloseWindow();
CloseWindow(); // Close window and OpenGL context
//--------------------------------------------------------------------------------------
return 0;

View file

@ -1,13 +1,17 @@
/*******************************************************************************************
*
* raylib [core] example - Scissor test
* raylib [core] example - scissor test
*
* This example has been created using raylib 2.5 (www.raylib.com)
* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details)
* Example complexity rating: [] 1/4
*
* Example originally created with raylib 2.5, last time updated with raylib 3.0
*
* Example contributed by Chris Dill (@MysteriousSpace) and reviewed by Ramon Santamaria (@raysan5)
*
* Copyright (c) 2019 Chris Dill (@MysteriousSpace)
* Example licensed under an unmodified zlib/libpng license, which is an OSI-certified,
* BSD-like license that allows static linking with closed source software
*
* Copyright (c) 2019-2025 Chris Dill (@MysteriousSpace)
*
********************************************************************************************/
@ -15,25 +19,25 @@ using static Raylib_cs.Raylib;
namespace Examples.Core;
public class ScissorTest
public partial class ScissorTest : IExample
{
public static int Main()
private const int screenWidth = 800;
private const int screenHeight = 450;
public string Name => "Core / Scissor Test";
public string Title => "raylib [core] example - scissor test";
private Rectangle scissorArea;
private bool scissorMode;
public void Init()
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
scissorArea = new(0, 0, 300, 300);
scissorMode = true;
}
InitWindow(screenWidth, screenHeight, "raylib [core] example - scissor test");
Rectangle scissorArea = new(0, 0, 300, 300);
bool scissorMode = true;
SetTargetFPS(60);
//--------------------------------------------------------------------------------------
// Main game loop
while (!WindowShouldClose())
public void Update()
{
// Update
//----------------------------------------------------------------------------------
@ -74,9 +78,33 @@ public class ScissorTest
//----------------------------------------------------------------------------------
}
public void Unload()
{
}
public static int Main()
{
// Initialization
//--------------------------------------------------------------------------------------
InitWindow(screenWidth, screenHeight, "raylib [core] example - scissor test");
SetTargetFPS(60); // Set our game to run at 60 frames-per-second
//--------------------------------------------------------------------------------------
var game = new ScissorTest();
game.Init();
// Main game loop
while (!WindowShouldClose()) // Detect window close button or ESC key
{
game.Update();
}
game.Unload();
// De-Initialization
//--------------------------------------------------------------------------------------
CloseWindow();
CloseWindow(); // Close window and OpenGL context
//--------------------------------------------------------------------------------------
return 0;

View file

@ -1,14 +1,18 @@
/*******************************************************************************************
*
* raylib [core] example - smooth pixel-perfect camera
* raylib [core] example - smooth pixelperfect
*
* This example has been created using raylib 3.7 (www.raylib.com)
* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details)
* Example complexity rating: [] 3/4
*
* Example originally created with raylib 3.7, last time updated with raylib 4.0
*
* Example contributed by Giancamillo Alessandroni (@NotManyIdeasDev) and
* reviewed by Ramon Santamaria (@raysan5)
*
* Copyright (c) 2021 Giancamillo Alessandroni (@NotManyIdeasDev) and Ramon Santamaria (@raysan5)
* Example licensed under an unmodified zlib/libpng license, which is an OSI-certified,
* BSD-like license that allows static linking with closed source software
*
* Copyright (c) 2021-2025 Giancamillo Alessandroni (@NotManyIdeasDev) and Ramon Santamaria (@raysan5)
*
********************************************************************************************/
@ -18,63 +22,79 @@ using static Raylib_cs.Raylib;
namespace Examples.Core;
public static class SmoothPixelPerfect
public partial class SmoothPixelPerfect : IExample
{
public static int Main()
private const int screenWidth = 800;
private const int screenHeight = 450;
private const int virtualScreenWidth = 160;
private const int virtualScreenHeight = 90;
private const float virtualRatio = (float)screenWidth / (float)virtualScreenWidth;
public string Name => "Core / Smooth Pixelperfect";
public string Title => "raylib [core] example - smooth pixelperfect";
private Camera2D worldSpaceCamera; // Game world camera
private Camera2D screenSpaceCamera; // Smoothing camera
private RenderTexture2D target;
private Rectangle rec01;
private Rectangle rec02;
private Rectangle rec03;
private Rectangle sourceRec;
private Rectangle destRec;
private Vector2 origin;
private float rotation;
private float cameraX;
private float cameraY;
private bool smoothOn;
private bool overscan;
public void Init()
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
const int virtualScreenWidth = 160;
const int virtualScreenHeight = 90;
const float virtualRatio = (float)screenWidth / (float)virtualScreenWidth;
InitWindow(screenWidth, screenHeight, "raylib [core] example - smooth pixel-perfect camera");
// Game world camera
Camera2D worldSpaceCamera = new();
worldSpaceCamera = new(); // Game world camera
worldSpaceCamera.Zoom = 1.0f;
// Smoothing camera
Camera2D screenSpaceCamera = new();
screenSpaceCamera = new(); // Smoothing camera
screenSpaceCamera.Zoom = 1.0f;
// This is where we'll draw all our objects.
RenderTexture2D target = LoadRenderTexture(virtualScreenWidth, virtualScreenHeight);
// Load render texture to draw all our objects
target = LoadRenderTexture(virtualScreenWidth, virtualScreenHeight);
Rectangle rec01 = new(70.0f, 35.0f, 20.0f, 20.0f);
Rectangle rec02 = new(90.0f, 55.0f, 30.0f, 10.0f);
Rectangle rec03 = new(80.0f, 65.0f, 15.0f, 25.0f);
rec01 = new(70.0f, 35.0f, 20.0f, 20.0f);
rec02 = new(90.0f, 55.0f, 30.0f, 10.0f);
rec03 = new(80.0f, 65.0f, 15.0f, 25.0f);
// The target's height is flipped (in the source Rectangle), due to OpenGL reasons
Rectangle sourceRec = new(
sourceRec = new(
0.0f,
0.0f,
(float)target.Texture.Width,
-(float)target.Texture.Height
);
Rectangle destRec = new(
-virtualRatio,
-virtualRatio,
screenWidth + (virtualRatio * 2),
screenHeight + (virtualRatio * 2)
destRec = new(
(screenWidth - screenWidth / 1.25f) / 2.0f,
(screenHeight - screenHeight / 1.25f) / 2.0f,
screenWidth / 1.25f,
screenHeight / 1.25f
);
Vector2 origin = new(0.0f, 0.0f);
origin = new(0.0f, 0.0f);
float rotation = 0.0f;
rotation = 0.0f;
float cameraX = 0.0f;
float cameraY = 0.0f;
cameraX = 0.0f;
cameraY = 0.0f;
SetTargetFPS(60);
//--------------------------------------------------------------------------------------
smoothOn = true;
overscan = false;
}
// Main game loop
while (!WindowShouldClose())
public void Update()
{
// Update
//----------------------------------------------------------------------------------
@ -88,13 +108,42 @@ public static class SmoothPixelPerfect
screenSpaceCamera.Target = new Vector2(cameraX, cameraY);
// Round worldSpace coordinates, keep decimals into screenSpace coordinates
worldSpaceCamera.Target.X = (int)screenSpaceCamera.Target.X;
worldSpaceCamera.Target.X = MathF.Truncate(screenSpaceCamera.Target.X);
screenSpaceCamera.Target.X -= worldSpaceCamera.Target.X;
screenSpaceCamera.Target.X *= virtualRatio;
worldSpaceCamera.Target.Y = (int)screenSpaceCamera.Target.Y;
worldSpaceCamera.Target.Y = MathF.Truncate(screenSpaceCamera.Target.Y);
screenSpaceCamera.Target.Y -= worldSpaceCamera.Target.Y;
screenSpaceCamera.Target.Y *= virtualRatio;
if (IsKeyPressed(KeyboardKey.S))
{
smoothOn = !smoothOn;
}
if (IsKeyPressed(KeyboardKey.O))
{
overscan = !overscan;
}
if (overscan)
{
destRec = new Rectangle(
-virtualRatio,
-virtualRatio,
screenWidth + (virtualRatio * 2),
screenHeight + (virtualRatio * 2)
);
}
else
{
destRec = new Rectangle(
(screenWidth - screenWidth / 1.25f) / 2.0f,
(screenHeight - screenHeight / 1.25f) / 2.0f,
screenWidth / 1.25f,
screenHeight / 1.25f
);
}
//----------------------------------------------------------------------------------
// Draw
@ -107,28 +156,59 @@ public static class SmoothPixelPerfect
DrawRectanglePro(rec02, origin, -rotation, Color.Red);
DrawRectanglePro(rec03, origin, rotation + 45.0f, Color.Blue);
EndMode2D();
EndTextureMode();
BeginDrawing();
ClearBackground(Color.Red);
ClearBackground(Color.LightGray);
if (smoothOn)
{
BeginMode2D(screenSpaceCamera);
DrawTexturePro(target.Texture, sourceRec, destRec, origin, 0.0f, Color.White);
EndMode2D();
}
else
{
DrawTexturePro(target.Texture, sourceRec, destRec, origin, 0.0f, Color.White);
}
DrawText($"Screen resolution: {screenWidth}x{screenHeight}", 10, 10, 20, Color.DarkBlue);
DrawText($"World resolution: {virtualScreenWidth}x{virtualScreenHeight}", 10, 40, 20, Color.DarkGreen);
DrawText($"Smooth: {(smoothOn ? "ON" : "OFF")}", 10, screenHeight - 60, 20, Color.Red);
DrawText($"Overscan: {(overscan ? "ON" : "OFF")}", 10, screenHeight - 30, 20, Color.Red);
DrawFPS(GetScreenWidth() - 95, 10);
EndDrawing();
//----------------------------------------------------------------------------------
}
public void Unload()
{
UnloadRenderTexture(target); // Unload render texture
}
public static int Main()
{
// Initialization
//--------------------------------------------------------------------------------------
InitWindow(screenWidth, screenHeight, "raylib [core] example - smooth pixelperfect");
SetTargetFPS(60);
//--------------------------------------------------------------------------------------
var game = new SmoothPixelPerfect();
game.Init();
// Main game loop
while (!WindowShouldClose()) // Detect window close button or ESC key
{
game.Update();
}
game.Unload();
// De-Initialization
//--------------------------------------------------------------------------------------
UnloadRenderTexture(target);
CloseWindow();
CloseWindow(); // Close window and OpenGL context
//--------------------------------------------------------------------------------------
return 0;

View file

@ -1,13 +1,17 @@
/*******************************************************************************************
*
* raylib [core] example - split screen
* raylib [core] example - 3d camera split screen
*
* This example has been created using raylib 3.7 (www.raylib.com)
* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details)
* Example complexity rating: [] 3/4
*
* Example originally created with raylib 3.7, last time updated with raylib 4.0
*
* Example contributed by Jeffery Myers (@JeffM2501) and reviewed by Ramon Santamaria (@raysan5)
*
* Copyright (c) 2021 Jeffery Myers (@JeffM2501)
* Example licensed under an unmodified zlib/libpng license, which is an OSI-certified,
* BSD-like license that allows static linking with closed source software
*
* Copyright (c) 2021-2025 Jeffery Myers (@JeffM2501)
*
********************************************************************************************/
@ -16,25 +20,34 @@ using static Raylib_cs.Raylib;
namespace Examples.Core;
public unsafe class SplitScreen
public partial class SplitScreen : IExample
{
static Texture2D TextureGrid;
static Camera3D CameraPlayer1;
static Camera3D CameraPlayer2;
private const int screenWidth = 800;
private const int screenHeight = 450;
private Camera3D CameraPlayer1;
private Camera3D CameraPlayer2;
private RenderTexture2D screenPlayer1;
private RenderTexture2D screenPlayer2;
private Rectangle splitScreenRect;
public string Name => "Core / Split Screen";
public string Title => "raylib [core] example - 3d camera split screen";
// Scene drawing
static void DrawScene()
private void DrawScene()
{
int count = 5;
var count = 5;
float spacing = 4;
// Grid of cube trees on a plane to make a "world"
// Simple world plane
DrawPlane(new Vector3(0, 0, 0), new Vector2(50, 50), Color.Beige);
// Draw scene: grid of cube trees on a plane to make a "world"
DrawPlane(new Vector3(0, 0, 0), new Vector2(50, 50), Color.Beige); // Simple world plane
for (float x = -count * spacing; x <= count * spacing; x += spacing)
for (var x = -count * spacing; x <= count * spacing; x += spacing)
{
for (float z = -count * spacing; z <= count * spacing; z += spacing)
for (var z = -count * spacing; z <= count * spacing; z += spacing)
{
DrawCube(new Vector3(x, 1.5f, z), 1, 1, 1, Color.Lime);
DrawCube(new Vector3(x, 0.5f, z), 0.25f, 1, 0.25f, Color.Brown);
@ -46,22 +59,8 @@ public unsafe class SplitScreen
DrawCube(CameraPlayer2.Position, 1, 1, 1, Color.Blue);
}
public static int Main()
public void Init()
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [core] example - split screen");
// Generate a simple texture to use for trees
Image img = GenImageChecked(256, 256, 32, 32, Color.DarkGray, Color.White);
TextureGrid = LoadTextureFromImage(img);
UnloadImage(img);
SetTextureFilter(TextureGrid, TextureFilter.Anisotropic16X);
SetTextureWrap(TextureGrid, TextureWrap.Clamp);
// Setup player 1 camera and screen
CameraPlayer1.FovY = 45.0f;
CameraPlayer1.Up.Y = 1.0f;
@ -69,7 +68,7 @@ public unsafe class SplitScreen
CameraPlayer1.Position.Z = -3.0f;
CameraPlayer1.Position.Y = 1.0f;
RenderTexture2D screenPlayer1 = LoadRenderTexture(screenWidth / 2, screenHeight);
screenPlayer1 = LoadRenderTexture(screenWidth / 2, screenHeight);
// Setup player two camera and screen
CameraPlayer2.FovY = 45.0f;
@ -78,27 +77,24 @@ public unsafe class SplitScreen
CameraPlayer2.Position.X = -3.0f;
CameraPlayer2.Position.Y = 3.0f;
RenderTexture2D screenPlayer2 = LoadRenderTexture(screenWidth / 2, screenHeight);
screenPlayer2 = LoadRenderTexture(screenWidth / 2, screenHeight);
// Build a flipped rectangle the size of the split view to use for drawing later
Rectangle splitScreenRect = new(
splitScreenRect = new(
0.0f,
0.0f,
(float)screenPlayer1.Texture.Width,
(float)-screenPlayer1.Texture.Height
);
}
SetTargetFPS(60);
//--------------------------------------------------------------------------------------
// Main game loop
while (!WindowShouldClose())
public void Update()
{
// Update
//----------------------------------------------------------------------------------
// If anyone moves this frame, how far will they move based on the time since the last frame
// this moves thigns at 10 world units per second, regardless of the actual FPS
float offsetThisFrame = 10.0f * GetFrameTime();
// this moves things at 10 world units per second, regardless of the actual FPS
var offsetThisFrame = 10.0f * GetFrameTime();
// Move Player1 forward and backwards (no turning)
if (IsKeyDown(KeyboardKey.W))
@ -135,7 +131,8 @@ public unsafe class SplitScreen
DrawScene();
EndMode3D();
DrawText("PLAYER 1 W/S to move", 10, 10, 20, Color.Red);
DrawRectangle(0, 0, GetScreenWidth() / 2, 40, Fade(Color.RayWhite, 0.8f));
DrawText("PLAYER1: W/S to move", 10, 10, 20, Color.Maroon);
EndTextureMode();
// Draw Player2 view to the render texture
@ -146,7 +143,8 @@ public unsafe class SplitScreen
DrawScene();
EndMode3D();
DrawText("PLAYER 2 UP/DOWN to move", 10, 10, 20, Color.Blue);
DrawRectangle(0, 0, GetScreenWidth() / 2, 40, Fade(Color.RayWhite, 0.8f));
DrawText("PLAYER2: UP/DOWN to move", 10, 10, 20, Color.DarkBlue);
EndTextureMode();
// Draw both views render textures to the screen side by side
@ -156,19 +154,42 @@ public unsafe class SplitScreen
DrawTextureRec(screenPlayer1.Texture, splitScreenRect, new Vector2(0, 0), Color.White);
DrawTextureRec(screenPlayer2.Texture, splitScreenRect, new Vector2(screenWidth / 2.0f, 0), Color.White);
DrawRectangle(GetScreenWidth() / 2 - 2, 0, 4, GetScreenHeight(), Color.LightGray);
EndDrawing();
//----------------------------------------------------------------------------------
}
public void Unload()
{
UnloadRenderTexture(screenPlayer1); // Unload render texture
UnloadRenderTexture(screenPlayer2); // Unload render texture
}
public static int Main()
{
// Initialization
//--------------------------------------------------------------------------------------
InitWindow(screenWidth, screenHeight, "raylib [core] example - 3d camera split screen");
SetTargetFPS(60); // Set our game to run at 60 frames-per-second
//--------------------------------------------------------------------------------------
var game = new SplitScreen();
game.Init();
// Main game loop
while (!WindowShouldClose()) // Detect window close button or ESC key
{
game.Update();
}
game.Unload();
// De-Initialization
//--------------------------------------------------------------------------------------
UnloadRenderTexture(screenPlayer1);
UnloadRenderTexture(screenPlayer2);
UnloadTexture(TextureGrid);
CloseWindow();
CloseWindow(); // Close window and OpenGL context
//--------------------------------------------------------------------------------------
return 0;
}
}

View file

@ -1,11 +1,15 @@
/*******************************************************************************************
*
* raylib [core] example - Storage save/load values
* raylib [core] example - storage values
*
* This example has been created using raylib 1.4 (www.raylib.com)
* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details)
* Example complexity rating: [] 2/4
*
* Copyright (c) 2015 Ramon Santamaria (@raysan5)
* Example originally created with raylib 1.4, last time updated with raylib 4.2
*
* Example licensed under an unmodified zlib/libpng license, which is an OSI-certified,
* BSD-like license that allows static linking with closed source software
*
* Copyright (c) 2015-2025 Ramon Santamaria (@raysan5)
*
********************************************************************************************/
@ -13,34 +17,35 @@ using static Raylib_cs.Raylib;
namespace Examples.Core;
public class StorageValues
public partial class StorageValues : IExample
{
private const int screenWidth = 800;
private const int screenHeight = 450;
private const string storageDataFile = "storage.data";
// NOTE: Storage positions must start with 0, directly related to file memory layout
enum StorageData
private enum StorageData
{
Score,
HiScore
}
public static int Main()
public string Name => "Core / Storage Values";
public string Title => "raylib [core] example - storage values";
private int score = 0;
private int hiscore = 0;
private int framesCounter = 0;
public void Init()
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
const string storageDataFile = "storage.data";
score = 0;
hiscore = 0;
framesCounter = 0;
}
InitWindow(screenWidth, screenHeight, "raylib [core] example - storage save/load values");
int score = 0;
int hiscore = 0;
int framesCounter = 0;
SetTargetFPS(60);
//--------------------------------------------------------------------------------------
// Main game loop
while (!WindowShouldClose())
public void Update()
{
// Update
//----------------------------------------------------------------------------------
@ -83,9 +88,33 @@ public class StorageValues
//----------------------------------------------------------------------------------
}
public void Unload()
{
}
public static int Main()
{
// Initialization
//--------------------------------------------------------------------------------------
InitWindow(screenWidth, screenHeight, "raylib [core] example - storage values");
SetTargetFPS(60); // Set our game to run at 60 frames-per-second
//--------------------------------------------------------------------------------------
var game = new StorageValues();
game.Init();
// Main game loop
while (!WindowShouldClose()) // Detect window close button or ESC key
{
game.Update();
}
game.Unload();
// De-Initialization
//--------------------------------------------------------------------------------------
CloseWindow();
CloseWindow(); // Close window and OpenGL context
//--------------------------------------------------------------------------------------
return 0;
@ -97,11 +126,11 @@ public class StorageValues
{
using var fileNameBuffer = fileName.ToUtf8Buffer();
bool success = false;
int dataSize = 0;
int newDataSize = 0;
var success = false;
var dataSize = 0;
var newDataSize = 0;
byte* fileData = LoadFileData(fileNameBuffer.AsPointer(), &dataSize);
var fileData = LoadFileData(fileNameBuffer.AsPointer(), &dataSize);
byte* newFileData = null;
if (fileData != null)
@ -115,13 +144,13 @@ public class StorageValues
if (newFileData != null)
{
// RL_REALLOC succeded
int* dataPtr = (int*)newFileData;
var dataPtr = (int*)newFileData;
dataPtr[position] = value;
}
else
{
// RL_REALLOC failed
int positionInBytes = position * sizeof(int);
var positionInBytes = position * sizeof(int);
TraceLog(
TraceLogLevel.Warning,
@$"FILEIO: [{fileName}] Failed to realloc data ({dataSize}),
@ -140,7 +169,7 @@ public class StorageValues
newDataSize = dataSize;
// Replace value on selected position
int* dataPtr = (int*)newFileData;
var dataPtr = (int*)newFileData;
dataPtr[position] = value;
}
@ -155,7 +184,7 @@ public class StorageValues
dataSize = (position + 1) * sizeof(int);
fileData = (byte*)MemAlloc((uint)dataSize);
int* dataPtr = (int*)fileData;
var dataPtr = (int*)fileData;
dataPtr[position] = value;
success = SaveFileData(fileNameBuffer.AsPointer(), fileData, dataSize);
@ -173,9 +202,9 @@ public class StorageValues
{
using var fileNameBuffer = fileName.ToUtf8Buffer();
int value = 0;
int dataSize = 0;
byte* fileData = LoadFileData(fileNameBuffer.AsPointer(), &dataSize);
var value = 0;
var dataSize = 0;
var fileData = LoadFileData(fileNameBuffer.AsPointer(), &dataSize);
if (fileData != null)
{
@ -188,7 +217,7 @@ public class StorageValues
}
else
{
int* dataPtr = (int*)fileData;
var dataPtr = (int*)fileData;
value = dataPtr[position];
}

View file

@ -1,11 +1,15 @@
/*******************************************************************************************
*
* raylib [core] example - VR Simulator (Oculus Rift CV1 parameters)
* raylib [core] example - vr simulator
*
* This example has been created using raylib 1.7 (www.raylib.com)
* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details)
* Example complexity rating: [] 3/4
*
* Copyright (c) 2017 Ramon Santamaria (@raysan5)
* Example originally created with raylib 2.5, last time updated with raylib 4.0
*
* Example licensed under an unmodified zlib/libpng license, which is an OSI-certified,
* BSD-like license that allows static linking with closed source software
*
* Copyright (c) 2017-2025 Ramon Santamaria (@raysan5)
*
********************************************************************************************/
@ -15,51 +19,62 @@ using static Raylib_cs.Raylib;
namespace Examples.Core;
public class VrSimulator
public partial class VrSimulator : IExample
{
public static int Main()
private const int screenWidth = 800;
private const int screenHeight = 450;
#if BROWSER
const int GlslVersion = 100; // WebGL1 needs GLSL ES 100
#else
private const int GlslVersion = 330;
#endif
public string Name => "Core / VR Simulator";
public string Title => "raylib [core] example - vr simulator";
public bool CursorDisabled => true;
private VrStereoConfig config;
private Shader distortion;
private RenderTexture2D target;
private Rectangle sourceRec;
private Rectangle destRec;
private Camera3D camera;
private Vector3 cubePosition;
public unsafe void Init()
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 1080;
const int screenHeight = 600;
SetConfigFlags(ConfigFlags.Msaa4xHint);
InitWindow(screenWidth, screenHeight, "raylib [core] example - vr simulator");
// VR device parameters definition
VrDeviceInfo device = new VrDeviceInfo
var device = new VrDeviceInfo
{
// Oculus Rift CV1 parameters for simulator
HResolution = 2160,
VResolution = 1200,
HScreenSize = 0.133793f,
VScreenSize = 0.0669f,
EyeToScreenDistance = 0.041f,
LensSeparationDistance = 0.07f,
InterpupillaryDistance = 0.07f,
HResolution = 2160, // Horizontal resolution in pixels
VResolution = 1200, // Vertical resolution in pixels
HScreenSize = 0.133793f, // Horizontal size in meters
VScreenSize = 0.0669f, // Vertical size in meters
EyeToScreenDistance = 0.041f, // Distance between eye and display in meters
LensSeparationDistance = 0.07f, // Lens separation distance in meters
InterpupillaryDistance = 0.07f, // IPD (distance between pupils) in meters
};
// 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.
unsafe
{
device.LensDistortionValues[0] = 1.0f;
device.LensDistortionValues[1] = 0.22f;
device.LensDistortionValues[2] = 0.24f;
device.LensDistortionValues[3] = 0.0f;
device.ChromaAbCorrection[0] = 0.996f;
device.ChromaAbCorrection[1] = -0.004f;
device.ChromaAbCorrection[2] = 1.014f;
device.ChromaAbCorrection[3] = 0.0f;
}
// NOTE: CV1 uses fresnel-hybrid-asymmetric lenses with specific compute shaders
// Following parameters are just an approximation to CV1 distortion stereo rendering
device.LensDistortionValues[0] = 1.0f; // Lens distortion constant parameter 0
device.LensDistortionValues[1] = 0.22f; // Lens distortion constant parameter 1
device.LensDistortionValues[2] = 0.24f; // Lens distortion constant parameter 2
device.LensDistortionValues[3] = 0.0f; // Lens distortion constant parameter 3
device.ChromaAbCorrection[0] = 0.996f; // Chromatic aberration correction parameter 0
device.ChromaAbCorrection[1] = -0.004f; // Chromatic aberration correction parameter 1
device.ChromaAbCorrection[2] = 1.014f; // Chromatic aberration correction parameter 2
device.ChromaAbCorrection[3] = 0.0f; // Chromatic aberration correction parameter 3
// Load VR stereo config for VR device parameteres (Oculus Rift CV1 parameters)
VrStereoConfig config = LoadVrStereoConfig(device);
config = LoadVrStereoConfig(device);
// Distortion shader (uses device lens distortion and chroma)
Shader distortion = LoadShader(null, "resources/distortion330.fs");
distortion = LoadShader(null, $"resources/shaders/glsl{GlslVersion}/distortion.fs");
// Update distortion shader with lens and distortion-scale parameters
Raylib.SetShaderValue(
@ -100,8 +115,6 @@ public class VrSimulator
ShaderUniformDataType.Vec2
);
unsafe
{
SetShaderValue(
distortion,
GetShaderLocation(distortion, "deviceWarpParam"),
@ -114,27 +127,27 @@ public class VrSimulator
device.ChromaAbCorrection,
ShaderUniformDataType.Vec4
);
}
// Initialize framebuffer for stereo rendering
// NOTE: Screen size should match HMD aspect ratio
RenderTexture2D target = LoadRenderTexture(GetScreenWidth(), GetScreenHeight());
target = LoadRenderTexture(device.HResolution, device.VResolution);
// The target's height is flipped (in the source Rectangle), due to OpenGL reasons
sourceRec = new(0.0f, 0.0f, (float)target.Texture.Width, -(float)target.Texture.Height);
destRec = new(0.0f, 0.0f, (float)GetScreenWidth(), (float)GetScreenHeight());
// Define the camera to look into our 3d world
Camera3D camera;
camera.Position = new Vector3(5.0f, 2.0f, 5.0f);
camera.Target = new Vector3(0.0f, 2.0f, 0.0f);
camera.Up = new Vector3(0.0f, 1.0f, 0.0f);
camera.FovY = 60.0f;
camera.Projection = CameraProjection.Perspective;
camera = new();
camera.Position = new Vector3(5.0f, 2.0f, 5.0f); // Camera position
camera.Target = new Vector3(0.0f, 2.0f, 0.0f); // Camera looking at point
camera.Up = new Vector3(0.0f, 1.0f, 0.0f); // Camera up vector
camera.FovY = 60.0f; // Camera field-of-view Y
camera.Projection = CameraProjection.Perspective; // Camera projection type
Vector3 cubePosition = new(0.0f, 0.0f, 0.0f);
cubePosition = new(0.0f, 0.0f, 0.0f);
}
SetTargetFPS(90); // Set our game to run at 90 frames-per-second
//--------------------------------------------------------------------------------------
// Main game loop
while (!WindowShouldClose())
public void Update()
{
// Update
//----------------------------------------------------------------------------------
@ -143,12 +156,8 @@ public class VrSimulator
// Draw
//----------------------------------------------------------------------------------
BeginDrawing();
ClearBackground(Color.RayWhite);
BeginTextureMode(target);
ClearBackground(Color.RayWhite);
BeginVrStereoMode(config);
BeginMode3D(camera);
@ -160,28 +169,50 @@ public class VrSimulator
EndVrStereoMode();
EndTextureMode();
BeginDrawing();
ClearBackground(Color.RayWhite);
BeginShaderMode(distortion);
DrawTextureRec(
target.Texture,
new Rectangle(0, 0, (float)target.Texture.Width, (float)-target.Texture.Height),
new Vector2(0.0f, 0.0f),
Color.White
);
DrawTexturePro(target.Texture, sourceRec, destRec, new Vector2(0.0f, 0.0f), 0.0f, Color.White);
EndShaderMode();
DrawFPS(10, 10);
EndDrawing();
//----------------------------------------------------------------------------------
}
public void Unload()
{
UnloadVrStereoConfig(config); // Unload stereo config
UnloadRenderTexture(target); // Unload stereo render fbo
UnloadShader(distortion); // Unload distortion shader
}
public static int Main()
{
// Initialization
//--------------------------------------------------------------------------------------
// NOTE: screenWidth/screenHeight should match VR device aspect ratio
InitWindow(screenWidth, screenHeight, "raylib [core] example - vr simulator");
DisableCursor(); // Limit cursor to relative movement inside the window
SetTargetFPS(60); // Set our game to run at 60 frames-per-second
//--------------------------------------------------------------------------------------
var game = new VrSimulator();
game.Init();
// Main game loop
while (!WindowShouldClose()) // Detect window close button or ESC key
{
game.Update();
}
game.Unload();
// De-Initialization
//--------------------------------------------------------------------------------------
UnloadVrStereoConfig(config);
UnloadRenderTexture(target);
UnloadShader(distortion);
CloseWindow();
CloseWindow(); // Close window and OpenGL context
//--------------------------------------------------------------------------------------
return 0;

View file

@ -2,10 +2,14 @@
*
* raylib [core] example - window flags
*
* This example has been created using raylib 3.5 (www.raylib.com)
* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details)
* Example complexity rating: [] 3/4
*
* Copyright (c) 2020 Ramon Santamaria (@raysan5)
* Example originally created with raylib 3.5, last time updated with raylib 3.5
*
* Example licensed under an unmodified zlib/libpng license, which is an OSI-certified,
* BSD-like license that allows static linking with closed source software
*
* Copyright (c) 2020-2025 Ramon Santamaria (@raysan5)
*
********************************************************************************************/
@ -15,45 +19,31 @@ using static Raylib_cs.ConfigFlags;
namespace Examples.Core;
public class WindowFlags
public partial class WindowFlags : IExample
{
public static int Main()
private const int screenWidth = 800;
private const int screenHeight = 450;
public string Name => "Core / Window Flags";
public string Title => "raylib [core] example - window flags";
private Vector2 ballPosition;
private Vector2 ballSpeed;
private float ballRadius;
private int framesCounter = 0;
public void Init()
{
// Initialization
//---------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
ballPosition = new(GetScreenWidth() / 2.0f, GetScreenHeight() / 2.0f);
ballSpeed = new(5.0f, 4.0f);
ballRadius = 20;
// Possible window flags
/*
FLAG_VSYNC_HINT
FLAG_FULLSCREEN_MODE -> not working properly -> wrong scaling!
FLAG_WINDOW_RESIZABLE
FLAG_WINDOW_UNDECORATED
FLAG_WINDOW_TRANSPARENT
FLAG_WINDOW_HIDDEN
FLAG_WINDOW_MINIMIZED -> Not supported on window creation
FLAG_WINDOW_MAXIMIZED -> Not supported on window creation
FLAG_WINDOW_UNFOCUSED
FLAG_WINDOW_TOPMOST
FLAG_WINDOW_HIGHDPI -> errors after minimize-resize, fb size is recalculated
FLAG_WINDOW_ALWAYS_RUN
FLAG_MSAA_4X_HINT
*/
framesCounter = 0;
}
// Set configuration flags for window creation
SetConfigFlags(VSyncHint | Msaa4xHint);
InitWindow(screenWidth, screenHeight, "raylib [core] example - window flags");
Vector2 ballPosition = new(GetScreenWidth() / 2, GetScreenHeight() / 2);
Vector2 ballSpeed = new(5.0f, 4.0f);
int ballRadius = 20;
int framesCounter = 0;
//----------------------------------------------------------
// Main game loop
while (!WindowShouldClose())
public void Update()
{
// Update
//-----------------------------------------------------
@ -188,6 +178,11 @@ public class WindowFlags
}
}
if (IsKeyPressed(KeyboardKey.B))
{
ToggleBorderlessWindowed();
}
// Bouncing ball logic
ballPosition.X += ballSpeed.X;
ballPosition.Y += ballSpeed.Y;
@ -224,9 +219,6 @@ public class WindowFlags
DrawText($"Screen Size: [{GetScreenWidth()}, {GetScreenHeight()}]", 10, 40, 10, Color.Green);
// Draw window state info
Color on = Color.Lime;
Color off = Color.Maroon;
DrawText("Following flags can be set after window creation:", 10, 60, 10, Color.Gray);
DrawWindowState(FullscreenMode, "[F] FLAG_FULLSCREEN_MODE: ", 10, 80, 10);
@ -239,38 +231,81 @@ public class WindowFlags
DrawWindowState(TopmostWindow, "[T] FLAG_WINDOW_TOPMOST: ", 10, 220, 10);
DrawWindowState(AlwaysRunWindow, "[A] FLAG_WINDOW_ALWAYS_RUN: ", 10, 240, 10);
DrawWindowState(VSyncHint, "[V] FLAG_VSYNC_HINT: ", 10, 260, 10);
DrawWindowState(BorderlessWindowMode, "[B] FLAG_BORDERLESS_WINDOWED_MODE: ", 10, 280, 10);
DrawText("Following flags can only be set before window creation:", 10, 300, 10, Color.Gray);
DrawText("Following flags can only be set before window creation:", 10, 320, 10, Color.Gray);
DrawWindowState(HighDpiWindow, "[F] FLAG_WINDOW_HIGHDPI: ", 10, 320, 10);
DrawWindowState(TransparentWindow, "[F] FLAG_WINDOW_TRANSPARENT: ", 10, 340, 10);
DrawWindowState(Msaa4xHint, "[F] FLAG_MSAA_4X_HINT: ", 10, 360, 10);
DrawWindowState(HighDpiWindow, "FLAG_WINDOW_HIGHDPI: ", 10, 340, 10);
DrawWindowState(TransparentWindow, "FLAG_WINDOW_TRANSPARENT: ", 10, 360, 10);
DrawWindowState(Msaa4xHint, "FLAG_MSAA_4X_HINT: ", 10, 380, 10);
EndDrawing();
//-----------------------------------------------------
}
public void Unload()
{
}
public static int Main()
{
// Initialization
//---------------------------------------------------------
// Possible window flags
/*
FLAG_VSYNC_HINT
FLAG_FULLSCREEN_MODE -> not working properly -> wrong scaling!
FLAG_WINDOW_RESIZABLE
FLAG_WINDOW_UNDECORATED
FLAG_WINDOW_TRANSPARENT
FLAG_WINDOW_HIDDEN
FLAG_WINDOW_MINIMIZED -> Not supported on window creation
FLAG_WINDOW_MAXIMIZED -> Not supported on window creation
FLAG_WINDOW_UNFOCUSED
FLAG_WINDOW_TOPMOST
FLAG_WINDOW_HIGHDPI -> errors after minimize-resize, fb size is recalculated
FLAG_WINDOW_ALWAYS_RUN
FLAG_MSAA_4X_HINT
*/
// Set configuration flags for window creation
//SetConfigFlags(VSyncHint | Msaa4xHint | HighDpiWindow);// | TransparentWindow);
InitWindow(screenWidth, screenHeight, "raylib [core] example - window flags");
SetTargetFPS(60); // Set our game to run at 60 frames-per-second
//----------------------------------------------------------
var game = new WindowFlags();
game.Init();
// Main game loop
while (!WindowShouldClose()) // Detect window close button or ESC key
{
game.Update();
}
game.Unload();
// De-Initialization
//---------------------------------------------------------
CloseWindow();
CloseWindow(); // Close window and OpenGL context
//----------------------------------------------------------
return 0;
}
static void DrawWindowState(ConfigFlags flag, string text, int posX, int posY, int fontSize)
private static void DrawWindowState(ConfigFlags flag, string text, int posX, int posY, int fontSize)
{
Color onColor = Color.Lime;
Color offColor = Color.Maroon;
var onColor = Color.Lime;
var offColor = Color.Maroon;
if (Raylib.IsWindowState(flag))
{
DrawText($"{text} on", posX, posY, fontSize, onColor);
DrawText($"{text}on", posX, posY, fontSize, onColor);
}
else
{
DrawText($"{text} off", posX, posY, fontSize, offColor);
DrawText($"{text}off", posX, posY, fontSize, offColor);
}
}
}

View file

@ -1,13 +1,17 @@
/*******************************************************************************************
*
* raylib [core] example - window scale letterbox
* raylib [core] example - window letterbox
*
* This example has been created using raylib 2.5 (www.raylib.com)
* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details)
* Example complexity rating: [] 2/4
*
* Example originally created with raylib 2.5, last time updated with raylib 4.0
*
* Example contributed by Anata (@anatagawa) and reviewed by Ramon Santamaria (@raysan5)
*
* Copyright (c) 2019 Anata (@anatagawa) and Ramon Santamaria (@raysan5)
* Example licensed under an unmodified zlib/libpng license, which is an OSI-certified,
* BSD-like license that allows static linking with closed source software
*
* Copyright (c) 2019-2025 Anata (@anatagawa) and Ramon Santamaria (@raysan5)
*
********************************************************************************************/
@ -17,49 +21,50 @@ using static Raylib_cs.Raylib;
namespace Examples.Core;
public class WindowLetterbox
public partial class WindowLetterbox : IExample
{
public static int Main()
private const int windowWidth = 800;
private const int windowHeight = 450;
private const int gamescreenWidth = 640;
private const int gamescreenHeight = 480;
public string Name => "Core / Window Letterbox";
public string Title => "raylib [core] example - window letterbox";
public ConfigFlags ConfigFlags => ConfigFlags.ResizableWindow | ConfigFlags.VSyncHint;
private RenderTexture2D target;
private Color[] colors;
public void Init()
{
const int windowWidth = 800;
const int windowHeight = 450;
// Enable config flags for resizable window and vertical synchro
SetConfigFlags(ConfigFlags.ResizableWindow | ConfigFlags.VSyncHint);
InitWindow(windowWidth, windowHeight, "raylib [core] example - window scale letterbox");
SetWindowMinSize(320, 240);
int gameScreenWidth = 640;
int gameScreenHeight = 480;
// Render texture initialization, used to hold the rendering result so we can easily resize it
RenderTexture2D target = LoadRenderTexture(gameScreenWidth, gameScreenHeight);
SetTextureFilter(target.Texture, TextureFilter.Bilinear);
target = LoadRenderTexture(gamescreenWidth, gamescreenHeight);
SetTextureFilter(target.Texture, TextureFilter.Bilinear); // Texture scale filter to use
Color[] colors = new Color[10];
for (int i = 0; i < 10; i++)
colors = new Color[10];
for (var i = 0; i < 10; i++)
{
colors[i] = new Color(GetRandomValue(100, 250), GetRandomValue(50, 150), GetRandomValue(10, 100), 255);
}
}
SetTargetFPS(60);
//--------------------------------------------------------------------------------------
// Main game loop
while (!WindowShouldClose())
public void Update()
{
// Update
//----------------------------------------------------------------------------------
// Compute required framebuffer scaling
float scale = MathF.Min(
(float)GetScreenWidth() / gameScreenWidth,
(float)GetScreenHeight() / gameScreenHeight
var scale = MathF.Min(
(float)GetScreenWidth() / gamescreenWidth,
(float)GetScreenHeight() / gamescreenHeight
);
if (IsKeyPressed(KeyboardKey.Space))
{
// Recalculate random colors for the bars
for (int i = 0; i < 10; i++)
for (var i = 0; i < 10; i++)
{
colors[i] = new Color(
GetRandomValue(100, 250),
@ -71,27 +76,28 @@ public class WindowLetterbox
}
// Update virtual mouse (clamped mouse value behind game screen)
Vector2 mouse = GetMousePosition();
Vector2 virtualMouse = Vector2.Zero;
virtualMouse.X = (mouse.X - (GetScreenWidth() - (gameScreenWidth * scale)) * 0.5f) / scale;
virtualMouse.Y = (mouse.Y - (GetScreenHeight() - (gameScreenHeight * scale)) * 0.5f) / scale;
var mouse = GetMousePosition();
var virtualMouse = Vector2.Zero;
virtualMouse.X = (mouse.X - (GetScreenWidth() - (gamescreenWidth * scale)) * 0.5f) / scale;
virtualMouse.Y = (mouse.Y - (GetScreenHeight() - (gamescreenHeight * scale)) * 0.5f) / scale;
Vector2 max = new((float)gameScreenWidth, (float)gameScreenHeight);
Vector2 max = new((float)gamescreenWidth, (float)gamescreenHeight);
virtualMouse = Vector2.Clamp(virtualMouse, Vector2.Zero, max);
// Apply the same transformation as the virtual mouse to the real mouse (i.e. to work with raygui)
//SetMouseOffset(-(GetScreenWidth() - (gamescreenWidth*scale))*0.5f, -(GetScreenHeight() - (gamescreenHeight*scale))*0.5f);
//SetMouseScale(1/scale, 1/scale);
//----------------------------------------------------------------------------------
// Draw
//----------------------------------------------------------------------------------
BeginDrawing();
ClearBackground(Color.Black);
// Draw everything in the render texture, note this will not be rendered on screen, yet
BeginTextureMode(target);
ClearBackground(Color.RayWhite);
ClearBackground(Color.RayWhite); // Clear render texture background color
for (int i = 0; i < 10; i++)
for (var i = 0; i < 10; i++)
{
DrawRectangle(0, (gameScreenHeight / 10) * i, gameScreenWidth, gameScreenHeight / 10, colors[i]);
DrawRectangle(0, (gamescreenHeight / 10) * i, gamescreenWidth, gamescreenHeight / 10, colors[i]);
}
DrawText(
@ -102,12 +108,15 @@ public class WindowLetterbox
Color.White
);
DrawText($"Default Mouse: [{(int)mouse.X} {(int)mouse.Y}]", 350, 25, 20, Color.Green);
DrawText($"Virtual Mouse: [{(int)virtualMouse.X}, {(int)virtualMouse.Y}]", 350, 55, 20, Color.Yellow);
DrawText($"Default Mouse: [{(int)mouse.X} , {(int)mouse.Y}]", 350, 25, 20, Color.Green);
DrawText($"Virtual Mouse: [{(int)virtualMouse.X} , {(int)virtualMouse.Y}]", 350, 55, 20, Color.Yellow);
EndTextureMode();
// Draw RenderTexture2D to window, properly scaled
BeginDrawing();
ClearBackground(Color.Black); // Clear screen background
// Draw render texture to screen, properly scaled
Rectangle sourceRec = new(
0.0f,
0.0f,
@ -115,10 +124,10 @@ public class WindowLetterbox
(float)-target.Texture.Height
);
Rectangle destRec = new(
(GetScreenWidth() - ((float)gameScreenWidth * scale)) * 0.5f,
(GetScreenHeight() - ((float)gameScreenHeight * scale)) * 0.5f,
(float)gameScreenWidth * scale,
(float)gameScreenHeight * scale
(GetScreenWidth() - ((float)gamescreenWidth * scale)) * 0.5f,
(GetScreenHeight() - ((float)gamescreenHeight * scale)) * 0.5f,
(float)gamescreenWidth * scale,
(float)gamescreenHeight * scale
);
DrawTexturePro(target.Texture, sourceRec, destRec, new Vector2(0, 0), 0.0f, Color.White);
@ -126,14 +135,39 @@ public class WindowLetterbox
//--------------------------------------------------------------------------------------
}
public void Unload()
{
UnloadRenderTexture(target); // Unload render texture
}
public static int Main()
{
// Initialization
//--------------------------------------------------------------------------------------
// Enable config flags for resizable window and vertical synchro
SetConfigFlags(ConfigFlags.ResizableWindow | ConfigFlags.VSyncHint);
InitWindow(windowWidth, windowHeight, "raylib [core] example - window letterbox");
SetWindowMinSize(320, 240);
SetTargetFPS(60); // Set our game to run at 60 frames-per-second
//--------------------------------------------------------------------------------------
var game = new WindowLetterbox();
game.Init();
// Main game loop
while (!WindowShouldClose()) // Detect window close button or ESC key
{
game.Update();
}
game.Unload();
// De-Initialization
//--------------------------------------------------------------------------------------
UnloadRenderTexture(target);
CloseWindow();
CloseWindow(); // Close window and OpenGL context
//--------------------------------------------------------------------------------------
return 0;
}
}

View file

@ -1,11 +1,15 @@
/*******************************************************************************************
*
* raylib [core] example - World to screen
* raylib [core] example - world screen
*
* 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)
* Example complexity rating: [] 2/4
*
* Copyright (c) 2015 Ramon Santamaria (@raysan5)
* Example originally created with raylib 1.3, last time updated with raylib 1.4
*
* Example licensed under an unmodified zlib/libpng license, which is an OSI-certified,
* BSD-like license that allows static linking with closed source software
*
* Copyright (c) 2015-2025 Ramon Santamaria (@raysan5)
*
********************************************************************************************/
@ -14,37 +18,39 @@ using static Raylib_cs.Raylib;
namespace Examples.Core;
public class WorldScreen
public partial class WorldScreen : IExample
{
public static int Main()
private const int screenWidth = 800;
private const int screenHeight = 450;
public string Name => "Core / World to Screen";
public string Title => "raylib [core] example - world screen";
public bool CursorDisabled => true;
private Camera3D camera;
private Vector3 cubePosition;
private Vector2 cubeScreenPosition = new(0.0f, 0.0f);
public void Init()
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [core] example - 3d camera free");
// Define the camera to look into our 3d world
Camera3D camera = new();
camera.Position = new Vector3(10.0f, 10.0f, 10.0f);
camera.Target = new Vector3(0.0f, 0.0f, 0.0f);
camera.Up = new Vector3(0.0f, 1.0f, 0.0f);
camera.FovY = 45.0f;
camera.Projection = CameraProjection.Perspective;
camera = new();
camera.Position = new Vector3(10.0f, 10.0f, 10.0f); // Camera position
camera.Target = new Vector3(0.0f, 0.0f, 0.0f); // Camera looking at point
camera.Up = new Vector3(0.0f, 1.0f, 0.0f); // Camera up vector (rotation towards target)
camera.FovY = 45.0f; // Camera field-of-view Y
camera.Projection = CameraProjection.Perspective; // Camera projection type
Vector3 cubePosition = new(0.0f, 0.0f, 0.0f);
Vector2 cubeScreenPosition;
cubePosition = new(0.0f, 0.0f, 0.0f);
}
SetTargetFPS(60);
//--------------------------------------------------------------------------------------
// Main game loop
while (!WindowShouldClose())
public void Update()
{
// Update
//----------------------------------------------------------------------------------
UpdateCamera(ref camera, CameraMode.Free);
UpdateCamera(ref camera, CameraMode.ThirdPerson);
// Calculate cube screen space position (with a little offset to be in top)
cubeScreenPosition = GetWorldToScreen(
@ -68,30 +74,57 @@ public class WorldScreen
EndMode3D();
DrawText(
"Enemy: 100 / 100",
(int)cubeScreenPosition.X - MeasureText("Enemy: 100 / 100", 20) / 2,
"Enemy: 100/100",
(int)cubeScreenPosition.X - MeasureText("Enemy: 100/100", 20) / 2,
(int)cubeScreenPosition.Y,
20,
Color.Black
);
DrawText(
"Text is always on top of the cube",
(screenWidth - MeasureText("Text is always on top of the cube", 20)) / 2,
25,
$"Cube position in screen space coordinates: [{(int)cubeScreenPosition.X}, {(int)cubeScreenPosition.Y}]",
10,
10,
20,
Color.Gray
Color.Lime
);
DrawText("Text 2d should be always on top of the cube", 10, 40, 20, Color.Gray);
EndDrawing();
//----------------------------------------------------------------------------------
}
public void Unload()
{
}
public static int Main()
{
// Initialization
//--------------------------------------------------------------------------------------
InitWindow(screenWidth, screenHeight, "raylib [core] example - world screen");
DisableCursor(); // Limit cursor to relative movement inside the window
SetTargetFPS(60); // Set our game to run at 60 frames-per-second
//--------------------------------------------------------------------------------------
var game = new WorldScreen();
game.Init();
// Main game loop
while (!WindowShouldClose()) // Detect window close button or ESC key
{
game.Update();
}
game.Unload();
// De-Initialization
//--------------------------------------------------------------------------------------
CloseWindow();
CloseWindow(); // Close window and OpenGL context
//--------------------------------------------------------------------------------------
return 0;
}
}

View file

@ -0,0 +1,73 @@
using System.Diagnostics.CodeAnalysis;
using Examples.Core;
using Examples.Models;
using Examples.Shapes;
namespace Examples;
/// <summary>
/// Discovers every <see cref="IExample"/> implementation in this assembly via reflection and
/// derives the per-platform lists: <see cref="DesktopExamples"/> (Program.cs) and
/// <see cref="BrowserExamples"/> (Web/Host.cs). Ordering is by category (browser dropdown
/// grouping), then display name.
/// </summary>
public static class ExampleRegistry
{
/// <summary>Category order used for the browser dropdown and desktop run-all sequence.</summary>
private static readonly string[] CategoryOrder =
[
"Core",
"Shapes",
"Models",
"Textures",
"Text",
"Audio",
"Shaders",
];
/// <summary>Desktop examples omitted from the browser host (platform limitations).</summary>
private static readonly Type[] DesktopExcludedFromBrowser =
[
typeof(DropFiles),
typeof(LoadingThread), // System.Threading.Thread is unsupported on single-threaded wasm
typeof(SkyboxDemo),
];
/// <summary>Browser-only shape examples not registered for desktop CLI runs.</summary>
private static readonly Type[] BrowserOnly =
[
typeof(DrawCircleSector),
typeof(DrawRectangleRounded),
typeof(DrawRing),
];
private static readonly IExample[] AllExamples = DiscoverAll();
public static readonly IExample[] DesktopExamples =
Array.FindAll(AllExamples, e => Array.IndexOf(BrowserOnly, e.GetType()) < 0);
public static readonly IExample[] BrowserExamples =
Array.FindAll(AllExamples, e => Array.IndexOf(DesktopExcludedFromBrowser, e.GetType()) < 0);
[UnconditionalSuppressMessage("Trimming", "IL2026",
Justification = "The Examples assembly is rooted via TrimmerRootAssembly in Examples.csproj.")]
[UnconditionalSuppressMessage("Trimming", "IL2067",
Justification = "Same as IL2026: all example types and their parameterless constructors are rooted.")]
private static IExample[] DiscoverAll()
{
return typeof(IExample).Assembly
.GetTypes()
.Where(t => typeof(IExample).IsAssignableFrom(t) && t.IsClass && !t.IsAbstract)
.Select(t => (IExample)Activator.CreateInstance(t))
.OrderBy(e => Array.IndexOf(CategoryOrder, Category(e)))
.ThenBy(e => e.Name, StringComparer.OrdinalIgnoreCase)
.ToArray();
}
// "Examples.Core" -> "Core"
private static string Category(IExample example)
{
var ns = example.GetType().Namespace ?? "";
return ns[(ns.LastIndexOf('.') + 1)..];
}
}

View file

@ -3,23 +3,69 @@
<OutputType>Exe</OutputType>
<TargetFrameworks>net8.0;net10.0</TargetFrameworks>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<StartupObject>Examples.Program</StartupObject>
<StartupObject Condition="'$(RuntimeIdentifier)' != 'browser-wasm'">Examples.Program</StartupObject>
<StartupObject Condition="'$(RuntimeIdentifier)' == 'browser-wasm'">Examples.Web.Host</StartupObject>
<RunWorkingDirectory>$(MSBuildThisFileDirectory)</RunWorkingDirectory>
<LangVersion>12</LangVersion>
<ImplicitUsings>enable</ImplicitUsings>
<IsPackable>false</IsPackable>
</PropertyGroup>
<PropertyGroup Condition="'$(RuntimeIdentifier)' == 'browser-wasm'">
<WasmMainJSPath>Web/main.js</WasmMainJSPath>
<Nullable>disable</Nullable>
<!-- [JSExport] is browser-only by design; these files only compile for browser-wasm. -->
<NoWarn>$(NoWarn);CA1416</NoWarn>
<DefineConstants>$(DefineConstants);BROWSER</DefineConstants>
<!-- Link the native raylib.a (shipped by the Raylib-cs package) into the wasm module. -->
<WasmBuildNative>true</WasmBuildNative>
<WasmAllowUndefinedSymbols>true</WasmAllowUndefinedSymbols>
<InvariantGlobalization>true</InvariantGlobalization>
<EmccFlags>$(EmccFlags) -sALLOW_MEMORY_GROWTH=1 -sINITIAL_MEMORY=64MB</EmccFlags>
<!-- Avoid wasm-opt on SDK/workload combinations where Binaryen rejects bulk-memory-opt. -->
<EmccLinkOptimizationFlag Condition="'$(EmccLinkOptimizationFlag)' == ''">-O0</EmccLinkOptimizationFlag>
<EmccCompileOptimizationFlag Condition="'$(EmccCompileOptimizationFlag)' == ''">-O0</EmccCompileOptimizationFlag>
<WasmNativeStrip Condition="'$(WasmNativeStrip)' == ''">false</WasmNativeStrip>
<WasmEmitSymbolMap Condition="'$(WasmEmitSymbolMap)' == ''">false</WasmEmitSymbolMap>
</PropertyGroup>
<ItemGroup>
<Compile Remove="Core/LoadingThread.cs"/>
<Compile Remove="Text/Unicode.cs"/>
</ItemGroup>
<ItemGroup Condition="'$(RuntimeIdentifier)' != 'browser-wasm'">
<Compile Remove="Web/**/*.cs"/>
</ItemGroup>
<ItemGroup Condition="'$(RuntimeIdentifier)' == 'browser-wasm'">
<Compile Remove="Program.cs"/>
<!-- Examples are discovered via reflection (ExampleRegistry);
therefore they must be excluded from trimming. -->
<TrimmerRootAssembly Include="Examples"/>
</ItemGroup>
<ItemGroup>
<Using Include="Raylib_cs"/>
<Using Include="Raylib_cs.Raylib" Static="true"/>
<Using Include="System.Numerics"/>
</ItemGroup>
<ItemGroup>
<PackageReference Include="Raylib-cs" Version="$(RaylibCsVersion)"/>
<ProjectReference Include="..\Raylib-cs\Raylib-cs.csproj"/>
</ItemGroup>
<Import Project="..\Raylib-cs\Raylib-cs.targets"/>
<ItemGroup Condition="'$(RuntimeIdentifier)' == 'browser-wasm'">
<WasmExtraFilesToDeploy Include="Web/index.html" TargetPath="index.html"/>
<WasmExtraFilesToDeploy Include="Web/main.js" TargetPath="main.js"/>
<WasmExtraFilesToDeploy Include="Web/scaleUtils.js" TargetPath="scaleUtils.js"/>
<WasmExtraFilesToDeploy Include="..\Raylib-cs\logo\raylib-cs.ico" TargetPath="favicon.ico"/>
<!-- Bundle the example assets into the wasm virtual filesystem at /resources/...
so examples load from "resources/..." work unchanged. -->
<WasmFilesToIncludeInFileSystem Include="resources\**\*.*"
TargetPath="resources\%(RecursiveDir)%(Filename)%(Extension)"/>
</ItemGroup>
</Project>

46
Examples/IExample.cs Normal file
View file

@ -0,0 +1,46 @@
namespace Examples;
/// <summary>
/// A runnable raylib example. Each example class implements this interface directly: loop-spanning
/// state from the original example's Main lives in instance fields, (re)initialized in
/// <see cref="Init"/> so re-selecting an example resets it.
///
/// <para>
/// Desktop runs the example via its <c>static Main()</c>, a thin driver that owns the window
/// (InitWindow/CloseWindow, SetTargetFPS and friends) and drives <see cref="Init"/>,
/// <see cref="Update"/>, and <see cref="Unload"/> around a blocking
/// <c>while (!WindowShouldClose())</c> loop. In the browser, <c>Web/Host.cs</c> owns the single
/// window and calls <see cref="Update"/> one frame at a time from JavaScript, so examples never
/// block. Platform divergences (e.g. GLSL 100 vs 330 shaders) are guarded with <c>#if BROWSER</c>,
/// preferably around a single constant so both platforms share one code path.
/// </para>
/// </summary>
public interface IExample
{
/// <summary>Display name shown in the navigation dropdown.</summary>
string Name { get; }
/// <summary>Window title, matching the example's standalone <c>Main()</c>.</summary>
string Title { get; }
/// <summary>Config flags the desktop runner applies before window creation.</summary>
ConfigFlags ConfigFlags => 0;
/// <summary>Target FPS the desktop runner sets after window creation.</summary>
int TargetFps => 60;
/// <summary>Whether the desktop runner disables the cursor (relative mouse movement).</summary>
bool CursorDisabled => false;
/// <summary>Whether the desktop runner hides the cursor.</summary>
bool CursorHidden => false;
/// <summary>One-time setup.</summary>
void Init();
/// <summary>Render one frame, including BeginDrawing/EndDrawing.</summary>
void Update();
/// <summary>Free resources.</summary>
void Unload();
}

View file

@ -1,11 +1,15 @@
/*******************************************************************************************
*
* raylib [models] example - Drawing billboards
* raylib [models] example - billboard rendering
*
* 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)
* Example complexity rating: [] 3/4
*
* Copyright (c) 2015 Ramon Santamaria (@raysan5)
* Example originally created with raylib 1.3, last time updated with raylib 3.5
*
* Example licensed under an unmodified zlib/libpng license, which is an OSI-certified,
* BSD-like license that allows static linking with closed source software
*
* Copyright (c) 2015-2025 Ramon Santamaria (@raysan5)
*
********************************************************************************************/
@ -14,59 +18,67 @@ using static Raylib_cs.Raylib;
namespace Examples.Models;
public class BillboardDemo
public partial class BillboardDemo : IExample
{
public static int Main()
private const int screenWidth = 800;
private const int screenHeight = 450;
public string Name => "Models / Billboard Demo";
public string Title => "raylib [models] example - billboard rendering";
private Camera3D camera;
private Texture2D bill;
private Vector3 billPositionStatic;
private Vector3 billPositionRotating;
private Rectangle source;
private Vector3 billUp;
private Vector2 size;
private Vector2 origin;
private float distanceStatic;
private float distanceRotating;
private float rotation;
public void Init()
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [models] example - drawing billboards");
// Define the camera to look into our 3d world
Camera3D camera = new();
camera.Position = new Vector3(5.0f, 4.0f, 5.0f);
camera.Target = new Vector3(0.0f, 2.0f, 0.0f);
camera.Up = new Vector3(0.0f, 1.0f, 0.0f);
camera.FovY = 45.0f;
camera.Projection = CameraProjection.Perspective;
camera = new();
camera.Position = new Vector3(5.0f, 4.0f, 5.0f); // Camera position
camera.Target = new Vector3(0.0f, 2.0f, 0.0f); // Camera looking at point
camera.Up = new Vector3(0.0f, 1.0f, 0.0f); // Camera up vector (rotation towards target)
camera.FovY = 45.0f; // Camera field-of-view Y
camera.Projection = CameraProjection.Perspective; // Camera projection type
// Our texture billboard
Texture2D bill = LoadTexture("resources/billboard.png");
bill = LoadTexture("resources/billboard.png"); // Our billboard texture
billPositionStatic = new(0.0f, 2.0f, 0.0f); // Position of static billboard
billPositionRotating = new(1.0f, 2.0f, 1.0f); // Position of rotating billboard
// Position of billboard billboard
Vector3 billPositionStatic = new(0.0f, 2.0f, 0.0f);
Vector3 billPositionRotating = new(1.0f, 2.0f, 1.0f);
// Entire billboard texture, source is used to take a segment from a larger texture.
Rectangle source = new(0.0f, 0.0f, (float)bill.Width, (float)bill.Height);
// Entire billboard texture, source is used to take a segment from a larger texture
source = new(0.0f, 0.0f, (float)bill.Width, (float)bill.Height);
// NOTE: Billboard locked on axis-Y
Vector3 billUp = new(0.0f, 1.0f, 0.0f);
billUp = new(0.0f, 1.0f, 0.0f);
// Set the height of the rotating billboard to 1.0 with the aspect ratio fixed
size = new(source.Width / source.Height, 1.0f);
// Rotate around origin
// Here we choose to rotate around the image center
// NOTE: (-1, 1) is the range where origin.X, origin.Y is inside the texture
Vector2 rotateOrigin = Vector2.Zero;
origin = size * 0.5f;
// Distance is needed for the correct billboard draw order
// Larger distance (further away from the camera) should be drawn prior to smaller distance.
float distanceStatic = 0.0f;
float distanceRotating = 0.0f;
// Larger distance (further away from the camera) should be drawn prior to smaller distance
distanceStatic = 0.0f;
distanceRotating = 0.0f;
rotation = 0.0f;
}
float rotation = 0.0f;
SetTargetFPS(60);
//--------------------------------------------------------------------------------------
// Main game loop
while (!WindowShouldClose())
public void Update()
{
// Update
//----------------------------------------------------------------------------------
UpdateCamera(ref camera, CameraMode.Orbital);
rotation += 0.4f;
distanceStatic = Vector3.Distance(camera.Position, billPositionStatic);
distanceRotating = Vector3.Distance(camera.Position, billPositionRotating);
@ -79,37 +91,17 @@ public class BillboardDemo
BeginMode3D(camera);
DrawGrid(10, 1.0f);
DrawGrid(10, 1.0f); // Draw a grid
// Draw order matters!
if (distanceStatic > distanceRotating)
{
DrawBillboard(camera, bill, billPositionStatic, 2.0f, Color.White);
DrawBillboardPro(
camera,
bill,
source,
billPositionRotating,
billUp,
new Vector2(1.0f, 1.0f),
rotateOrigin,
rotation,
Color.White
);
DrawBillboardPro(camera, bill, source, billPositionRotating, billUp, size, origin, rotation, Color.White);
}
else
{
DrawBillboardPro(
camera,
bill,
source,
billPositionRotating,
billUp,
new Vector2(1.0f, 1.0f),
rotateOrigin,
rotation,
Color.White
);
DrawBillboardPro(camera, bill, source, billPositionRotating, billUp, size, origin, rotation, Color.White);
DrawBillboard(camera, bill, billPositionStatic, 2.0f, Color.White);
}
@ -121,14 +113,36 @@ public class BillboardDemo
//----------------------------------------------------------------------------------
}
public void Unload()
{
UnloadTexture(bill); // Unload texture
}
public static int Main()
{
// Initialization
//--------------------------------------------------------------------------------------
InitWindow(screenWidth, screenHeight, "raylib [models] example - billboard rendering");
SetTargetFPS(60); // Set our game to run at 60 frames-per-second
//--------------------------------------------------------------------------------------
var game = new BillboardDemo();
game.Init();
// Main game loop
while (!WindowShouldClose()) // Detect window close button or ESC key
{
game.Update();
}
game.Unload();
// De-Initialization
//--------------------------------------------------------------------------------------
UnloadTexture(bill);
CloseWindow();
CloseWindow(); // Close window and OpenGL context
//--------------------------------------------------------------------------------------
return 0;
}
}

View file

@ -1,11 +1,15 @@
/*******************************************************************************************
*
* raylib [models] example - Detect basic 3d collisions (box vs sphere vs box)
* raylib [models] example - box collisions
*
* 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)
* Example complexity rating: [] 1/4
*
* Copyright (c) 2015 Ramon Santamaria (@raysan5)
* Example originally created with raylib 1.3, last time updated with raylib 3.5
*
* Example licensed under an unmodified zlib/libpng license, which is an OSI-certified,
* BSD-like license that allows static linking with closed source software
*
* Copyright (c) 2015-2025 Ramon Santamaria (@raysan5)
*
********************************************************************************************/
@ -14,42 +18,53 @@ using static Raylib_cs.Raylib;
namespace Examples.Models;
public class BoxCollisions
public partial class BoxCollisions : IExample
{
public static int Main()
private const int screenWidth = 800;
private const int screenHeight = 450;
public string Name => "Models / Box Collisions";
public string Title => "raylib [models] example - box collisions";
private Camera3D camera;
private Vector3 playerPosition;
private Vector3 playerSize;
private Color playerColor;
private Vector3 enemyBoxPos;
private Vector3 enemyBoxSize;
private Vector3 enemySpherePos;
private float enemySphereSize;
private bool collision;
public void Init()
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [models] example - box collisions");
// Define the camera to look into our 3d world
Camera3D camera = new();
camera = new();
camera.Position = new Vector3(0.0f, 10.0f, 10.0f);
camera.Target = new Vector3(0.0f, 0.0f, 0.0f);
camera.Up = new Vector3(0.0f, 1.0f, 0.0f);
camera.FovY = 45.0f;
camera.Projection = CameraProjection.Perspective;
Vector3 playerPosition = new(0.0f, 1.0f, 2.0f);
Vector3 playerSize = new(1.0f, 2.0f, 1.0f);
Color playerColor = Color.Green;
playerPosition = new(0.0f, 1.0f, 2.0f);
playerSize = new(1.0f, 2.0f, 1.0f);
playerColor = Color.Green;
Vector3 enemyBoxPos = new(-4.0f, 1.0f, 0.0f);
Vector3 enemyBoxSize = new(2.0f, 2.0f, 2.0f);
enemyBoxPos = new(-4.0f, 1.0f, 0.0f);
enemyBoxSize = new(2.0f, 2.0f, 2.0f);
Vector3 enemySpherePos = new(4.0f, 0.0f, 0.0f);
float enemySphereSize = 1.5f;
enemySpherePos = new(4.0f, 0.0f, 0.0f);
enemySphereSize = 1.5f;
bool collision = false;
collision = false;
}
SetTargetFPS(60); // Set our game to run at 60 frames-per-second
//--------------------------------------------------------------------------------------
// Main game loop
while (!WindowShouldClose())
public void Update()
{
// Update
//----------------------------------------------------------------------------------
@ -123,20 +138,45 @@ public class BoxCollisions
// Draw player
DrawCubeV(playerPosition, playerSize, playerColor);
DrawGrid(10, 1.0f);
DrawGrid(10, 1.0f); // Draw a grid
EndMode3D();
DrawText("Move player with cursors to collide", 220, 40, 20, Color.Gray);
DrawText("Move player with arrow keys to collide", 220, 40, 20, Color.Gray);
DrawFPS(10, 10);
EndDrawing();
//----------------------------------------------------------------------------------
}
public void Unload()
{
}
public static int Main()
{
// Initialization
//--------------------------------------------------------------------------------------
InitWindow(screenWidth, screenHeight, "raylib [models] example - box collisions");
SetTargetFPS(60); // Set our game to run at 60 frames-per-second
//--------------------------------------------------------------------------------------
var game = new BoxCollisions();
game.Init();
// Main game loop
while (!WindowShouldClose()) // Detect window close button or ESC key
{
game.Update();
}
game.Unload();
// De-Initialization
//--------------------------------------------------------------------------------------
CloseWindow();
CloseWindow(); // Close window and OpenGL context
//--------------------------------------------------------------------------------------
return 0;

View file

@ -1,11 +1,15 @@
/*******************************************************************************************
*
* raylib [models] example - Cubicmap loading and drawing
* raylib [models] example - cubicmap rendering
*
* This example has been created using raylib 1.8 (www.raylib.com)
* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details)
* Example complexity rating: [] 2/4
*
* Copyright (c) 2015 Ramon Santamaria (@raysan5)
* Example originally created with raylib 1.8, last time updated with raylib 3.5
*
* Example licensed under an unmodified zlib/libpng license, which is an OSI-certified,
* BSD-like license that allows static linking with closed source software
*
* Copyright (c) 2015-2025 Ramon Santamaria (@raysan5)
*
********************************************************************************************/
@ -14,49 +18,64 @@ using static Raylib_cs.Raylib;
namespace Examples.Models;
public class CubicmapDemo
public partial class CubicmapDemo : IExample
{
public static int Main()
private const int screenWidth = 800;
private const int screenHeight = 450;
public string Name => "Models / Cubicmap Demo";
public string Title => "raylib [models] example - cubicmap rendering";
private Camera3D camera;
private Texture2D cubicmap;
private Texture2D texture;
private Model model;
private Vector3 mapPosition;
private bool pause;
public void Init()
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [models] example - cubesmap loading and drawing");
// Define the camera to look into our 3d world
Camera3D camera = new();
camera.Position = new Vector3(16.0f, 14.0f, 16.0f);
camera.Target = new Vector3(0.0f, 0.0f, 0.0f);
camera.Up = new Vector3(0.0f, 1.0f, 0.0f);
camera.FovY = 45.0f;
camera.Projection = CameraProjection.Perspective;
camera = new();
camera.Position = new Vector3(16.0f, 14.0f, 16.0f); // Camera position
camera.Target = new Vector3(0.0f, 0.0f, 0.0f); // Camera looking at point
camera.Up = new Vector3(0.0f, 1.0f, 0.0f); // Camera up vector (rotation towards target)
camera.FovY = 45.0f; // Camera field-of-view Y
camera.Projection = CameraProjection.Perspective; // Camera projection type
Image image = LoadImage("resources/cubicmap.png");
Texture2D cubicmap = LoadTextureFromImage(image);
var image = LoadImage("resources/cubicmap.png"); // Load cubicmap image (RAM)
cubicmap = LoadTextureFromImage(image); // Convert image to texture to display (VRAM)
Mesh mesh = GenMeshCubicmap(image, new Vector3(1.0f, 1.0f, 1.0f));
Model model = LoadModelFromMesh(mesh);
var mesh = GenMeshCubicmap(image, new Vector3(1.0f, 1.0f, 1.0f));
model = LoadModelFromMesh(mesh);
// NOTE: By default each cube is mapped to one part of texture atlas
Texture2D texture = LoadTexture("resources/cubicmap_atlas.png");
texture = LoadTexture("resources/cubicmap_atlas.png"); // Load map texture
// Set map diffuse texture
Raylib.SetMaterialTexture(ref model, 0, MaterialMapIndex.Albedo, ref texture);
Vector3 mapPosition = new(-16.0f, 0.0f, -8.0f);
UnloadImage(image);
mapPosition = new(-16.0f, 0.0f, -8.0f); // Set model position
SetTargetFPS(60);
//--------------------------------------------------------------------------------------
UnloadImage(image); // Unload cubesmap image from RAM, already uploaded to VRAM
// Main game loop
while (!WindowShouldClose())
pause = false; // Pause camera orbital rotation (and zoom)
}
public void Update()
{
// Update
//----------------------------------------------------------------------------------
if (IsKeyPressed(KeyboardKey.P))
{
pause = !pause;
}
if (!pause)
{
UpdateCamera(ref camera, CameraMode.Orbital);
}
//----------------------------------------------------------------------------------
// Draw
@ -89,16 +108,38 @@ public class CubicmapDemo
//----------------------------------------------------------------------------------
}
public void Unload()
{
UnloadTexture(cubicmap); // Unload cubicmap texture
UnloadTexture(texture); // Unload map texture
UnloadModel(model); // Unload map model
}
public static int Main()
{
// Initialization
//--------------------------------------------------------------------------------------
InitWindow(screenWidth, screenHeight, "raylib [models] example - cubicmap rendering");
SetTargetFPS(60); // Set our game to run at 60 frames-per-second
//--------------------------------------------------------------------------------------
var game = new CubicmapDemo();
game.Init();
// Main game loop
while (!WindowShouldClose()) // Detect window close button or ESC key
{
game.Update();
}
game.Unload();
// De-Initialization
//--------------------------------------------------------------------------------------
UnloadTexture(cubicmap);
UnloadTexture(texture);
UnloadModel(model);
CloseWindow();
CloseWindow(); // Close window and OpenGL context
//--------------------------------------------------------------------------------------
return 0;
}
}

View file

@ -3,19 +3,28 @@ using static Raylib_cs.Raylib;
namespace Examples.Models;
public class DynamicMesh
public partial class DynamicMesh : IExample
{
public unsafe static int Main()
private const int screenWidth = 800;
private const int screenHeight = 450;
private const int triangleRows = 48;
private const int vertexRows = triangleRows + 1;
public string Name => "Models / Dynamic Mesh";
public string Title => "raylib [models] example - dynamic mesh";
private Camera3D camera;
private Mesh dynamicMesh;
private Texture2D texture;
private Color[] pixels;
private Material material;
public void Init()
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [models] example - dynamic mesh");
// Define the camera to look into our 3d world
Camera3D camera = new();
camera = new();
camera.Position = Vector3.One * 1.5f;
camera.Target = camera.Position + new Vector3(1f, -0.25f, 1f);
camera.Up = Vector3.UnitY;
@ -23,18 +32,14 @@ public class DynamicMesh
camera.Projection = CameraProjection.Perspective;
// Generate a dynamic mesh using utils to allocate/access mesh attribute data
const int triangleRows = 48;
const int vertexRows = triangleRows + 1;
Mesh dynamicMesh = new(vertexRows * vertexRows, triangleRows * triangleRows * 2);
dynamicMesh = new(vertexRows * vertexRows, triangleRows * triangleRows * 2);
dynamicMesh.AllocVertices();
dynamicMesh.AllocTexCoords();
dynamicMesh.AllocIndices();
Span<Vector3> vertices = dynamicMesh.VerticesAs<Vector3>();
Span<Vector2> texcoords = dynamicMesh.TexCoordsAs<Vector2>();
Span<ushort> indices = dynamicMesh.IndicesAs<ushort>();
var indices = dynamicMesh.IndicesAs<ushort>();
for (int z = 0, i = 0; z < triangleRows; z++)
{
for (int x = 0; x < triangleRows; x++, i += 6)
for (var x = 0; x < triangleRows; x++, i += 6)
{
indices[i + 0] = (ushort)(x + (z * vertexRows));
indices[i + 1] = (ushort)(indices[i] + vertexRows);
@ -47,32 +52,32 @@ public class DynamicMesh
UploadMesh(ref dynamicMesh, true);
// Allocate the texture
Image image = GenImageColor(triangleRows, triangleRows, Color.Blank);
Texture2D texture = LoadTextureFromImage(image);
Color[] pixels = new Color[texture.Width * texture.Height];
var image = GenImageColor(triangleRows, triangleRows, Color.Blank);
texture = LoadTextureFromImage(image);
pixels = new Color[texture.Width * texture.Height];
UnloadImage(image);
// Load the material
Material material = LoadMaterialDefault();
material = LoadMaterialDefault();
SetMaterialTexture(ref material, MaterialMapIndex.Diffuse, texture);
}
SetTargetFPS(60);
//--------------------------------------------------------------------------------------
// Main game loop
while (!WindowShouldClose())
public void Update()
{
// Update
//----------------------------------------------------------------------------------
float time = (float)GetTime();
var time = (float)GetTime();
Random random = new(42);
var vertices = dynamicMesh.VerticesAs<Vector3>();
var texcoords = dynamicMesh.TexCoordsAs<Vector2>();
for (int z = 0, i = 0; z < vertexRows; z++)
{
for (int x = 0; x < vertexRows; x++, i++)
for (var x = 0; x < vertexRows; x++, i++)
{
float noiseX = SmoothNoise(time + random.Next(10000));
float noiseZ = SmoothNoise(time + random.Next(10000));
var noiseX = SmoothNoise(time + random.Next(10000));
var noiseZ = SmoothNoise(time + random.Next(10000));
vertices[i].X = x + noiseX - .5f;
vertices[i].Y = (noiseX + noiseZ) / 2;
vertices[i].Z = z + noiseZ - .5f;
@ -85,7 +90,7 @@ public class DynamicMesh
for (int y = 0, i = 0; y < texture.Height; y++)
{
for (int x = 0; x < texture.Width; x++, i++)
for (var x = 0; x < texture.Width; x++, i++)
{
pixels[i] = new(32, 178, 170, 255);
pixels[i] = ColorBrightness(pixels[i], (SmoothNoise(time + random.Next(10000)) / 8) - (1 / 16f));
@ -108,12 +113,35 @@ public class DynamicMesh
//----------------------------------------------------------------------------------
}
// De-Initialization
//--------------------------------------------------------------------------------------
public void Unload()
{
UnloadMaterial(material);
// Raylib.UnloadTexture(texture); <- No need to unload the texture. UnloadMaterial(Material) already unloaded it for us
UnloadMesh(dynamicMesh);
}
public static int Main()
{
// Initialization
//--------------------------------------------------------------------------------------
InitWindow(screenWidth, screenHeight, "raylib [models] example - dynamic mesh");
SetTargetFPS(60);
//--------------------------------------------------------------------------------------
var game = new DynamicMesh();
game.Init();
// Main game loop
while (!WindowShouldClose())
{
game.Update();
}
game.Unload();
// De-Initialization
//--------------------------------------------------------------------------------------
CloseWindow();
//--------------------------------------------------------------------------------------

View file

@ -2,10 +2,14 @@
*
* raylib [models] example - first person maze
*
* This example has been created using raylib 2.5 (www.raylib.com)
* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details)
* Example complexity rating: [] 2/4
*
* Copyright (c) 2019 Ramon Santamaria (@raysan5)
* Example originally created with raylib 2.5, last time updated with raylib 3.5
*
* Example licensed under an unmodified zlib/libpng license, which is an OSI-certified,
* BSD-like license that allows static linking with closed source software
*
* Copyright (c) 2019-2025 Ramon Santamaria (@raysan5)
*
********************************************************************************************/
@ -14,63 +18,66 @@ using static Raylib_cs.Raylib;
namespace Examples.Models;
public class FirstPersonMaze
public unsafe partial class FirstPersonMaze : IExample
{
public unsafe static int Main()
private const int screenWidth = 800;
private const int screenHeight = 450;
public string Name => "Models / First Person Maze";
public string Title => "raylib [models] example - first person maze";
public bool CursorDisabled => true;
private Camera3D camera;
private Texture2D cubicmap;
private Texture2D texture;
private Model model;
private Color* mapPixels;
private Vector3 mapPosition;
public void Init()
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [models] example - first person maze");
// Define the camera to look into our 3d world
Camera3D camera = new();
camera.Position = new Vector3(0.2f, 0.4f, 0.2f);
camera.Target = new Vector3(0.0f, 0.0f, 0.0f);
camera.Up = new Vector3(0.0f, 1.0f, 0.0f);
camera.FovY = 45.0f;
camera.Projection = CameraProjection.Perspective;
camera = new();
camera.Position = new Vector3(0.2f, 0.4f, 0.2f); // Camera position
camera.Target = new Vector3(0.185f, 0.4f, 0.0f); // Camera looking at point
camera.Up = new Vector3(0.0f, 1.0f, 0.0f); // Camera up vector (rotation towards target)
camera.FovY = 45.0f; // Camera field-of-view Y
camera.Projection = CameraProjection.Perspective; // Camera projection type
Image imMap = LoadImage("resources/cubicmap.png");
Texture2D cubicmap = LoadTextureFromImage(imMap);
Mesh mesh = GenMeshCubicmap(imMap, new Vector3(1.0f, 1.0f, 1.0f));
Model model = LoadModelFromMesh(mesh);
var imMap = LoadImage("resources/cubicmap.png"); // Load cubicmap image (RAM)
cubicmap = LoadTextureFromImage(imMap); // Convert image to texture to display (VRAM)
var mesh = GenMeshCubicmap(imMap, new Vector3(1.0f, 1.0f, 1.0f));
model = LoadModelFromMesh(mesh);
// NOTE: By default each cube is mapped to one part of texture atlas
Texture2D texture = LoadTexture("resources/cubicmap_atlas.png");
texture = LoadTexture("resources/cubicmap_atlas.png"); // Load map texture
// Set map diffuse texture
Raylib.SetMaterialTexture(ref model, 0, MaterialMapIndex.Albedo, ref texture);
// Get map image data to be used for collision detection
Color* mapPixels = LoadImageColors(imMap);
UnloadImage(imMap);
mapPixels = LoadImageColors(imMap);
UnloadImage(imMap); // Unload image from RAM
Vector3 mapPosition = new(-16.0f, 0.0f, -8.0f);
Vector3 playerPosition = camera.Position;
mapPosition = new(-16.0f, 0.0f, -8.0f); // Set model position
}
SetTargetFPS(60);
//--------------------------------------------------------------------------------------
// Main game loop
while (!WindowShouldClose())
public void Update()
{
// Update
//----------------------------------------------------------------------------------
Vector3 oldCamPos = camera.Position;
var oldCamPos = camera.Position; // Store old camera position
UpdateCamera(ref camera, CameraMode.FirstPerson);
// Check player collision (we simplify to 2D collision detection)
Vector2 playerPos = new(camera.Position.X, camera.Position.Z);
var playerRadius = 0.1f; // Collision radius (player is modelled as a cilinder for collision)
// Collision radius (player is modelled as a cilinder for collision)
float playerRadius = 0.1f;
int playerCellX = (int)(playerPos.X - mapPosition.X + 0.5f);
int playerCellY = (int)(playerPos.Y - mapPosition.Z + 0.5f);
var playerCellX = (int)(playerPos.X - mapPosition.X + 0.5f);
var playerCellY = (int)(playerPos.Y - mapPosition.Z + 0.5f);
// Out-of-limits security check
if (playerCellX < 0)
@ -91,30 +98,26 @@ public class FirstPersonMaze
playerCellY = cubicmap.Height - 1;
}
// Check map collisions using image data and player position
// TODO: Improvement: Just check player surrounding cells for collision
for (int y = 0; y < cubicmap.Height; y++)
// Check map collisions using image data and player position against surrounding cells only
for (var y = playerCellY - 1; y <= playerCellY + 1; y++)
{
for (int x = 0; x < cubicmap.Width; x++)
// Avoid map accessing out of bounds
if ((y >= 0) && (y < cubicmap.Height))
{
Color* mapPixelsData = mapPixels;
// Collision: Color.white pixel, only check R channel
Rectangle rec = new(
mapPosition.X - 0.5f + x * 1.0f,
mapPosition.Z - 0.5f + y * 1.0f,
1.0f,
1.0f
);
bool collision = CheckCollisionCircleRec(playerPos, playerRadius, rec);
if ((mapPixelsData[y * cubicmap.Width + x].R == 255) && collision)
for (var x = playerCellX - 1; x <= playerCellX + 1; x++)
{
// NOTE: Collision: Only checking R channel for white pixel
if (((x >= 0) && (x < cubicmap.Width)) &&
(mapPixels[y * cubicmap.Width + x].R == 255) &&
(CheckCollisionCircleRec(playerPos, playerRadius,
new Rectangle(mapPosition.X - 0.5f + x * 1.0f, mapPosition.Z - 0.5f + y * 1.0f, 1.0f, 1.0f))))
{
// Collision detected, reset camera position
camera.Position = oldCamPos;
}
}
}
}
//----------------------------------------------------------------------------------
// Draw
@ -122,9 +125,8 @@ public class FirstPersonMaze
BeginDrawing();
ClearBackground(Color.RayWhite);
// Draw maze map
BeginMode3D(camera);
DrawModel(model, mapPosition, 1.0f, Color.White);
DrawModel(model, mapPosition, 1.0f, Color.White); // Draw maze map
EndMode3D();
DrawTextureEx(cubicmap, new Vector2(GetScreenWidth() - cubicmap.Width * 4 - 20, 20), 0.0f, 4.0f, Color.White);
@ -139,15 +141,40 @@ public class FirstPersonMaze
//----------------------------------------------------------------------------------
}
public void Unload()
{
UnloadImageColors(mapPixels); // Unload color array
UnloadTexture(cubicmap); // Unload cubicmap texture
UnloadTexture(texture); // Unload map texture
UnloadModel(model); // Unload map model
}
public static int Main()
{
// Initialization
//--------------------------------------------------------------------------------------
InitWindow(screenWidth, screenHeight, "raylib [models] example - first person maze");
DisableCursor(); // Limit cursor to relative movement inside the window
SetTargetFPS(60); // Set our game to run at 60 frames-per-second
//--------------------------------------------------------------------------------------
var game = new FirstPersonMaze();
game.Init();
// Main game loop
while (!WindowShouldClose()) // Detect window close button or ESC key
{
game.Update();
}
game.Unload();
// De-Initialization
//--------------------------------------------------------------------------------------
UnloadImageColors(mapPixels);
UnloadTexture(cubicmap);
UnloadTexture(texture);
UnloadModel(model);
CloseWindow();
CloseWindow(); // Close window and OpenGL context
//--------------------------------------------------------------------------------------
return 0;

View file

@ -1,11 +1,15 @@
/*******************************************************************************************
*
* raylib [models] example - Draw some basic geometric shapes (cube, sphere, cylinder...)
* raylib [models] example - geometric shapes
*
* 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)
* Example complexity rating: [] 1/4
*
* Copyright (c) 2014 Ramon Santamaria (@raysan5)
* Example originally created with raylib 1.0, last time updated with raylib 3.5
*
* Example licensed under an unmodified zlib/libpng license, which is an OSI-certified,
* BSD-like license that allows static linking with closed source software
*
* Copyright (c) 2014-2025 Ramon Santamaria (@raysan5)
*
********************************************************************************************/
@ -14,36 +18,30 @@ using static Raylib_cs.Raylib;
namespace Examples.Models;
public class GeometricShapes
public partial class GeometricShapes : IExample
{
public static int Main()
private const int screenWidth = 800;
private const int screenHeight = 450;
public string Name => "Models / Geometric Shapes";
public string Title => "raylib [models] example - geometric shapes";
private Camera3D camera;
public void Init()
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [models] example - geometric shapes");
// Define the camera to look into our 3d world
Camera3D camera = new();
camera = new();
camera.Position = new Vector3(0.0f, 10.0f, 10.0f);
camera.Target = new Vector3(0.0f, 0.0f, 0.0f);
camera.Up = new Vector3(0.0f, 1.0f, 0.0f);
camera.FovY = 45.0f;
camera.Projection = CameraProjection.Perspective;
}
SetTargetFPS(60); // Set our game to run at 60 frames-per-second
//--------------------------------------------------------------------------------------
// Main game loop
while (!WindowShouldClose())
public void Update()
{
// Update
//----------------------------------------------------------------------------------
// TODO: Update your variables here
//----------------------------------------------------------------------------------
// Draw
//----------------------------------------------------------------------------------
BeginDrawing();
@ -65,7 +63,10 @@ public class GeometricShapes
DrawCylinder(new Vector3(1.0f, 0.0f, -4.0f), 0.0f, 1.5f, 3.0f, 8, Color.Gold);
DrawCylinderWires(new Vector3(1.0f, 0.0f, -4.0f), 0.0f, 1.5f, 3.0f, 8, Color.Pink);
DrawGrid(10, 1.0f);
DrawCapsule(new Vector3(-3.0f, 1.5f, -4.0f), new Vector3(-4.0f, -1.0f, -4.0f), 1.2f, 8, 8, Color.Violet);
DrawCapsuleWires(new Vector3(-3.0f, 1.5f, -4.0f), new Vector3(-4.0f, -1.0f, -4.0f), 1.2f, 8, 8, Color.Purple);
DrawGrid(10, 1.0f); // Draw a grid
EndMode3D();
@ -75,9 +76,33 @@ public class GeometricShapes
//----------------------------------------------------------------------------------
}
public void Unload()
{
}
public static int Main()
{
// Initialization
//--------------------------------------------------------------------------------------
InitWindow(screenWidth, screenHeight, "raylib [models] example - geometric shapes");
SetTargetFPS(60); // Set our game to run at 60 frames-per-second
//--------------------------------------------------------------------------------------
var game = new GeometricShapes();
game.Init();
// Main game loop
while (!WindowShouldClose()) // Detect window close button or ESC key
{
game.Update();
}
game.Unload();
// De-Initialization
//--------------------------------------------------------------------------------------
CloseWindow();
CloseWindow(); // Close window and OpenGL context
//--------------------------------------------------------------------------------------
return 0;

View file

@ -1,11 +1,15 @@
/*******************************************************************************************
*
* raylib [models] example - Heightmap loading and drawing
* raylib [models] example - heightmap rendering
*
* This example has been created using raylib 1.8 (www.raylib.com)
* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details)
* Example complexity rating: [] 1/4
*
* Copyright (c) 2015 Ramon Santamaria (@raysan5)
* Example originally created with raylib 1.8, last time updated with raylib 3.5
*
* Example licensed under an unmodified zlib/libpng license, which is an OSI-certified,
* BSD-like license that allows static linking with closed source software
*
* Copyright (c) 2015-2025 Ramon Santamaria (@raysan5)
*
********************************************************************************************/
@ -14,43 +18,45 @@ using static Raylib_cs.Raylib;
namespace Examples.Models;
public class HeightmapDemo
public partial class HeightmapDemo : IExample
{
public static int Main()
private const int screenWidth = 800;
private const int screenHeight = 450;
public string Name => "Models / Heightmap Demo";
public string Title => "raylib [models] example - heightmap rendering";
private Camera3D camera;
private Texture2D texture;
private Model model;
private Vector3 mapPosition;
public void Init()
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [models] example - heightmap loading and drawing");
// Define our custom camera to look into our 3d world
Camera3D camera = new();
camera.Position = new Vector3(18.0f, 16.0f, 18.0f);
camera.Target = new Vector3(0.0f, 0.0f, 0.0f);
camera.Up = new Vector3(0.0f, 1.0f, 0.0f);
camera.FovY = 45.0f;
camera.Projection = CameraProjection.Perspective;
camera = new();
camera.Position = new Vector3(18.0f, 21.0f, 18.0f); // Camera position
camera.Target = new Vector3(0.0f, 0.0f, 0.0f); // Camera looking at point
camera.Up = new Vector3(0.0f, 1.0f, 0.0f); // Camera up vector (rotation towards target)
camera.FovY = 45.0f; // Camera field-of-view Y
camera.Projection = CameraProjection.Perspective; // Camera projection type
Image image = LoadImage("resources/heightmap.png");
Texture2D texture = LoadTextureFromImage(image);
var image = LoadImage("resources/heightmap.png"); // Load heightmap image (RAM)
texture = LoadTextureFromImage(image); // Convert image to texture (VRAM)
Mesh mesh = GenMeshHeightmap(image, new Vector3(16, 8, 16));
Model model = LoadModelFromMesh(mesh);
var mesh = GenMeshHeightmap(image, new Vector3(16, 8, 16)); // Generate heightmap mesh (RAM and VRAM)
model = LoadModelFromMesh(mesh); // Load model from generated mesh
// Set map diffuse texture
Raylib.SetMaterialTexture(ref model, 0, MaterialMapIndex.Albedo, ref texture);
Vector3 mapPosition = new(-8.0f, 0.0f, -8.0f);
mapPosition = new(-8.0f, 0.0f, -8.0f); // Define model position
UnloadImage(image);
UnloadImage(image); // Unload heightmap image from RAM, already uploaded to VRAM
}
SetTargetFPS(60);
//--------------------------------------------------------------------------------------
// Main game loop
while (!WindowShouldClose())
public void Update()
{
// Update
//----------------------------------------------------------------------------------
@ -79,12 +85,35 @@ public class HeightmapDemo
//----------------------------------------------------------------------------------
}
public void Unload()
{
UnloadTexture(texture); // Unload texture
UnloadModel(model); // Unload model
}
public static int Main()
{
// Initialization
//--------------------------------------------------------------------------------------
InitWindow(screenWidth, screenHeight, "raylib [models] example - heightmap rendering");
SetTargetFPS(60); // Set our game to run at 60 frames-per-second
//--------------------------------------------------------------------------------------
var game = new HeightmapDemo();
game.Init();
// Main game loop
while (!WindowShouldClose()) // Detect window close button or ESC key
{
game.Update();
}
game.Unload();
// De-Initialization
//--------------------------------------------------------------------------------------
UnloadTexture(texture);
UnloadModel(model);
CloseWindow();
CloseWindow(); // Close window and OpenGL context
//--------------------------------------------------------------------------------------
return 0;

View file

@ -25,52 +25,59 @@ using static Raylib_cs.Raylib;
namespace Examples.Models;
public class LoadingGltf
public partial class LoadingGltf : IExample
{
public static int Main()
private const int screenWidth = 800;
private const int screenHeight = 450;
public string Name => "Models / Loading GLTF";
public string Title => "raylib [models] example - loading gltf";
private Camera3D camera;
private Model model;
private Vector3 position;
private unsafe ModelAnimation* anims;
private int animCount;
private int animIndex;
private float animCurrentFrame;
public unsafe void Init()
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [models] example - loading gltf");
// Define the camera to look into our 3d world
Camera3D camera = new();
camera.Position = new Vector3(6.0f, 6.0f, 6.0f);
camera.Target = new Vector3(0.0f, 2.0f, 0.0f);
camera.Up = new Vector3(0.0f, 1.0f, 0.0f);
camera.FovY = 45.0f;
camera.Projection = CameraProjection.Perspective;
camera = new();
camera.Position = new Vector3(6.0f, 6.0f, 6.0f); // Camera position
camera.Target = new Vector3(0.0f, 2.0f, 0.0f); // Camera looking at point
camera.Up = new Vector3(0.0f, 1.0f, 0.0f); // Camera up vector (rotation towards target)
camera.FovY = 45.0f; // Camera field-of-view Y
camera.Projection = CameraProjection.Perspective; // Camera projection type
Model model = LoadModel("resources/models/gltf/robot.glb");
Vector3 position = new(0.0f, 0.0f, 0.0f);
// Load model
model = LoadModel("resources/models/gltf/robot.glb");
position = new(0.0f, 0.0f, 0.0f); // Set model world position
// Load animation data
var anims = LoadModelAnimations("resources/models/gltf/robot.glb");
// Load model animations
anims = LoadModelAnimations("resources/models/gltf/robot.glb", ref animCount);
// Animation playing variables
int animIndex = 0;
float animCurrentFrame = 0.0f;
animIndex = 0; // Current animation playing
animCurrentFrame = 0.0f; // Current animation frame
}
SetTargetFPS(60);
//--------------------------------------------------------------------------------------
// Main game loop
while (!WindowShouldClose())
public unsafe void Update()
{
// Update
//----------------------------------------------------------------------------------
UpdateCamera(ref camera, CameraMode.Orbital);
// Select current animation
if (IsKeyPressed(KeyboardKey.Right))
{
animIndex = (animIndex + 1) % anims.Length;
animIndex = (animIndex + 1) % animCount;
}
else if (IsKeyPressed(KeyboardKey.Left))
{
animIndex = (animIndex + anims.Length - 1) % anims.Length;
animIndex = (animIndex + animCount - 1) % animCount;
}
@ -103,15 +110,37 @@ public class LoadingGltf
//----------------------------------------------------------------------------------
}
public unsafe void Unload()
{
UnloadModelAnimations(anims, animCount); // Unload model animations data
UnloadModel(model); // Unload model
}
public static int Main()
{
// Initialization
//--------------------------------------------------------------------------------------
InitWindow(screenWidth, screenHeight, "raylib [models] example - loading gltf");
SetTargetFPS(60); // Set our game to run at 60 frames-per-second
//--------------------------------------------------------------------------------------
var game = new LoadingGltf();
game.Init();
// Main game loop
while (!WindowShouldClose()) // Detect window close button or ESC key
{
game.Update();
}
game.Unload();
// De-Initialization
//--------------------------------------------------------------------------------------
UnloadModelAnimations(anims);
UnloadModel(model);
CloseWindow();
CloseWindow(); // Close window and OpenGL context
//--------------------------------------------------------------------------------------
return 0;
}
}

View file

@ -25,42 +25,48 @@ using static Raylib_cs.Raylib;
namespace Examples.Models;
public class LoadingIqm
public partial class LoadingIqm : IExample
{
public unsafe static int Main()
private const int screenWidth = 800;
private const int screenHeight = 450;
public string Name => "Models / Loading IQM";
public string Title => "raylib [models] example - loading iqm";
private Camera3D camera;
private Model model;
private Texture2D texture;
private Vector3 position;
private unsafe ModelAnimation* anims;
private int animCount;
private int animIndex;
private float animCurrentFrame;
public unsafe void Init()
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [models] example - model animation");
// Define the camera to look into our 3d world
Camera3D camera = new();
camera.Position = new Vector3(10.0f, 10.0f, 10.0f);
camera.Target = new Vector3(0.0f, 4.0f, 0.0f);
camera.Up = new Vector3(0.0f, 1.0f, 0.0f);
camera.FovY = 45.0f;
camera.Projection = CameraProjection.Perspective;
camera = new();
camera.Position = new Vector3(10.0f, 10.0f, 10.0f); // Camera position
camera.Target = new Vector3(0.0f, 4.0f, 0.0f); // Camera looking at point
camera.Up = new Vector3(0.0f, 1.0f, 0.0f); // Camera up vector (rotation towards target)
camera.FovY = 45.0f; // Camera field-of-view Y
camera.Projection = CameraProjection.Perspective; // Camera mode type
Model model = LoadModel("resources/models/iqm/guy.iqm");
Texture2D texture = LoadTexture("resources/models/iqm/guytex.png");
Raylib.SetMaterialTexture(ref model, 0, MaterialMapIndex.Diffuse, ref texture);
Vector3 position = new(0.0f, 0.0f, 0.0f);
model = LoadModel("resources/models/iqm/guy.iqm"); // Load the animated model mesh and basic data
texture = LoadTexture("resources/models/iqm/guytex.png"); // Load model texture and set material
Raylib.SetMaterialTexture(ref model, 0, MaterialMapIndex.Diffuse, ref texture); // Set model material map texture
position = new(0.0f, 0.0f, 0.0f); // Set model position
// Load animation data
var anims = LoadModelAnimations("resources/models/iqm/guyanim.iqm");
anims = LoadModelAnimations("resources/models/iqm/guyanim.iqm", ref animCount);
// Animation playing variables
int animIndex = 0;
float animCurrentFrame = 0.0f;
animIndex = 0; // Current animation playing
animCurrentFrame = 0.0f; // Current animation frame (supporting interpolated frames)
}
SetTargetFPS(60);
//--------------------------------------------------------------------------------------
// Main game loop
while (!WindowShouldClose())
public unsafe void Update()
{
// Update
//----------------------------------------------------------------------------------
@ -102,16 +108,38 @@ public class LoadingIqm
//----------------------------------------------------------------------------------
}
public unsafe void Unload()
{
UnloadTexture(texture); // Unload texture
UnloadModelAnimations(anims, animCount); // Unload model animations data
UnloadModel(model); // Unload model
}
public static int Main()
{
// Initialization
//--------------------------------------------------------------------------------------
InitWindow(screenWidth, screenHeight, "raylib [models] example - loading iqm");
SetTargetFPS(60); // Set our game to run at 60 frames-per-second
//--------------------------------------------------------------------------------------
var game = new LoadingIqm();
game.Init();
// Main game loop
while (!WindowShouldClose()) // Detect window close button or ESC key
{
game.Update();
}
game.Unload();
// De-Initialization
//--------------------------------------------------------------------------------------
UnloadTexture(texture);
UnloadModelAnimations(anims);
UnloadModel(model);
CloseWindow();
CloseWindow(); // Close window and OpenGL context
//--------------------------------------------------------------------------------------
return 0;
}
}

View file

@ -3,19 +3,24 @@ using static Raylib_cs.Raylib;
namespace Examples.Models;
public class MeshDemo
public partial class MeshDemo : IExample
{
public unsafe static int Main()
private const int screenWidth = 800;
private const int screenHeight = 450;
public string Name => "Models / Mesh Demo";
public string Title => "raylib [models] example - mesh demo";
private Camera3D camera;
private Model model;
private Texture2D texture;
private float rotationAngle;
public void Init()
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [models] example - mesh demo");
// Define the camera to look into our 3d world
Camera3D camera = new();
camera = new();
camera.Position = Vector3.One * 1.5f;
camera.Target = Vector3.Zero;
camera.Up = Vector3.UnitY;
@ -28,10 +33,10 @@ public class MeshDemo
tetrahedron.AllocTexCoords();
tetrahedron.AllocColors();
tetrahedron.AllocIndices();
Span<Vector3> vertices = tetrahedron.VerticesAs<Vector3>();
Span<Vector2> texcoords = tetrahedron.TexCoordsAs<Vector2>();
Span<Color> colors = tetrahedron.ColorsAs<Color>();
Span<ushort> indices = tetrahedron.IndicesAs<ushort>();
var vertices = tetrahedron.VerticesAs<Vector3>();
var texcoords = tetrahedron.TexCoordsAs<Vector2>();
var colors = tetrahedron.ColorsAs<Color>();
var indices = tetrahedron.IndicesAs<ushort>();
// Coordinates for a regular tetrahedron
vertices[0] = new(MathF.Sqrt(8f / 9f), 0f, -1f / 3f);
@ -65,24 +70,21 @@ public class MeshDemo
indices[10] = 3;
indices[11] = 2;
float rotationAngle = 0f;
rotationAngle = 0f;
Raylib.UploadMesh(ref tetrahedron, false);
Model model = Raylib.LoadModelFromMesh(tetrahedron);
model = Raylib.LoadModelFromMesh(tetrahedron);
Image image = Raylib.GenImagePerlinNoise(16, 16, 0, 0, 1000f);
var image = Raylib.GenImagePerlinNoise(16, 16, 0, 0, 1000f);
Raylib.ImageBlurGaussian(ref image, 2);
Raylib.ImageColorBrightness(ref image, 100);
Raylib.ImageDither(ref image, 4, 4, 4, 4);
Texture2D texture = Raylib.LoadTextureFromImage(image);
texture = Raylib.LoadTextureFromImage(image);
Raylib.UnloadImage(image);
Raylib.SetMaterialTexture(ref model, 0, MaterialMapIndex.Diffuse, ref texture);
}
SetTargetFPS(60);
//--------------------------------------------------------------------------------------
// Main game loop
while (!WindowShouldClose())
public void Update()
{
// Update
//----------------------------------------------------------------------------------
@ -103,11 +105,34 @@ public class MeshDemo
//----------------------------------------------------------------------------------
}
// De-Initialization
//--------------------------------------------------------------------------------------
public void Unload()
{
UnloadTexture(texture);
UnloadModel(model);
}
public static int Main()
{
// Initialization
//--------------------------------------------------------------------------------------
InitWindow(screenWidth, screenHeight, "raylib [models] example - mesh demo");
SetTargetFPS(60);
//--------------------------------------------------------------------------------------
var game = new MeshDemo();
game.Init();
// Main game loop
while (!WindowShouldClose())
{
game.Update();
}
game.Unload();
// De-Initialization
//--------------------------------------------------------------------------------------
CloseWindow();
//--------------------------------------------------------------------------------------

View file

@ -1,11 +1,15 @@
/*******************************************************************************************
*
* raylib example - procedural mesh generation
* raylib [models] example - mesh generation
*
* This example has been created using raylib 1.8 (www.raylib.com)
* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details)
* Example complexity rating: [] 2/4
*
* Copyright (c) 2017 Ramon Santamaria (Ray San)
* Example originally created with raylib 1.8, last time updated with raylib 4.0
*
* Example licensed under an unmodified zlib/libpng license, which is an OSI-certified,
* BSD-like license that allows static linking with closed source software
*
* Copyright (c) 2017-2025 Ramon Santamaria (@raysan5)
*
********************************************************************************************/
@ -14,25 +18,31 @@ using static Raylib_cs.Raylib;
namespace Examples.Models;
public class MeshGeneration
public partial class MeshGeneration : IExample
{
public static int Main()
private const int screenWidth = 800;
private const int screenHeight = 450;
public string Name => "Models / Mesh Generation";
public string Title => "raylib [models] example - mesh generation";
private Texture2D texture;
private Model[] models;
private Camera3D camera;
private Vector3 position;
private int currentModel;
public void Init()
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [models] example - mesh generation");
// We generate a isChecked image for texturing
Image isChecked = GenImageChecked(2, 2, 1, 1, Color.Red, Color.Green);
Texture2D texture = LoadTextureFromImage(isChecked);
// We generate a checked image for texturing
var isChecked = GenImageChecked(2, 2, 1, 1, Color.Red, Color.Green);
texture = LoadTextureFromImage(isChecked);
UnloadImage(isChecked);
Model[] models = new Model[9];
models = new Model[9];
models[0] = LoadModelFromMesh(GenMeshPlane(2, 2, 5, 5));
models[0] = LoadModelFromMesh(GenMeshPlane(2, 2, 4, 3));
models[1] = LoadModelFromMesh(GenMeshCube(2.0f, 1.0f, 2.0f));
models[2] = LoadModelFromMesh(GenMeshSphere(2, 32, 32));
models[3] = LoadModelFromMesh(GenMeshHemiSphere(2, 16, 16));
@ -42,15 +52,17 @@ public class MeshGeneration
models[7] = LoadModelFromMesh(GenMeshPoly(5, 2.0f));
models[8] = LoadModelFromMesh(GenMeshCustom());
// Set isChecked texture as default diffuse component for all models material
for (int i = 0; i < models.Length; i++)
// NOTE: Generated meshes could be exported using ExportMesh()
// Set checked texture as default diffuse component for all models material
for (var i = 0; i < models.Length; i++)
{
// Set map diffuse texture
Raylib.SetMaterialTexture(ref models[i], 0, MaterialMapIndex.Albedo, ref texture);
}
// Define the camera to look into our 3d world
Camera3D camera = new();
camera = new();
camera.Position = new Vector3(5.0f, 5.0f, 5.0f);
camera.Target = new Vector3(0.0f, 0.0f, 0.0f);
camera.Up = new Vector3(0.0f, 1.0f, 0.0f);
@ -58,15 +70,12 @@ public class MeshGeneration
camera.Projection = CameraProjection.Perspective;
// Model drawing position
Vector3 position = new(0.0f, 0.0f, 0.0f);
position = new(0.0f, 0.0f, 0.0f);
int currentModel = 0;
currentModel = 0;
}
SetTargetFPS(60);
//--------------------------------------------------------------------------------------
// Main game loop
while (!WindowShouldClose())
public void Update()
{
// Update
//----------------------------------------------------------------------------------
@ -74,8 +83,24 @@ public class MeshGeneration
if (IsMouseButtonPressed(MouseButton.Left))
{
// Cycle between the textures
currentModel = (currentModel + 1) % models.Length;
currentModel = (currentModel + 1) % models.Length; // Cycle between the textures
}
if (IsKeyPressed(KeyboardKey.Right))
{
currentModel++;
if (currentModel >= models.Length)
{
currentModel = 0;
}
}
else if (IsKeyPressed(KeyboardKey.Left))
{
currentModel--;
if (currentModel < 0)
{
currentModel = models.Length - 1;
}
}
//----------------------------------------------------------------------------------
@ -87,13 +112,12 @@ public class MeshGeneration
BeginMode3D(camera);
DrawModel(models[currentModel], position, 1.0f, Color.White);
DrawGrid(10, 1.0f);
EndMode3D();
DrawRectangle(30, 400, 310, 30, ColorAlpha(Color.SkyBlue, 0.5f));
DrawRectangleLines(30, 400, 310, 30, ColorAlpha(Color.DarkBlue, 0.5f));
DrawRectangle(30, 400, 310, 30, Fade(Color.SkyBlue, 0.5f));
DrawRectangleLines(30, 400, 310, 30, Fade(Color.DarkBlue, 0.5f));
DrawText("MOUSE LEFT BUTTON to CYCLE PROCEDURAL MODELS", 40, 410, 10, Color.Blue);
switch (currentModel)
@ -123,7 +147,7 @@ public class MeshGeneration
DrawText("POLY", 680, 10, 20, Color.DarkBlue);
break;
case 8:
DrawText("Custom (triagnle)", 580, 10, 20, Color.DarkBlue);
DrawText("Custom (triangle)", 580, 10, 20, Color.DarkBlue);
break;
default:
break;
@ -133,17 +157,15 @@ public class MeshGeneration
//----------------------------------------------------------------------------------
}
// De-Initialization
//--------------------------------------------------------------------------------------
for (int i = 0; i < models.Length; i++)
public void Unload()
{
UnloadTexture(texture); // Unload texture
// Unload models data (GPU VRAM)
for (var i = 0; i < models.Length; i++)
{
UnloadModel(models[i]);
}
CloseWindow();
//--------------------------------------------------------------------------------------
return 0;
}
// Generate a simple triangle mesh from code
@ -153,9 +175,9 @@ public class MeshGeneration
mesh.AllocVertices();
mesh.AllocTexCoords();
mesh.AllocNormals();
Span<Vector3> vertices = mesh.VerticesAs<Vector3>();
Span<Vector2> texcoords = mesh.TexCoordsAs<Vector2>();
Span<Vector3> normals = mesh.NormalsAs<Vector3>();
var vertices = mesh.VerticesAs<Vector3>();
var texcoords = mesh.TexCoordsAs<Vector2>();
var normals = mesh.NormalsAs<Vector3>();
// Vertex at (0, 0, 0)
vertices[0] = new(0, 0, 0);
@ -177,4 +199,32 @@ public class MeshGeneration
return mesh;
}
public static int Main()
{
// Initialization
//--------------------------------------------------------------------------------------
InitWindow(screenWidth, screenHeight, "raylib [models] example - mesh generation");
SetTargetFPS(60); // Set our game to run at 60 frames-per-second
//--------------------------------------------------------------------------------------
var game = new MeshGeneration();
game.Init();
// Main game loop
while (!WindowShouldClose()) // Detect window close button or ESC key
{
game.Update();
}
game.Unload();
// De-Initialization
//--------------------------------------------------------------------------------------
CloseWindow(); // Close window and OpenGL context
//--------------------------------------------------------------------------------------
return 0;
}
}

View file

@ -1,12 +1,17 @@
/*******************************************************************************************
*
* raylib [models] example - Mesh picking in 3d mode, ground plane, triangle, mesh
* raylib [models] example - mesh picking
*
* This example has been created using raylib 1.7 (www.raylib.com)
* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details)
* Example complexity rating: [] 3/4
*
* Copyright (c) 2015 Ramon Santamaria (@raysan5)
* Example contributed by Joel Davis (@joeld42)
* Example originally created with raylib 1.7, last time updated with raylib 4.0
*
* Example contributed by Joel Davis (@joeld42) and reviewed by Ramon Santamaria (@raysan5)
*
* Example licensed under an unmodified zlib/libpng license, which is an OSI-certified,
* BSD-like license that allows static linking with closed source software
*
* Copyright (c) 2017-2025 Joel Davis (@joeld42) and Ramon Santamaria (@raysan5)
*
********************************************************************************************/
@ -16,19 +21,38 @@ using static Raylib_cs.Raymath;
namespace Examples.Models;
public class MeshPicking
public partial class MeshPicking : IExample
{
public unsafe static int Main()
private const int screenWidth = 800;
private const int screenHeight = 450;
public string Name => "Models / Mesh Picking";
public string Title => "raylib [models] example - mesh picking";
public bool CursorDisabled => true;
private Camera3D camera;
private Ray ray;
private Model tower;
private Texture2D texture;
private Vector3 towerPos;
private BoundingBox towerBBox;
private Vector3 g0;
private Vector3 g1;
private Vector3 g2;
private Vector3 g3;
private Vector3 ta;
private Vector3 tb;
private Vector3 tc;
private Vector3 bary;
private Vector3 sp;
private float sr;
public unsafe void Init()
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [models] example - mesh picking");
// Define the camera to look into our 3d world
Camera3D camera;
camera = new();
camera.Position = new Vector3(20.0f, 20.0f, 20.0f);
camera.Target = new Vector3(0.0f, 8.0f, 0.0f);
camera.Up = new Vector3(0.0f, 1.6f, 0.0f);
@ -36,39 +60,34 @@ public class MeshPicking
camera.Projection = CameraProjection.Perspective;
// Picking ray
Ray ray = new();
ray = new();
Model tower = LoadModel("resources/models/obj/turret.obj");
Texture2D texture = LoadTexture("resources/models/obj/turret_diffuse.png");
tower = LoadModel("resources/models/obj/turret.obj");
texture = LoadTexture("resources/models/obj/turret_diffuse.png");
Raylib.SetMaterialTexture(ref tower, 0, MaterialMapIndex.Albedo, ref texture);
Vector3 towerPos = new(0.0f, 0.0f, 0.0f);
BoundingBox towerBBox = GetMeshBoundingBox(tower.Meshes[0]);
towerPos = new(0.0f, 0.0f, 0.0f);
towerBBox = GetMeshBoundingBox(tower.Meshes[0]);
// Ground quad
Vector3 g0 = new(-50.0f, 0.0f, -50.0f);
Vector3 g1 = new(-50.0f, 0.0f, 50.0f);
Vector3 g2 = new(50.0f, 0.0f, 50.0f);
Vector3 g3 = new(50.0f, 0.0f, -50.0f);
g0 = new(-50.0f, 0.0f, -50.0f);
g1 = new(-50.0f, 0.0f, 50.0f);
g2 = new(50.0f, 0.0f, 50.0f);
g3 = new(50.0f, 0.0f, -50.0f);
// Test triangle
Vector3 ta = new(-25.0f, 0.5f, 0.0f);
Vector3 tb = new(-4.0f, 2.5f, 1.0f);
Vector3 tc = new(-8.0f, 6.5f, 0.0f);
ta = new(-25.0f, 0.5f, 0.0f);
tb = new(-4.0f, 2.5f, 1.0f);
tc = new(-8.0f, 6.5f, 0.0f);
Vector3 bary = new(0.0f, 0.0f, 0.0f);
bary = new(0.0f, 0.0f, 0.0f);
// Test sphere
Vector3 sp = new(-30.0f, 5.0f, 5.0f);
float sr = 4.0f;
sp = new(-30.0f, 5.0f, 5.0f);
sr = 4.0f;
}
SetTargetFPS(60);
//--------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------
// Main game loop
//--------------------------------------------------------------------------------------
while (!WindowShouldClose())
public unsafe void Update()
{
//----------------------------------------------------------------------------------
// Update
@ -93,16 +112,16 @@ public class MeshPicking
// Display information about closest hit
RayCollision collision = new();
string hitObjectName = "None";
var hitObjectName = "None";
collision.Distance = float.MaxValue;
collision.Hit = false;
Color cursorColor = Color.White;
var cursorColor = Color.White;
// Get ray and test against objects
ray = GetScreenToWorldRay(GetMousePosition(), camera);
// Check ray collision aginst ground quad
RayCollision groundHitInfo = GetRayCollisionQuad(ray, g0, g1, g2, g3);
// Check ray collision against ground quad
var groundHitInfo = GetRayCollisionQuad(ray, g0, g1, g2, g3);
if (groundHitInfo.Hit && (groundHitInfo.Distance < collision.Distance))
{
collision = groundHitInfo;
@ -111,7 +130,7 @@ public class MeshPicking
}
// Check ray collision against test triangle
RayCollision triHitInfo = GetRayCollisionTriangle(ray, ta, tb, tc);
var triHitInfo = GetRayCollisionTriangle(ray, ta, tb, tc);
if (triHitInfo.Hit && (triHitInfo.Distance < collision.Distance))
{
collision = triHitInfo;
@ -122,7 +141,7 @@ public class MeshPicking
}
// Check ray collision against test sphere
RayCollision sphereHitInfo = GetRayCollisionSphere(ray, sp, sr);
var sphereHitInfo = GetRayCollisionSphere(ray, sp, sr);
if ((sphereHitInfo.Hit) && (sphereHitInfo.Distance < collision.Distance))
{
collision = sphereHitInfo;
@ -131,7 +150,7 @@ public class MeshPicking
}
// Check ray collision against bounding box first, before trying the full ray-mesh test
RayCollision boxHitInfo = GetRayCollisionBox(ray, towerBBox);
var boxHitInfo = GetRayCollisionBox(ray, towerBBox);
if (boxHitInfo.Hit && boxHitInfo.Distance < collision.Distance)
{
collision = boxHitInfo;
@ -140,7 +159,7 @@ public class MeshPicking
// Check ray collision against model meshes
RayCollision meshHitInfo = new();
for (int m = 0; m < tower.MeshCount; m++)
for (var m = 0; m < tower.MeshCount; m++)
{
// NOTE: We consider the model.Transform for the collision check but
// it can be checked against any transform matrix, used when checking against same
@ -174,6 +193,8 @@ public class MeshPicking
BeginMode3D(camera);
// Draw the tower
// WARNING: If scale is different than 1.0f,
// not considered by GetRayCollisionModel()
DrawModel(tower, towerPos, 1.0f, Color.White);
// Draw the test triangle
@ -196,7 +217,7 @@ public class MeshPicking
DrawCube(collision.Point, 0.3f, 0.3f, 0.3f, cursorColor);
DrawCubeWires(collision.Point, 0.3f, 0.3f, 0.3f, Color.Red);
Vector3 normalEnd = collision.Point + collision.Normal;
var normalEnd = collision.Point + collision.Normal;
DrawLine3D(collision.Point, normalEnd, Color.Red);
}
@ -211,7 +232,7 @@ public class MeshPicking
if (collision.Hit)
{
int ypos = 70;
var ypos = 70;
DrawText($"Distance: {collision.Distance}", 10, ypos, 10, Color.Black);
@ -219,7 +240,7 @@ public class MeshPicking
DrawText($"Hit Norm: {collision.Normal}", 10, ypos + 30, 10, Color.Black);
if (triHitInfo.Hit)
if (triHitInfo.Hit && hitObjectName == "Triangle")
{
DrawText($"Barycenter: {bary}", 10, ypos + 45, 10, Color.Black);
}
@ -235,11 +256,36 @@ public class MeshPicking
//----------------------------------------------------------------------------------
}
// De-Initialization
//--------------------------------------------------------------------------------------
public void Unload()
{
UnloadModel(tower);
UnloadTexture(texture);
}
public static int Main()
{
// Initialization
//--------------------------------------------------------------------------------------
InitWindow(screenWidth, screenHeight, "raylib [models] example - mesh picking");
SetTargetFPS(60);
//--------------------------------------------------------------------------------------
var game = new MeshPicking();
game.Init();
//----------------------------------------------------------------------------------
// Main game loop
//--------------------------------------------------------------------------------------
while (!WindowShouldClose())
{
game.Update();
}
game.Unload();
// De-Initialization
//--------------------------------------------------------------------------------------
CloseWindow();
//--------------------------------------------------------------------------------------

View file

@ -1,13 +1,15 @@
/*******************************************************************************************
*
* raylib [models] example - Draw textured cube
* raylib [models] example - textured cube
*
* Example complexity rating: [] 2/4
*
* Example originally created with raylib 4.5, last time updated with raylib 4.5
*
* Example licensed under an unmodified zlib/libpng license, which is an OSI-certified,
* BSD-like license that allows static linking with closed source software
*
* Copyright (c) 2022-2023 Ramon Santamaria (@raysan5)
* Copyright (c) 2022-2025 Ramon Santamaria (@raysan5)
*
********************************************************************************************/
@ -16,19 +18,22 @@ using static Raylib_cs.Raylib;
namespace Examples.Models;
public class ModelCubeTexture
public partial class ModelCubeTexture : IExample
{
public static int Main()
private const int screenWidth = 800;
private const int screenHeight = 450;
public string Name => "Models / Model Cube Texture";
public string Title => "raylib [models] example - textured cube";
private Camera3D camera;
private Texture2D texture;
public void Init()
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [models] example - draw cube texture");
// Define the camera to look into our 3d world
Camera3D camera;
camera = new();
camera.Position = new Vector3(0.0f, 10.0f, 10.0f);
camera.Target = new Vector3(0.0f, 0.0f, 0.0f);
camera.Up = new Vector3(0.0f, 1.0f, 0.0f);
@ -36,18 +41,11 @@ public class ModelCubeTexture
camera.Projection = CameraProjection.Perspective;
// Load texture to be applied to the cubes sides
Texture2D texture = LoadTexture("resources/cubicmap_atlas.png");
texture = LoadTexture("resources/cubicmap_atlas.png");
}
SetTargetFPS(60);
//--------------------------------------------------------------------------------------
// Main game loop
while (!WindowShouldClose())
public void Update()
{
// Update
//----------------------------------------------------------------------------------
//----------------------------------------------------------------------------------
// Draw
//----------------------------------------------------------------------------------
BeginDrawing();
@ -77,19 +75,14 @@ public class ModelCubeTexture
//----------------------------------------------------------------------------------
}
// De-Initialization
//--------------------------------------------------------------------------------------
public void Unload()
{
UnloadTexture(texture);
CloseWindow();
//--------------------------------------------------------------------------------------
return 0;
}
// Draw cube textured
// NOTE: Cube position is the center position
static void DrawCubeTexture(
private static void DrawCubeTexture(
Texture2D texture,
Vector3 position,
float width,
@ -98,9 +91,9 @@ public class ModelCubeTexture
Color color
)
{
float x = position.X;
float y = position.Y;
float z = position.Z;
var x = position.X;
var y = position.Y;
var z = position.Z;
// Set desired texture to be enabled while drawing following vertex data
Rlgl.SetTexture(texture.Id);
@ -218,7 +211,7 @@ public class ModelCubeTexture
}
// Draw cube with texture piece applied to all faces
static void DrawCubeTextureRec(
private static void DrawCubeTextureRec(
Texture2D texture,
Rectangle source,
Vector3 position,
@ -228,11 +221,11 @@ public class ModelCubeTexture
Color color
)
{
float x = position.X;
float y = position.Y;
float z = position.Z;
float texWidth = (float)texture.Width;
float texHeight = (float)texture.Height;
var x = position.X;
var y = position.Y;
var z = position.Z;
var texWidth = (float)texture.Width;
var texHeight = (float)texture.Height;
// Set desired texture to be enabled while drawing following vertex data
Rlgl.SetTexture(texture.Id);
@ -312,5 +305,32 @@ public class ModelCubeTexture
Rlgl.SetTexture(0);
}
}
public static int Main()
{
// Initialization
//--------------------------------------------------------------------------------------
InitWindow(screenWidth, screenHeight, "raylib [models] example - textured cube");
SetTargetFPS(60);
//--------------------------------------------------------------------------------------
var game = new ModelCubeTexture();
game.Init();
// Main game loop
while (!WindowShouldClose())
{
game.Update();
}
game.Unload();
// De-Initialization
//--------------------------------------------------------------------------------------
CloseWindow();
//--------------------------------------------------------------------------------------
return 0;
}
}

View file

@ -1,20 +1,28 @@
/*******************************************************************************************
*
* raylib [models] example - Models loading
* raylib [models] example - loading
*
* raylib supports multiple models file formats:
* Example complexity rating: [] 1/4
*
* - OBJ > Text file, must include vertex position-texcoords-normals information,
* if files references some .mtl materials file, it will be loaded (or try to)
* - GLTF > Modern text/binary file format, includes lot of information and it could
* also reference external files, raylib will try loading mesh and materials data
* - IQM > Binary file format including mesh vertex data but also animation data,
* raylib can load .iqm animations.
* NOTE: raylib supports multiple models file formats:
*
* This example has been created using raylib 2.6 (www.raylib.com)
* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details)
* - OBJ > Text file format. Must include vertex position-texcoords-normals information,
* if .obj references some .mtl materials file, it will be tried to be loaded
* - GLTF/GLB > Text/binary file formats. Includes lot of information and it could
* also reference external files, mesh and materials data will be tried to be loaded
* - IQM > Binary file format. Includes mesh vertex data but also animation data,
* meshes and animation data can be loaded
* - VOX > Binary file format. MagikaVoxel mesh format:
* https://github.com/ephtracy/voxel-model/blob/master/MagicaVoxel-file-format-vox.txt
* - M3D > Binary file format. Model 3D format:
* https://bztsrc.gitlab.io/model3d
*
* Copyright (c) 2014-2019 Ramon Santamaria (@raysan5)
* Example originally created with raylib 2.0, last time updated with raylib 4.2
*
* Example licensed under an unmodified zlib/libpng license, which is an OSI-certified,
* BSD-like license that allows static linking with closed source software
*
* Copyright (c) 2014-2025 Ramon Santamaria (@raysan5)
*
********************************************************************************************/
@ -23,82 +31,95 @@ using static Raylib_cs.Raylib;
namespace Examples.Models;
public class ModelLoading
public partial class ModelLoading : IExample
{
public unsafe static int Main()
private const int screenWidth = 800;
private const int screenHeight = 450;
public string Name => "Models / Model Loading";
public string Title => "raylib [models] example - loading";
private Camera3D camera;
private Model model;
private Texture2D texture;
private Vector3 position;
private BoundingBox bounds;
private bool selected;
public unsafe void Init()
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [models] example - models loading");
// Define the camera to look into our 3d world
Camera3D camera = new();
camera.Position = new Vector3(50.0f, 50.0f, 50.0f);
camera.Target = new Vector3(0.0f, 10.0f, 0.0f);
camera.Up = new Vector3(0.0f, 1.0f, 0.0f);
camera.FovY = 45.0f;
camera.Projection = CameraProjection.Perspective;
camera = new();
camera.Position = new Vector3(50.0f, 50.0f, 50.0f); // Camera position
camera.Target = new Vector3(0.0f, 12.0f, 0.0f); // Camera looking at point
camera.Up = new Vector3(0.0f, 1.0f, 0.0f); // Camera up vector (rotation towards target)
camera.FovY = 45.0f; // Camera field-of-view Y
camera.Projection = CameraProjection.Perspective; // Camera mode type
Model model = LoadModel("resources/models/obj/castle.obj");
Texture2D texture = LoadTexture("resources/models/obj/castle_diffuse.png");
model = LoadModel("resources/models/obj/castle.obj"); // Load model
texture = LoadTexture("resources/models/obj/castle_diffuse.png"); // Load model texture
// Set map diffuse texture
Raylib.SetMaterialTexture(ref model, 0, MaterialMapIndex.Albedo, ref texture);
Vector3 position = new(0.0f, 0.0f, 0.0f);
BoundingBox bounds = GetMeshBoundingBox(model.Meshes[0]);
position = new(0.0f, 0.0f, 0.0f); // Set model position
bounds = GetMeshBoundingBox(model.Meshes[0]); // Set model bounds
// NOTE: bounds are calculated from the original size of the model,
// if model is scaled on drawing, bounds must be also scaled
bool selected = false;
selected = false;
}
SetTargetFPS(60);
//--------------------------------------------------------------------------------------
// Main game loop
while (!WindowShouldClose())
public unsafe void Update()
{
// Update
//----------------------------------------------------------------------------------
UpdateCamera(ref camera, CameraMode.Orbital);
#if BROWSER
// NOTE: Drag & drop file loading (IsFileDropped) is not available in the browser
// host, so it is skipped here. The default model stays loaded.
#else
// Load new models/textures on drag&drop
if (IsFileDropped())
{
string[] droppedFiles = Raylib.GetDroppedFiles();
var droppedFiles = Raylib.GetDroppedFiles();
if (droppedFiles.Length == 1)
if (droppedFiles.Length == 1) // Only support one file dropped
{
if (IsFileExtension(droppedFiles[0], ".obj") ||
IsFileExtension(droppedFiles[0], ".gltf") ||
IsFileExtension(droppedFiles[0], ".glb") ||
IsFileExtension(droppedFiles[0], ".vox") ||
IsFileExtension(droppedFiles[0], ".iqm") ||
IsFileExtension(droppedFiles[0], ".m3d")
IsFileExtension(droppedFiles[0], ".m3d") // Model file formats supported
)
{
UnloadModel(model);
model = LoadModel(droppedFiles[0]);
UnloadModel(model); // Unload previous model
model = LoadModel(droppedFiles[0]); // Load new model
// Set current map diffuse texture
Raylib.SetMaterialTexture(ref model, 0, MaterialMapIndex.Albedo, ref texture);
bounds = GetMeshBoundingBox(model.Meshes[0]);
// TODO: Move camera position from target enough distance to visualize model properly
// Move camera position from target enough distance to visualize model properly
camera.Position.X = bounds.Max.X + 10.0f;
camera.Position.Y = bounds.Max.Y + 10.0f;
camera.Position.Z = bounds.Max.Z + 10.0f;
}
else if (IsFileExtension(droppedFiles[0], ".png"))
else if (IsFileExtension(droppedFiles[0], ".png")) // Texture file formats supported
{
// Unload model texture and load new one
// Unload current model texture and load new one
UnloadTexture(texture);
texture = LoadTexture(droppedFiles[0]);
Raylib.SetMaterialTexture(ref model, 0, MaterialMapIndex.Albedo, ref texture);
}
}
}
#endif
// Select model on mouse click
if (IsMouseButtonPressed(MouseButton.Left))
@ -122,13 +143,13 @@ public class ModelLoading
BeginMode3D(camera);
DrawModel(model, position, 1.0f, Color.White);
DrawModel(model, position, 1.0f, Color.White); // Draw 3d model with texture
DrawGrid(20, 10.0f);
DrawGrid(20, 10.0f); // Draw a grid
if (selected)
{
DrawBoundingBox(bounds, Color.Green);
DrawBoundingBox(bounds, Color.Green); // Draw selection box
}
EndMode3D();
@ -147,11 +168,34 @@ public class ModelLoading
//----------------------------------------------------------------------------------
}
// De-Initialization
//--------------------------------------------------------------------------------------
public void Unload()
{
UnloadTexture(texture);
UnloadModel(model);
}
public static int Main()
{
// Initialization
//--------------------------------------------------------------------------------------
InitWindow(screenWidth, screenHeight, "raylib [models] example - loading");
SetTargetFPS(60);
//--------------------------------------------------------------------------------------
var game = new ModelLoading();
game.Init();
// Main game loop
while (!WindowShouldClose())
{
game.Update();
}
game.Unload();
// De-Initialization
//--------------------------------------------------------------------------------------
CloseWindow();
//--------------------------------------------------------------------------------------

View file

@ -1,13 +1,17 @@
/*******************************************************************************************
*
* raylib [models] example - Show the difference between perspective and orthographic projection
* raylib [models] example - orthographic projection
*
* This program is heavily based on the geometric objects example
* Example complexity rating: [] 1/4
*
* This example has been created using raylib 1.9.7 (www.raylib.com)
* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details)
* Example originally created with raylib 2.0, last time updated with raylib 3.7
*
* Copyright (c) 2018 Max Danielsson ref Ramon Santamaria (@raysan5)
* Example contributed by Max Danielsson (@autious) and reviewed by Ramon Santamaria (@raysan5)
*
* Example licensed under an unmodified zlib/libpng license, which is an OSI-certified,
* BSD-like license that allows static linking with closed source software
*
* Copyright (c) 2018-2025 Max Danielsson (@autious) and Ramon Santamaria (@raysan5)
*
********************************************************************************************/
@ -16,33 +20,32 @@ using static Raylib_cs.Raylib;
namespace Examples.Models;
public class OrthographicProjection
public partial class OrthographicProjection : IExample
{
public const float FOVY_PERSPECTIVE = 45.0f;
public const float WIDTH_ORTHOGRAPHIC = 10.0f;
public static int Main()
private const int screenWidth = 800;
private const int screenHeight = 450;
public string Name => "Models / Orthographic Projection";
public string Title => "raylib [models] example - orthographic projection";
private Camera3D camera;
public void Init()
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [models] example - geometric shapes");
// Define the camera to look into our 3d world
Camera3D camera = new();
camera = new();
camera.Position = new Vector3(0.0f, 10.0f, 10.0f);
camera.Target = new Vector3(0.0f, 0.0f, 0.0f);
camera.Up = new Vector3(0.0f, 1.0f, 0.0f);
camera.FovY = FOVY_PERSPECTIVE;
camera.Projection = CameraProjection.Perspective;
}
SetTargetFPS(60); // Set our game to run at 60 frames-per-second
//--------------------------------------------------------------------------------------
// Main game loop
while (!WindowShouldClose())
public void Update()
{
// Update
//----------------------------------------------------------------------------------
@ -82,7 +85,7 @@ public class OrthographicProjection
DrawCylinder(new Vector3(1.0f, 0.0f, -4.0f), 0.0f, 1.5f, 3.0f, 8, Color.Gold);
DrawCylinderWires(new Vector3(1.0f, 0.0f, -4.0f), 0.0f, 1.5f, 3.0f, 8, Color.Pink);
DrawGrid(10, 1.0f);
DrawGrid(10, 1.0f); // Draw a grid
EndMode3D();
@ -103,9 +106,33 @@ public class OrthographicProjection
//----------------------------------------------------------------------------------
}
public void Unload()
{
}
public static int Main()
{
// Initialization
//--------------------------------------------------------------------------------------
InitWindow(screenWidth, screenHeight, "raylib [models] example - orthographic projection");
SetTargetFPS(60); // Set our game to run at 60 frames-per-second
//--------------------------------------------------------------------------------------
var game = new OrthographicProjection();
game.Init();
// Main game loop
while (!WindowShouldClose()) // Detect window close button or ESC key
{
game.Update();
}
game.Unload();
// De-Initialization
//--------------------------------------------------------------------------------------
CloseWindow();
CloseWindow(); // Close window and OpenGL context
//--------------------------------------------------------------------------------------
return 0;

View file

@ -1,32 +1,49 @@
/*******************************************************************************************
*
* raylib [models] example - Skybox loading and drawing
* raylib [models] example - skybox rendering
*
* This example has been created using raylib 1.8 (www.raylib.com)
* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details)
* Example complexity rating: [] 2/4
*
* Copyright (c) 2017 Ramon Santamaria (@raysan5)
* Example originally created with raylib 1.8, last time updated with raylib 4.0
*
* Example licensed under an unmodified zlib/libpng license, which is an OSI-certified,
* BSD-like license that allows static linking with closed source software
*
* Copyright (c) 2017-2025 Ramon Santamaria (@raysan5)
*
********************************************************************************************/
using System;
using System.Numerics;
using static Raylib_cs.Raylib;
namespace Examples.Models;
public class SkyboxDemo
public partial class SkyboxDemo : IExample
{
public static int Main()
private const int screenWidth = 800;
private const int screenHeight = 450;
// GLSL version used for shaders (330 desktop, 100 web/GLES)
public const int GlslVersion = 330;
public string Name => "Models / Skybox Demo";
public string Title => "raylib [models] example - skybox rendering";
public bool CursorDisabled => true;
private Camera3D camera;
private Model skybox;
private bool useHdr;
private Shader shdrCubemap;
private string skyboxFileName;
private Texture2D panorama;
public void Init()
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [models] example - skybox loading and drawing");
// Define the camera to look into our 3d world
Camera3D camera = new();
camera = new();
camera.Position = new Vector3(1.0f, 1.0f, 1.0f);
camera.Target = new Vector3(4.0f, 1.0f, 4.0f);
camera.Up = new Vector3(0.0f, 1.0f, 0.0f);
@ -34,14 +51,19 @@ public class SkyboxDemo
camera.Projection = CameraProjection.Perspective;
// Load skybox model
Mesh cube = GenMeshCube(1.0f, 1.0f, 1.0f);
Model skybox = LoadModelFromMesh(cube);
var cube = GenMeshCube(1.0f, 1.0f, 1.0f);
skybox = LoadModelFromMesh(cube);
bool useHdr = false;
// Set this to true to use an HDR Texture
// NOTE: raylib must be built with HDR Support for this to work: SUPPORT_FILEFORMAT_HDR
useHdr = false;
// Load skybox shader and set required locations
// NOTE: Some locations are automatically set at shader loading
Shader shdrSkybox = LoadShader("resources/shaders/glsl330/skybox.vs", "resources/shaders/glsl330/skybox.fs");
var shdrSkybox = LoadShader(
$"resources/shaders/glsl{GlslVersion}/skybox.vs",
$"resources/shaders/glsl{GlslVersion}/skybox.fs"
);
Raylib.SetShaderValue(
shdrSkybox,
@ -67,9 +89,9 @@ public class SkyboxDemo
Raylib.SetMaterialShader(ref skybox, 0, ref shdrSkybox);
// Load cubemap shader and setup required shader locations
Shader shdrCubemap = LoadShader(
"resources/shaders/glsl330/cubemap.vs",
"resources/shaders/glsl330/cubemap.fs"
shdrCubemap = LoadShader(
$"resources/shaders/glsl{GlslVersion}/cubemap.vs",
$"resources/shaders/glsl{GlslVersion}/cubemap.fs"
);
Raylib.SetShaderValue(
shdrCubemap,
@ -79,14 +101,12 @@ public class SkyboxDemo
);
// Load skybox
string skyboxFileName = "resources/dresden_square_2k.hdr";
Texture2D panorama;
skyboxFileName = "resources/dresden_square_2k.hdr";
if (useHdr)
{
panorama = LoadTexture(skyboxFileName);
Texture2D cubemap = GenTextureCubemap(
var cubemap = GenTextureCubemap(
shdrCubemap,
panorama,
1024,
@ -97,19 +117,16 @@ public class SkyboxDemo
}
else
{
Image img = LoadImage("resources/skybox.png");
Texture2D cubemap = LoadTextureCubemap(img, CubemapLayout.AutoDetect);
// TODO: WARNING: On PLATFORM_WEB it requires a big amount of memory to process input image
// and generate the required cubemap image to be passed to rlLoadTextureCubemap()
var img = LoadImage("resources/skybox.png");
var cubemap = LoadTextureCubemap(img, CubemapLayout.AutoDetect);
SetMaterialTexture(ref skybox, 0, MaterialMapIndex.Cubemap, ref cubemap);
UnloadImage(img);
}
}
DisableCursor();
SetTargetFPS(60);
//--------------------------------------------------------------------------------------
// Main game loop
while (!WindowShouldClose())
public void Update()
{
// Update
//----------------------------------------------------------------------------------
@ -118,7 +135,7 @@ public class SkyboxDemo
// Load new cubemap texture on drag & drop
if (IsFileDropped())
{
string[] files = Raylib.GetDroppedFiles();
var files = Raylib.GetDroppedFiles();
if (files.Length == 1)
{
@ -130,7 +147,7 @@ public class SkyboxDemo
if (useHdr)
{
panorama = LoadTexture(files[0]);
Texture2D cubemap = GenTextureCubemap(
var cubemap = GenTextureCubemap(
shdrCubemap,
panorama,
1024,
@ -141,8 +158,8 @@ public class SkyboxDemo
}
else
{
Image img = LoadImage(files[0]);
Texture2D cubemap = LoadTextureCubemap(img, CubemapLayout.AutoDetect);
var img = LoadImage(files[0]);
var cubemap = LoadTextureCubemap(img, CubemapLayout.AutoDetect);
SetMaterialTexture(ref skybox, 0, MaterialMapIndex.Cubemap, ref cubemap);
UnloadImage(img);
}
@ -192,13 +209,38 @@ public class SkyboxDemo
//----------------------------------------------------------------------------------
}
// De-Initialization
//--------------------------------------------------------------------------------------
public void Unload()
{
UnloadShader(Raylib.GetMaterial(ref skybox, 0).Shader);
UnloadTexture(Raylib.GetMaterialTexture(ref skybox, 0, MaterialMapIndex.Cubemap));
UnloadModel(skybox);
}
public static int Main()
{
// Initialization
//--------------------------------------------------------------------------------------
InitWindow(screenWidth, screenHeight, "raylib [models] example - skybox rendering");
DisableCursor(); // Limit cursor to relative movement inside the window
SetTargetFPS(60);
//--------------------------------------------------------------------------------------
var game = new SkyboxDemo();
game.Init();
// Main game loop
while (!WindowShouldClose())
{
game.Update();
}
game.Unload();
// De-Initialization
//--------------------------------------------------------------------------------------
CloseWindow();
//--------------------------------------------------------------------------------------
@ -215,10 +257,10 @@ public class SkyboxDemo
// STEP 1: Setup framebuffer
//------------------------------------------------------------------------------------------
uint rbo = Rlgl.LoadTextureDepth(size, size, true);
var rbo = Rlgl.LoadTextureDepth(size, size, true);
cubemap.Id = Rlgl.LoadTextureCubemap(null, size, format, 1);
uint fbo = Rlgl.LoadFramebuffer();
var fbo = Rlgl.LoadFramebuffer();
Rlgl.FramebufferAttach(
fbo,
rbo,
@ -235,7 +277,7 @@ public class SkyboxDemo
);
// Check if framebuffer is complete with attachments (valid)
if (Rlgl.FramebufferComplete(fbo))
if (Rlgl.FramebufferComplete(fbo) != 0)
{
Console.WriteLine($"FBO: [ID {fbo}] Framebuffer object created successfully");
}
@ -247,7 +289,7 @@ public class SkyboxDemo
Rlgl.EnableShader(shader.Id);
// Define projection matrix and send it to shader
Matrix4x4 matFboProjection = Raymath.MatrixPerspective(
var matFboProjection = Raymath.MatrixPerspective(
90.0f * DEG2RAD,
1.0f,
Rlgl.CULL_DISTANCE_NEAR,
@ -256,14 +298,14 @@ public class SkyboxDemo
Rlgl.SetUniformMatrix(shader.Locs[(int)ShaderLocationIndex.MatrixProjection], matFboProjection);
// Define view matrix for every side of the cubemap
Matrix4x4[] fboViews = new[]
var fboViews = new[]
{
Raymath.MatrixLookAt(Vector3.Zero, new Vector3(-1.0f, 0.0f, 0.0f), new Vector3( 0.0f, -1.0f, 0.0f)),
Raymath.MatrixLookAt(Vector3.Zero, new Vector3( 1.0f, 0.0f, 0.0f), new Vector3( 0.0f, -1.0f, 0.0f)),
Raymath.MatrixLookAt(Vector3.Zero, new Vector3(-1.0f, 0.0f, 0.0f), new Vector3( 0.0f, -1.0f, 0.0f)),
Raymath.MatrixLookAt(Vector3.Zero, new Vector3( 0.0f, 1.0f, 0.0f), new Vector3( 0.0f, 0.0f, 1.0f)),
Raymath.MatrixLookAt(Vector3.Zero, new Vector3( 0.0f, -1.0f, 0.0f), new Vector3( 0.0f, 0.0f, -1.0f)),
Raymath.MatrixLookAt(Vector3.Zero, new Vector3( 0.0f, 0.0f, -1.0f), new Vector3( 0.0f, -1.0f, 0.0f)),
Raymath.MatrixLookAt(Vector3.Zero, new Vector3( 0.0f, 0.0f, 1.0f), new Vector3( 0.0f, -1.0f, 0.0f)),
Raymath.MatrixLookAt(Vector3.Zero, new Vector3( 0.0f, 0.0f, -1.0f), new Vector3( 0.0f, -1.0f, 0.0f)),
};
// Set viewport to current fbo dimensions
@ -273,7 +315,7 @@ public class SkyboxDemo
Rlgl.ActiveTextureSlot(0);
Rlgl.EnableTexture(panorama.Id);
for (int i = 0; i < 6; i++)
for (var i = 0; i < 6; i++)
{
// Set the view matrix for the current cube face
Rlgl.SetUniformMatrix(shader.Locs[(int)ShaderLocationIndex.MatrixView], fboViews[i]);

View file

@ -1,13 +1,17 @@
/*******************************************************************************************
*
* raylib [models] example - rlgl module usage with push/pop matrix transformations
* raylib [models] example - rlgl solar system
*
* This example uses [rlgl] module funtionality (pseudo-OpenGL 1.1 style coding)
* Example complexity rating: [] 4/4
*
* 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)
* NOTE: This example uses [rlgl] module functionality (pseudo-OpenGL 1.1 style coding)
*
* Copyright (c) 2018 Ramon Santamaria (@raysan5)
* Example originally created with raylib 2.5, last time updated with raylib 4.0
*
* Example licensed under an unmodified zlib/libpng license, which is an OSI-certified,
* BSD-like license that allows static linking with closed source software
*
* Copyright (c) 2018-2025 Ramon Santamaria (@raysan5)
*
********************************************************************************************/
@ -17,52 +21,52 @@ using static Raylib_cs.Raylib;
namespace Examples.Models;
public class SolarSystem
public partial class SolarSystem : IExample
{
public static int Main()
private const int screenWidth = 800;
private const int screenHeight = 450;
private const float sunRadius = 4.0f;
private const float earthRadius = 0.6f;
private const float earthOrbitRadius = 8.0f;
private const float moonRadius = 0.16f;
private const float moonOrbitRadius = 1.5f;
public string Name => "Models / Solar System";
public string Title => "raylib [models] example - rlgl solar system";
private Camera3D camera;
private float rotationSpeed;
private float earthRotation;
private float earthOrbitRotation;
private float moonRotation;
private float moonOrbitRotation;
public void Init()
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
const float sunRadius = 4.0f;
const float earthRadius = 0.6f;
const float earthOrbitRadius = 8.0f;
const float moonRadius = 0.16f;
const float moonOrbitRadius = 1.5f;
InitWindow(screenWidth, screenHeight, "raylib [models] example - rlgl module usage with push/pop matrix transformations");
// Define the camera to look into our 3d world
Camera3D camera = new();
camera.Position = new Vector3(16.0f, 16.0f, 16.0f);
camera.Target = new Vector3(0.0f, 0.0f, 0.0f);
camera.Up = new Vector3(0.0f, 1.0f, 0.0f);
camera.FovY = 45.0f;
camera.Projection = CameraProjection.Perspective;
camera = new();
camera.Position = new Vector3(16.0f, 16.0f, 16.0f); // Camera position
camera.Target = new Vector3(0.0f, 0.0f, 0.0f); // Camera looking at point
camera.Up = new Vector3(0.0f, 1.0f, 0.0f); // Camera up vector (rotation towards target)
camera.FovY = 45.0f; // Camera field-of-view Y
camera.Projection = CameraProjection.Perspective; // Camera projection type
// General system rotation speed
float rotationSpeed = 0.2f;
// Rotation of earth around itself (days) in degrees
float earthRotation = 0.0f;
// Rotation of earth around the Sun (years) in degrees
float earthOrbitRotation = 0.0f;
// Rotation of moon around itself
float moonRotation = 0.0f;
// Rotation of moon around earth in degrees
float moonOrbitRotation = 0.0f;
rotationSpeed = 0.2f; // General system rotation speed
SetTargetFPS(60);
//--------------------------------------------------------------------------------------
earthRotation = 0.0f; // Rotation of earth around itself (days) in degrees
earthOrbitRotation = 0.0f; // Rotation of earth around the Sun (years) in degrees
moonRotation = 0.0f; // Rotation of moon around itself
moonOrbitRotation = 0.0f; // Rotation of moon around earth in degrees
}
// Main game loop
while (!WindowShouldClose())
public void Update()
{
// Update
//----------------------------------------------------------------------------------
UpdateCamera(ref camera, CameraMode.Free);
earthRotation += (5.0f * rotationSpeed);
earthOrbitRotation += (365 / 360.0f * (5.0f * rotationSpeed) * rotationSpeed);
moonRotation += (2.0f * rotationSpeed);
@ -88,8 +92,6 @@ public class SolarSystem
Rlgl.Rotatef(earthOrbitRotation, 0.0f, 1.0f, 0.0f);
// Translation for Earth orbit
Rlgl.Translatef(earthOrbitRadius, 0.0f, 0.0f);
// Rotation for Earth orbit around Sun inverted
Rlgl.Rotatef(-earthOrbitRotation, 0.0f, 1.0f, 0.0f);
Rlgl.PushMatrix();
// Rotation for Earth itself
@ -105,8 +107,6 @@ public class SolarSystem
Rlgl.Rotatef(moonOrbitRotation, 0.0f, 1.0f, 0.0f);
// Translation for Moon orbit
Rlgl.Translatef(moonOrbitRadius, 0.0f, 0.0f);
// Rotation for Moon orbit around Earth inverted
Rlgl.Rotatef(-moonOrbitRotation, 0.0f, 1.0f, 0.0f);
// Rotation for Moon itself
Rlgl.Rotatef(moonRotation, 0.0f, 1.0f, 0.0f);
// Scale Moon
@ -122,7 +122,7 @@ public class SolarSystem
earthOrbitRadius,
new Vector3(1, 0, 0),
90.0f,
ColorAlpha(Color.Red, 0.5f)
Fade(Color.Red, 0.5f)
);
DrawGrid(20, 1.0f);
@ -135,27 +135,23 @@ public class SolarSystem
//----------------------------------------------------------------------------------
}
// De-Initialization
//--------------------------------------------------------------------------------------
CloseWindow();
//--------------------------------------------------------------------------------------
return 0;
public void Unload()
{
}
// Draw sphere without any matrix transformation
// NOTE: Sphere is drawn in world position ( 0, 0, 0 ) with radius 1.0f
static void DrawSphereBasic(Color color)
private static void DrawSphereBasic(Color color)
{
int rings = 16;
int slices = 16;
var rings = 16;
var slices = 16;
Rlgl.Begin(DrawMode.Triangles);
Rlgl.Color4ub(color.R, color.G, color.B, color.A);
for (int i = 0; i < (rings + 2); i++)
for (var i = 0; i < (rings + 2); i++)
{
for (int j = 0; j < slices; j++)
for (var j = 0; j < slices; j++)
{
Rlgl.Vertex3f(
MathF.Cos(DEG2RAD * (270 + (180 / (rings + 1)) * i)) * MathF.Sin(DEG2RAD * (j * 360 / slices)),
@ -192,5 +188,32 @@ public class SolarSystem
}
Rlgl.End();
}
}
public static int Main()
{
// Initialization
//--------------------------------------------------------------------------------------
InitWindow(screenWidth, screenHeight, "raylib [models] example - rlgl solar system");
SetTargetFPS(60);
//--------------------------------------------------------------------------------------
var game = new SolarSystem();
game.Init();
// Main game loop
while (!WindowShouldClose()) // Detect window close button or ESC key
{
game.Update();
}
game.Unload();
// De-Initialization
//--------------------------------------------------------------------------------------
CloseWindow(); // Close window and OpenGL context
//--------------------------------------------------------------------------------------
return 0;
}
}

View file

@ -1,13 +1,17 @@
/*******************************************************************************************
*
* raylib [models] example - Waving cubes
* raylib [models] example - waving cubes
*
* This example has been created using raylib 2.5 (www.raylib.com)
* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details)
* Example complexity rating: [] 3/4
*
* Example originally created with raylib 2.5, last time updated with raylib 3.7
*
* Example contributed by Codecat (@codecat) and reviewed by Ramon Santamaria (@raysan5)
*
* Copyright (c) 2019 Codecat (@codecat) and Ramon Santamaria (@raysan5)
* Example licensed under an unmodified zlib/libpng license, which is an OSI-certified,
* BSD-like license that allows static linking with closed source software
*
* Copyright (c) 2019-2025 Codecat (@codecat) and Ramon Santamaria (@raysan5)
*
********************************************************************************************/
@ -17,43 +21,42 @@ using static Raylib_cs.Raylib;
namespace Examples.Models;
public class WavingCubes
public partial class WavingCubes : IExample
{
public static int Main()
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [models] example - waving cubes");
// Initialize the camera
Camera3D camera = new();
camera.Position = new Vector3(30.0f, 20.0f, 30.0f);
camera.Target = new Vector3(0.0f, 0.0f, 0.0f);
camera.Up = new Vector3(0.0f, 1.0f, 0.0f);
camera.FovY = 70.0f;
camera.Projection = CameraProjection.Perspective;
private const int screenWidth = 800;
private const int screenHeight = 450;
// Specify the amount of blocks in each direction
const int numBlocks = 15;
private const int numBlocks = 15;
SetTargetFPS(60);
//--------------------------------------------------------------------------------------
public string Name => "Models / Waving Cubes";
// Main game loop
while (!WindowShouldClose())
public string Title => "raylib [models] example - waving cubes";
private Camera3D camera;
public void Init()
{
// Initialize the camera
camera = new();
camera.Position = new Vector3(30.0f, 20.0f, 30.0f); // Camera position
camera.Target = new Vector3(0.0f, 0.0f, 0.0f); // Camera looking at point
camera.Up = new Vector3(0.0f, 1.0f, 0.0f); // Camera up vector (rotation towards target)
camera.FovY = 70.0f; // Camera field-of-view Y
camera.Projection = CameraProjection.Perspective; // Camera projection type
}
public void Update()
{
// Update
//----------------------------------------------------------------------------------
double time = GetTime();
var time = GetTime();
// Calculate time scale for cube position and size
float scale = (2.0f + (float)Math.Sin(time)) * 0.7f;
var scale = (2.0f + (float)Math.Sin(time)) * 0.7f;
// Move camera around the scene
double cameraTime = time * 0.3;
var cameraTime = time * 0.3;
camera.Position.X = (float)Math.Cos(cameraTime) * 40.0f;
camera.Position.Z = (float)Math.Sin(cameraTime) * 40.0f;
//----------------------------------------------------------------------------------
@ -67,17 +70,17 @@ public class WavingCubes
DrawGrid(10, 5.0f);
for (int x = 0; x < numBlocks; x++)
for (var x = 0; x < numBlocks; x++)
{
for (int y = 0; y < numBlocks; y++)
for (var y = 0; y < numBlocks; y++)
{
for (int z = 0; z < numBlocks; z++)
for (var z = 0; z < numBlocks; z++)
{
// Scale of the blocks depends on x/y/z positions
float blockScale = (x + y + z) / 30.0f;
var blockScale = (x + y + z) / 30.0f;
// Scatter makes the waving effect by adding blockScale over time
float scatter = (float)Math.Sin(blockScale * 20.0f + (float)(time * 4.0f));
var scatter = (float)Math.Sin(blockScale * 20.0f + (float)(time * 4.0f));
// Calculate the cube position
Vector3 cubePos = new(
@ -87,10 +90,12 @@ public class WavingCubes
);
// Pick a color with a hue depending on cube position for the rainbow color effect
Color cubeColor = ColorFromHSV((float)(((x + y + z) * 18) % 360), 0.75f, 0.9f);
// NOTE: This function is quite costly to be done per cube and frame,
// pre-catching the results into a separate array could improve performance
var cubeColor = ColorFromHSV((float)(((x + y + z) * 18) % 360), 0.75f, 0.9f);
// Calculate cube size
float cubeSize = (2.4f - scale) * blockScale;
var cubeSize = (2.4f - scale) * blockScale;
// And finally, draw the cube!
DrawCube(cubePos, cubeSize, cubeSize, cubeSize, cubeColor);
@ -106,12 +111,35 @@ public class WavingCubes
//----------------------------------------------------------------------------------
}
public void Unload()
{
}
public static int Main()
{
// Initialization
//--------------------------------------------------------------------------------------
InitWindow(screenWidth, screenHeight, "raylib [models] example - waving cubes");
SetTargetFPS(60);
//--------------------------------------------------------------------------------------
var game = new WavingCubes();
game.Init();
// Main game loop
while (!WindowShouldClose()) // Detect window close button or ESC key
{
game.Update();
}
game.Unload();
// De-Initialization
//--------------------------------------------------------------------------------------
CloseWindow();
CloseWindow(); // Close window and OpenGL context
//--------------------------------------------------------------------------------------
return 0;
}
}

View file

@ -1,13 +1,17 @@
/*******************************************************************************************
*
* raylib [models] example - Plane rotations (yaw, pitch, roll)
* raylib [models] example - yaw pitch roll
*
* This example has been created using raylib 1.8 (www.raylib.com)
* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details)
* Example complexity rating: [] 2/4
*
* Example originally created with raylib 1.8, last time updated with raylib 4.0
*
* Example contributed by Berni (@Berni8k) and reviewed by Ramon Santamaria (@raysan5)
*
* Copyright (c) 2017-2021 Berni (@Berni8k) and Ramon Santamaria (@raysan5)
* Example licensed under an unmodified zlib/libpng license, which is an OSI-certified,
* BSD-like license that allows static linking with closed source software
*
* Copyright (c) 2017-2025 Berni (@Berni8k) and Ramon Santamaria (@raysan5)
*
********************************************************************************************/
@ -17,42 +21,51 @@ using static Raylib_cs.Raymath;
namespace Examples.Models;
public class YawPitchRoll
public partial class YawPitchRoll : IExample
{
public unsafe static int Main()
private const int screenWidth = 800;
private const int screenHeight = 450;
public string Name => "Models / Yaw Pitch Roll";
public string Title => "raylib [models] example - yaw pitch roll";
private Camera3D camera;
private Model model;
private Texture2D texture;
private float pitch;
private float roll;
private float yaw;
public unsafe void Init()
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
camera = new();
camera.Position = new Vector3(0.0f, 50.0f, -120.0f);// Camera position perspective
camera.Target = new Vector3(0.0f, 0.0f, 0.0f); // Camera looking at point
camera.Up = new Vector3(0.0f, 1.0f, 0.0f); // Camera up vector (rotation towards target)
camera.FovY = 30.0f; // Camera field-of-view Y
camera.Projection = CameraProjection.Perspective; // Camera type
InitWindow(screenWidth, screenHeight, "raylib [models] example - plane rotations (yaw, pitch, roll)");
model = LoadModel("resources/models/obj/plane.obj"); // Load model
texture = LoadTexture("resources/models/obj/plane_diffuse.png"); // Load model texture
Camera3D camera = new();
camera.Position = new Vector3(0.0f, 50.0f, -120.0f);
camera.Target = new Vector3(0.0f, 0.0f, 0.0f);
camera.Up = new Vector3(0.0f, 1.0f, 0.0f);
camera.FovY = 30.0f;
camera.Projection = CameraProjection.Perspective;
SetTextureWrap(texture, TextureWrap.Repeat); // Force Repeat to avoid issue on Web version
// Model loading
Model model = LoadModel("resources/models/obj/plane.obj");
Texture2D texture = LoadTexture("resources/models/obj/plane_diffuse.png");
model.Materials[0].Maps[(int)MaterialMapIndex.Diffuse].Texture = texture;
model.Materials[0].Maps[(int)MaterialMapIndex.Diffuse].Texture = texture; // Set map diffuse texture
float pitch = 0.0f;
float roll = 0.0f;
float yaw = 0.0f;
pitch = 0.0f;
roll = 0.0f;
yaw = 0.0f;
}
SetTargetFPS(60);
//--------------------------------------------------------------------------------------
while (!WindowShouldClose())
public void Update()
{
// Update
//----------------------------------------------------------------------------------
// Plane roll (x-axis) controls
// Plane pitch (x-axis) controls
if (IsKeyDown(KeyboardKey.Down))
{
pitch += 0.6f;
@ -94,7 +107,7 @@ public class YawPitchRoll
}
}
// Plane pitch (z-axis) controls
// Plane roll (z-axis) controls
if (IsKeyDown(KeyboardKey.Left))
{
roll += 1.0f;
@ -152,11 +165,34 @@ public class YawPitchRoll
//----------------------------------------------------------------------------------
}
public void Unload()
{
UnloadModel(model);
}
public static int Main()
{
// Initialization
//--------------------------------------------------------------------------------------
InitWindow(screenWidth, screenHeight, "raylib [models] example - yaw pitch roll");
SetTargetFPS(60);
//--------------------------------------------------------------------------------------
var game = new YawPitchRoll();
game.Init();
// Main game loop
while (!WindowShouldClose()) // Detect window close button or ESC key
{
game.Update();
}
game.Unload();
// De-Initialization
//--------------------------------------------------------------------------------------
UnloadModel(model);
CloseWindow();
CloseWindow(); // Close window and OpenGL context
//--------------------------------------------------------------------------------------
return 0;

View file

@ -1,195 +1,81 @@
#nullable enable
using System.Diagnostics;
using Examples.Core;
using Examples.Shapes;
using Examples.Textures;
using Examples.Text;
using Examples.Models;
using Examples.Shaders;
using Examples.Audio;
namespace Examples;
public class ExampleInfo
internal static class Program
{
public ExampleInfo(string name, Func<int> main)
{
this.Name = name;
this.Main = main;
}
private const int screenWidth = 800;
private const int screenHeight = 450;
public string Name
{
get; set;
}
public Func<int> Main
{
get; set;
}
}
public class ExampleList
{
public static ExampleInfo[] AllExamples = new[]
{
// Core
new ExampleInfo("DeltaTime", DeltaTime.Main),
new ExampleInfo("InputGesturesTestBed", InputGesturesTestBed.Main),
new ExampleInfo("InputVirtualControls", InputVirtualControls.Main),
new ExampleInfo("Camera2dPlatformer", Camera2dPlatformer.Main),
new ExampleInfo("Camera2dDemo", Camera2dDemo.Main),
new ExampleInfo("Camera3dFirstPerson", Camera3dFirstPerson.Main),
new ExampleInfo("Camera3dFree", Camera3dFree.Main),
new ExampleInfo("Camera3dMode", Camera3dMode.Main),
new ExampleInfo("Picking3d", Picking3d.Main),
new ExampleInfo("BasicScreenManager", BasicScreenManager.Main),
new ExampleInfo("BasicWindow", BasicWindow.Main),
new ExampleInfo("CustomLogging", CustomLogging.Main),
new ExampleInfo("DropFiles", DropFiles.Main),
new ExampleInfo("InputGamepad", InputGamepad.Main),
new ExampleInfo("InputGestures", InputGestures.Main),
new ExampleInfo("InputKeys", InputKeys.Main),
new ExampleInfo("InputMouseWheel", InputMouseWheel.Main),
new ExampleInfo("InputMouse", InputMouse.Main),
new ExampleInfo("InputMultitouch", InputMultitouch.Main),
new ExampleInfo("RandomValues", RandomValues.Main),
new ExampleInfo("ScissorTest", ScissorTest.Main),
new ExampleInfo("SmoothPixelPerfect", SmoothPixelPerfect.Main),
new ExampleInfo("SplitScreen", SplitScreen.Main),
new ExampleInfo("StorageValues", StorageValues.Main),
new ExampleInfo("VrSimulator", VrSimulator.Main),
new ExampleInfo("WindowFlags", WindowFlags.Main),
new ExampleInfo("WindowLetterbox", WindowLetterbox.Main),
new ExampleInfo("WorldScreen", WorldScreen.Main),
// Shapes
new ExampleInfo("BasicShapes", BasicShapes.Main),
new ExampleInfo("BouncingBall", BouncingBall.Main),
new ExampleInfo("CollisionArea", CollisionArea.Main),
new ExampleInfo("ColorsPalette", ColorsPalette.Main),
new ExampleInfo("EasingsBallAnim", EasingsBallAnim.Main),
new ExampleInfo("EasingsBoxAnim", EasingsBoxAnim.Main),
new ExampleInfo("EasingsRectangleArray", EasingsRectangleArray.Main),
new ExampleInfo("FollowingEyes", FollowingEyes.Main),
new ExampleInfo("LinesBezier", LinesBezier.Main),
new ExampleInfo("LogoRaylibAnim", LogoRaylibAnim.Main),
new ExampleInfo("LogoRaylibShape", LogoRaylibShape.Main),
new ExampleInfo("RectangleScaling", RectangleScaling.Main),
// Textures
new ExampleInfo("BackgroundScrolling", BackgroundScrolling.Main),
new ExampleInfo("BlendModes", BlendModes.Main),
new ExampleInfo("Bunnymark", Bunnymark.Main),
new ExampleInfo("DrawTiled", DrawTiled.Main),
new ExampleInfo("ImageDrawing", ImageDrawing.Main),
new ExampleInfo("ImageGeneration", ImageGeneration.Main),
new ExampleInfo("ImageLoading", ImageLoading.Main),
new ExampleInfo("ImageProcessing", ImageProcessing.Main),
new ExampleInfo("ImageText", ImageText.Main),
new ExampleInfo("LogoRaylibTexture", LogoRaylibTexture.Main),
new ExampleInfo("MousePainting", MousePainting.Main),
new ExampleInfo("NpatchDrawing", NpatchDrawing.Main),
new ExampleInfo("ParticlesBlending", ParticlesBlending.Main),
new ExampleInfo("TexturedCurve", TexturedCurve.Main),
new ExampleInfo("Polygon", Polygon.Main),
new ExampleInfo("RawData", RawData.Main),
new ExampleInfo("SpriteAnim", SpriteAnim.Main),
new ExampleInfo("SpriteButton", SpriteButton.Main),
new ExampleInfo("SpriteExplosion", SpriteExplosion.Main),
new ExampleInfo("SrcRecDstRec", SrcRecDstRec.Main),
new ExampleInfo("ToImage", ToImage.Main),
// Text
new ExampleInfo("CodepointsLoading", CodepointsLoading.Main),
new ExampleInfo("FontFilters", FontFilters.Main),
new ExampleInfo("FontLoading", FontLoading.Main),
new ExampleInfo("FontSdf", FontSdf.Main),
new ExampleInfo("FontSpritefont", FontSpritefont.Main),
new ExampleInfo("FormatText", FormatText.Main),
new ExampleInfo("InputBox", InputBox.Main),
new ExampleInfo("RaylibFonts", RaylibFonts.Main),
new ExampleInfo("RectangleBounds", RectangleBounds.Main),
new ExampleInfo("WritingAnim", WritingAnim.Main),
// Models
new ExampleInfo("LoadingIqm", LoadingIqm.Main),
new ExampleInfo("LoadingGltf", LoadingGltf.Main),
new ExampleInfo("BillboardDemo", BillboardDemo.Main),
new ExampleInfo("BoxCollisions", BoxCollisions.Main),
new ExampleInfo("CubicmapDemo", CubicmapDemo.Main),
new ExampleInfo("ModelCubeTexture", ModelCubeTexture.Main),
new ExampleInfo("FirstPersonMaze", FirstPersonMaze.Main),
new ExampleInfo("GeometricShapes", GeometricShapes.Main),
new ExampleInfo("HeightmapDemo", HeightmapDemo.Main),
new ExampleInfo("MeshDemo", MeshDemo.Main),
new ExampleInfo("ModelLoading", ModelLoading.Main),
new ExampleInfo("MeshGeneration", MeshGeneration.Main),
new ExampleInfo("MeshPicking", MeshPicking.Main),
new ExampleInfo("OrthographicProjection", OrthographicProjection.Main),
new ExampleInfo("SolarSystem", SolarSystem.Main),
new ExampleInfo("SkyboxDemo", SkyboxDemo.Main),
new ExampleInfo("WavingCubes", WavingCubes.Main),
new ExampleInfo("YawPitchRoll", YawPitchRoll.Main),
new ExampleInfo("DynamicMesh", DynamicMesh.Main),
// Shaders
new ExampleInfo("BasicLighting", BasicLighting.Main),
new ExampleInfo("BasicPbr", BasicPbr.Main),
new ExampleInfo("CustomUniform", CustomUniform.Main),
new ExampleInfo("Eratosthenes", Eratosthenes.Main),
new ExampleInfo("Fog", Fog.Main),
new ExampleInfo("HotReloading", HotReloading.Main),
new ExampleInfo("HybridRender", HybridRender.Main),
new ExampleInfo("JuliaSet", JuliaSet.Main),
new ExampleInfo("ModelShader", ModelShader.Main),
new ExampleInfo("MultiSample2d", MultiSample2d.Main),
new ExampleInfo("PaletteSwitch", PaletteSwitch.Main),
new ExampleInfo("PostProcessing", PostProcessing.Main),
new ExampleInfo("Raymarching", Raymarching.Main),
new ExampleInfo("MeshInstancing", MeshInstancing.Main),
new ExampleInfo("ShapesTextures", ShapesTextures.Main),
new ExampleInfo("SimpleMask", SimpleMask.Main),
new ExampleInfo("Spotlight", Spotlight.Main),
new ExampleInfo("TextureDrawing", TextureDrawing.Main),
new ExampleInfo("TextureOutline", TextureOutline.Main),
new ExampleInfo("TextureWaves", TextureWaves.Main),
new ExampleInfo("WriteDepth", WriteDepth.Main),
// Audio
new ExampleInfo("ModulePlaying", ModulePlaying.Main),
new ExampleInfo("MusicStreamDemo", MusicStreamDemo.Main),
new ExampleInfo("SoundLoading", SoundLoading.Main),
};
public static ExampleInfo GetExample(string name)
{
var example = Array.Find(ExampleList.AllExamples, x =>
x.Name.Equals(name, StringComparison.OrdinalIgnoreCase)
);
return example;
}
}
class Program
{
static unsafe void Main(string[] args)
private static unsafe void Main(string[] args)
{
Raylib.SetTraceLogCallback(&Logging.LogConsole);
if (args.Length > 0)
{
var example = ExampleList.GetExample(args[0]);
example?.Main?.Invoke();
var example = GetExample(args[0]);
if (example == null)
{
Console.WriteLine($"Unknown example: {args[0]}");
return;
}
foreach (var example in ExampleList.AllExamples)
RunExample(example);
return;
}
foreach (var example in ExampleRegistry.DesktopExamples)
{
RunExampleProcess(Environment.ProcessPath, example.Name);
RunExampleProcess(Environment.ProcessPath!, example.GetType().Name);
}
}
static void RunExampleProcess(
private static IExample? GetExample(string name)
{
return Array.Find(ExampleRegistry.DesktopExamples, x =>
x.GetType().Name.Equals(name, StringComparison.OrdinalIgnoreCase) ||
x.Name.Equals(name, StringComparison.OrdinalIgnoreCase)
);
}
/// <summary>
/// Drives an example the same way its standalone Main() does: window setup from the
/// example's properties, then Init/Update/Unload around a blocking frame loop.
/// </summary>
private static void RunExample(IExample example)
{
if (example.ConfigFlags != 0)
{
SetConfigFlags(example.ConfigFlags);
}
InitWindow(screenWidth, screenHeight, example.Title);
if (example.CursorDisabled)
{
DisableCursor();
}
else if (example.CursorHidden)
{
HideCursor();
}
SetTargetFPS(example.TargetFps);
example.Init();
while (!WindowShouldClose())
{
example.Update();
}
example.Unload();
CloseWindow();
}
private static void RunExampleProcess(
string fileName,
string exampleName
)

View file

@ -2,26 +2,21 @@
*
* raylib [shaders] example - basic lighting
*
* Example complexity rating: [] 4/4
*
* NOTE: This example requires raylib OpenGL 3.3 or ES2 versions for shaders support,
* OpenGL 1.1 does not support shaders, recompile raylib to OpenGL 3.3 version.
* OpenGL 1.1 does not support shaders, recompile raylib to OpenGL 3.3 version
*
* NOTE: Shaders used in this example are #version 330 (OpenGL 3.3).
* NOTE: Shaders used in this example are #version 330 (OpenGL 3.3)
*
* This example has been created using raylib 2.5 (www.raylib.com)
* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details)
* Example originally created with raylib 3.0, last time updated with raylib 4.2
*
* Example contributed by Chris Camacho (@codifies) and reviewed by Ramon Santamaria (@raysan5)
* Example contributed by Chris Camacho (@chriscamacho) and reviewed by Ramon Santamaria (@raysan5)
*
* Chris Camacho (@codifies - http://bedroomcoders.co.uk/) notes:
* Example licensed under an unmodified zlib/libpng license, which is an OSI-certified,
* BSD-like license that allows static linking with closed source software
*
* This is based on the PBR lighting example, but greatly simplified to aid learning...
* actually there is very little of the PBR example left!
* When I first looked at the bewildering complexity of the PBR example I feared
* I would never understand how I could do simple lighting with raylib however its
* a testement to the authors of raylib (including rlights.h) that the example
* came together fairly quickly.
*
* Copyright (c) 2019 Chris Camacho (@codifies) and Ramon Santamaria (@raysan5)
* Copyright (c) 2019-2025 Chris Camacho (@chriscamacho) and Ramon Santamaria (@raysan5)
*
********************************************************************************************/
@ -31,52 +26,55 @@ using Examples.Shared;
namespace Examples.Shaders;
public class BasicLighting
public class BasicLighting : IExample
{
const int GLSL_VERSION = 330;
private const int screenWidth = 800;
private const int screenHeight = 450;
public unsafe static int Main()
#if BROWSER
const int GlslVersion = 100; // WebGL1 needs GLSL ES 100
#else
private const int GlslVersion = 330;
#endif
public string Name => "Shaders / Basic Lighting";
public string Title => "raylib [shaders] example - basic lighting";
public ConfigFlags ConfigFlags => ConfigFlags.Msaa4xHint;
private Camera3D camera;
private Shader shader;
private Light[] lights;
public unsafe void Init()
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
// Enable Multi Sampling Anti Aliasing 4x (if available)
SetConfigFlags(ConfigFlags.Msaa4xHint);
InitWindow(screenWidth, screenHeight, "raylib [shaders] example - basic lighting");
// Define the camera to look into our 3d world
Camera3D camera = new();
camera.Position = new Vector3(2.0f, 4.0f, 6.0f);
camera.Target = new Vector3(0.0f, 0.5f, 0.0f);
camera.Up = new Vector3(0.0f, 1.0f, 0.0f);
camera.FovY = 45.0f;
camera.Projection = CameraProjection.Perspective;
camera = new();
camera.Position = new Vector3(2.0f, 4.0f, 6.0f); // Camera position
camera.Target = new Vector3(0.0f, 0.5f, 0.0f); // Camera looking at point
camera.Up = new Vector3(0.0f, 1.0f, 0.0f); // Camera up vector (rotation towards target)
camera.FovY = 45.0f; // Camera field-of-view Y
camera.Projection = CameraProjection.Perspective; // Camera projection type
// Load plane model from a generated mesh
Model model = LoadModelFromMesh(GenMeshPlane(10.0f, 10.0f, 3, 3));
Model cube = LoadModelFromMesh(GenMeshCube(2.0f, 4.0f, 2.0f));
Shader shader = LoadShader(
"resources/shaders/glsl330/lighting.vs",
"resources/shaders/glsl330/lighting.fs"
// Load basic lighting shader
shader = LoadShader(
$"resources/shaders/glsl{GlslVersion}/lighting.vs",
$"resources/shaders/glsl{GlslVersion}/lighting.fs"
);
// Get some required shader loactions
// Get some required shader locations
shader.Locs[(int)ShaderLocationIndex.VectorView] = GetShaderLocation(shader, "viewPos");
// NOTE: "matModel" location name is automatically assigned on shader loading,
// no need to get the location again if using that uniform name
//shader.Locs[(int)ShaderLocationIndex.MatrixModel] = GetShaderLocation(shader, "matModel");
// ambient light level
int ambientLoc = GetShaderLocation(shader, "ambient");
float[] ambient = new[] { 0.1f, 0.1f, 0.1f, 1.0f };
// Ambient light level (some basic lighting)
var ambientLoc = GetShaderLocation(shader, "ambient");
var ambient = new[] { 0.1f, 0.1f, 0.1f, 1.0f };
Raylib.SetShaderValue(shader, ambientLoc, ambient, ShaderUniformDataType.Vec4);
// Assign out lighting shader to model
model.Materials[0].Shader = shader;
cube.Materials[0].Shader = shader;
// Using 4 point lights: Color.gold, Color.red, Color.green and Color.blue
Light[] lights = new Light[4];
// Create lights
lights = new Light[4];
lights[0] = Rlights.CreateLight(
0,
LightType.Point,
@ -109,17 +107,23 @@ public class BasicLighting
Color.Blue,
shader
);
}
SetTargetFPS(60);
//--------------------------------------------------------------------------------------
// Main game loop
while (!WindowShouldClose())
public unsafe void Update()
{
// Update
//----------------------------------------------------------------------------------
UpdateCamera(ref camera, CameraMode.Orbital);
// Update the shader with the camera view vector (points towards { 0.0f, 0.0f, 0.0f })
Raylib.SetShaderValue(
shader,
shader.Locs[(int)ShaderLocationIndex.VectorView],
camera.Position,
ShaderUniformDataType.Vec3
);
// Check key inputs to enable/disable lights
if (IsKeyPressed(KeyboardKey.Y))
{
lights[0].Enabled = !lights[0].Enabled;
@ -138,65 +142,38 @@ public class BasicLighting
}
// Update light values (actually, only enable/disable them)
Rlights.UpdateLightValues(shader, lights[0]);
Rlights.UpdateLightValues(shader, lights[1]);
Rlights.UpdateLightValues(shader, lights[2]);
Rlights.UpdateLightValues(shader, lights[3]);
// Update the light shader with the camera view position
Raylib.SetShaderValue(
shader,
shader.Locs[(int)ShaderLocationIndex.VectorView],
camera.Position,
ShaderUniformDataType.Vec3
);
for (var i = 0; i < 4; i++)
{
Rlights.UpdateLightValues(shader, lights[i]);
}
//----------------------------------------------------------------------------------
// Draw
//----------------------------------------------------------------------------------
BeginDrawing();
ClearBackground(Color.RayWhite);
BeginMode3D(camera);
DrawModel(model, Vector3.Zero, 1.0f, Color.White);
DrawModel(cube, Vector3.Zero, 1.0f, Color.White);
BeginShaderMode(shader);
// Draw markers to show where the lights are
if (lights[0].Enabled)
DrawPlane(Vector3.Zero, new Vector2(10.0f, 10.0f), Color.White);
DrawCube(Vector3.Zero, 2.0f, 4.0f, 2.0f, Color.White);
EndShaderMode();
// Draw spheres to show where the lights are
for (var i = 0; i < 4; i++)
{
DrawSphereEx(lights[0].Position, 0.2f, 8, 8, Color.Yellow);
if (lights[i].Enabled)
{
DrawSphereEx(lights[i].Position, 0.2f, 8, 8, lights[i].Color);
}
else
{
DrawSphereWires(lights[0].Position, 0.2f, 8, 8, ColorAlpha(Color.Yellow, 0.3f));
DrawSphereWires(lights[i].Position, 0.2f, 8, 8, ColorAlpha(lights[i].Color, 0.3f));
}
if (lights[1].Enabled)
{
DrawSphereEx(lights[1].Position, 0.2f, 8, 8, Color.Red);
}
else
{
DrawSphereWires(lights[1].Position, 0.2f, 8, 8, ColorAlpha(Color.Red, 0.3f));
}
if (lights[2].Enabled)
{
DrawSphereEx(lights[2].Position, 0.2f, 8, 8, Color.Green);
}
else
{
DrawSphereWires(lights[2].Position, 0.2f, 8, 8, ColorAlpha(Color.Green, 0.3f));
}
if (lights[3].Enabled)
{
DrawSphereEx(lights[3].Position, 0.2f, 8, 8, Color.Blue);
}
else
{
DrawSphereWires(lights[3].Position, 0.2f, 8, 8, ColorAlpha(Color.Blue, 0.3f));
}
DrawGrid(10, 1.0f);
@ -204,19 +181,42 @@ public class BasicLighting
EndMode3D();
DrawFPS(10, 10);
DrawText("Use keys [Y][R][G][B] to toggle lights", 10, 40, 20, Color.DarkGray);
EndDrawing();
//----------------------------------------------------------------------------------
}
public void Unload()
{
UnloadShader(shader); // Unload shader
}
public static int Main()
{
// Initialization
//--------------------------------------------------------------------------------------
SetConfigFlags(ConfigFlags.Msaa4xHint); // Enable Multi Sampling Anti Aliasing 4x (if available)
InitWindow(screenWidth, screenHeight, "raylib [shaders] example - basic lighting");
SetTargetFPS(60); // Set our game to run at 60 frames-per-second
//--------------------------------------------------------------------------------------
var game = new BasicLighting();
game.Init();
// Main game loop
while (!WindowShouldClose()) // Detect window close button or ESC key
{
game.Update();
}
game.Unload();
// De-Initialization
//--------------------------------------------------------------------------------------
UnloadModel(model);
UnloadModel(cube);
UnloadShader(shader);
CloseWindow();
CloseWindow(); // Close window and OpenGL context
//--------------------------------------------------------------------------------------
return 0;

View file

@ -1,21 +1,23 @@
/*******************************************************************************************
*
* raylib [shaders] example - Basic PBR
*
* Example originally created with raylib 5.0, last time updated with raylib 5.1-dev
*
* Example contributed by Afan OLOVCIC (@_DevDad) and reviewed by Ramon Santamaria (@raysan5)
*
* Example licensed under an unmodified zlib/libpng license, which is an OSI-certified,
* BSD-like license that allows static linking with closed source software
*
* Copyright (c) 2023-2024 Afan OLOVCIC (@_DevDad)
*
* Model: "Old Rusty Car" (https://skfb.ly/LxRy) by Renafox,
* licensed under Creative Commons Attribution-NonCommercial
* (http://creativecommons.org/licenses/by-nc/4.0/)
*
********************************************************************************************/
*
* raylib [shaders] example - basic pbr
*
* Example complexity rating: [] 4/4
*
* Example originally created with raylib 5.0, last time updated with raylib 5.5
*
* Example contributed by Afan OLOVCIC (@_DevDad) and reviewed by Ramon Santamaria (@raysan5)
*
* Example licensed under an unmodified zlib/libpng license, which is an OSI-certified,
* BSD-like license that allows static linking with closed source software
*
* Copyright (c) 2023-2025 Afan OLOVCIC (@_DevDad)
*
* Model: "Old Rusty Car" (https://skfb.ly/LxRy) by Renafox,
* licensed under Creative Commons Attribution-NonCommercial
* (http://creativecommons.org/licenses/by-nc/4.0/)
*
********************************************************************************************/
using System.Numerics;
using Examples.Shared;
@ -23,31 +25,50 @@ using static Raylib_cs.Raylib;
namespace Examples.Shaders;
public class BasicPbr
public class BasicPbr : IExample
{
private const int GLSL_VERSION = 330;
#if BROWSER
const int GlslVersion = 100; // WebGL1 needs GLSL ES 100
#else
private const int GlslVersion = 330;
#endif
public static unsafe int Main()
private const int screenWidth = 800;
private const int screenHeight = 450;
public string Name => "Shaders / Basic PBR";
public string Title => "raylib [shaders] example - basic pbr";
public ConfigFlags ConfigFlags => ConfigFlags.Msaa4xHint;
private Camera3D camera;
private Shader shader;
private Model car;
private Model floor;
private PbrLight[] lights;
private int metallicValueLoc;
private int roughnessValueLoc;
private int emissiveIntensityLoc;
private int emissiveColorLoc;
private int textureTilingLoc;
private Vector2 carTextureTiling;
private Vector2 floorTextureTiling;
public unsafe void Init()
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
// Enable Multi Sampling Anti Aliasing 4x (if available)
SetConfigFlags(ConfigFlags.Msaa4xHint);
InitWindow(screenWidth, screenHeight, "raylib [shaders] example - basic pbr");
// Define the camera to look into our 3d world
Camera3D camera = new();
camera.Position = new Vector3(2.0f, 4.0f, 6.0f);
camera = new();
camera.Position = new Vector3(2.0f, 2.0f, 6.0f);
camera.Target = new Vector3(0.0f, 0.5f, 0.0f);
camera.Up = new Vector3(0.0f, 1.0f, 0.0f);
camera.FovY = 45.0f;
camera.Projection = CameraProjection.Perspective;
// Load PBR shader and setup all required locations
var shader = LoadShader("resources/shaders/glsl330/pbr.vs", "resources/shaders/glsl330/pbr.fs");
shader = LoadShader($"resources/shaders/glsl{GlslVersion}/pbr.vs", $"resources/shaders/glsl{GlslVersion}/pbr.fs");
shader.Locs[(int)ShaderLocationIndex.MapAlbedo] = GetShaderLocation(shader, "albedoMap");
// WARNING: Metalness, roughness, and ambient occlusion are all packed into a MRA texture
@ -75,23 +96,25 @@ public class BasicPbr
SetShaderValue(shader, GetShaderLocation(shader, "ambient"), &ambientIntensity, ShaderUniformDataType.Float);
// Get location for shader parameters that can be modified in real time
var emissiveIntensityLoc = GetShaderLocation(shader, "emissivePower");
var emissiveColorLoc = GetShaderLocation(shader, "emissiveColor");
var textureTilingLoc = GetShaderLocation(shader, "tiling");
metallicValueLoc = GetShaderLocation(shader, "metallicValue");
roughnessValueLoc = GetShaderLocation(shader, "roughnessValue");
emissiveIntensityLoc = GetShaderLocation(shader, "emissivePower");
emissiveColorLoc = GetShaderLocation(shader, "emissiveColor");
textureTilingLoc = GetShaderLocation(shader, "tiling");
// Load old car model using PBR maps and shader
// WARNING: We know this model consists of a single model.meshes[0] and
// that model.materials[0] is by default assigned to that mesh
// There could be more complex models consisting of multiple meshes and
// multiple materials defined for those meshes... but always 1 mesh = 1 material
var car = LoadModel("resources/models/gltf/old_car_new.glb");
car = LoadModel("resources/models/gltf/old_car_new.glb");
// Assign already setup PBR shader to model.materials[0], used by models.meshes[0]
car.Materials[0].Shader = shader;
// Setup materials[0].maps default parameters
car.Materials[0].Maps[(int)MaterialMapIndex.Albedo].Color = Color.White;
car.Materials[0].Maps[(int)MaterialMapIndex.Metalness].Value = 0.0f;
car.Materials[0].Maps[(int)MaterialMapIndex.Metalness].Value = 1.0f;
car.Materials[0].Maps[(int)MaterialMapIndex.Roughness].Value = 0.0f;
car.Materials[0].Maps[(int)MaterialMapIndex.Occlusion].Value = 1.0f;
car.Materials[0].Maps[(int)MaterialMapIndex.Emission].Color = new Color(255, 162, 0, 255);
@ -104,7 +127,7 @@ public class BasicPbr
// Load floor model mesh and assign material parameters
// NOTE: A basic plane shape can be generated instead of being loaded from a model file
var floor = LoadModel("resources/models/gltf/plane.glb");
floor = LoadModel("resources/models/gltf/plane.glb");
//Mesh floorMesh = GenMeshPlane(10, 10, 10, 10);
//GenMeshTangents(&floorMesh); // TODO: Review tangents generation
//Model floor = LoadModelFromMesh(floorMesh);
@ -113,8 +136,8 @@ public class BasicPbr
floor.Materials[0].Shader = shader;
floor.Materials[0].Maps[(int)MaterialMapIndex.Albedo].Color = Color.White;
floor.Materials[0].Maps[(int)MaterialMapIndex.Metalness].Value = 0.0f;
floor.Materials[0].Maps[(int)MaterialMapIndex.Roughness].Value = 0.0f;
floor.Materials[0].Maps[(int)MaterialMapIndex.Metalness].Value = 0.8f;
floor.Materials[0].Maps[(int)MaterialMapIndex.Roughness].Value = 0.1f;
floor.Materials[0].Maps[(int)MaterialMapIndex.Occlusion].Value = 1.0f;
floor.Materials[0].Maps[(int)MaterialMapIndex.Emission].Color = Color.Black;
@ -124,11 +147,11 @@ public class BasicPbr
// Models texture tiling parameter can be stored in the Material struct if required (CURRENTLY NOT USED)
// NOTE: Material.params[4] are available for generic parameters storage (float)
var carTextureTiling = new Vector2(0.5f, 0.5f);
var floorTextureTiling = new Vector2(0.5f, 0.5f);
carTextureTiling = new Vector2(0.5f, 0.5f);
floorTextureTiling = new Vector2(0.5f, 0.5f);
// Create some lights
var lights = new PbrLight[4];
lights = new PbrLight[4];
lights[0] = PbrLights.CreateLight(
0,
PbrLightType.Point,
@ -167,16 +190,13 @@ public class BasicPbr
SetShaderValue(shader, GetShaderLocation(shader, "useTexNormal"), &usage, ShaderUniformDataType.Int);
SetShaderValue(shader, GetShaderLocation(shader, "useTexMRA"), &usage, ShaderUniformDataType.Int);
SetShaderValue(shader, GetShaderLocation(shader, "useTexEmissive"), &usage, ShaderUniformDataType.Int);
}
SetTargetFPS(60); // Set our game to run at 60 frames-per-second
//---------------------------------------------------------------------------------------
// Main game loop
while (!WindowShouldClose()) // Detect window close button or ESC key
public unsafe void Update()
{
// Update
//----------------------------------------------------------------------------------
UpdateCamera(&camera, CameraMode.Orbital);
UpdateCamera(ref camera, CameraMode.Orbital);
// Update the shader with the camera view vector (points towards { 0.0f, 0.0f, 0.0f })
var cameraPos = camera.Position;
@ -219,19 +239,31 @@ public class BasicPbr
BeginMode3D(camera);
// Set floor model texture tiling and emissive color parameters on shader
SetShaderValue(shader, textureTilingLoc, &floorTextureTiling, ShaderUniformDataType.Vec2);
SetShaderValue(shader, textureTilingLoc, floorTextureTiling, ShaderUniformDataType.Vec2);
var floorEmissiveColor = ColorNormalize(floor.Materials[0].Maps[(int)MaterialMapIndex.Emission].Color);
SetShaderValue(shader, emissiveColorLoc, &floorEmissiveColor, ShaderUniformDataType.Vec4);
// Set floor metallic and roughness values
var floorMetallicValue = floor.Materials[0].Maps[(int)MaterialMapIndex.Metalness].Value;
SetShaderValue(shader, metallicValueLoc, &floorMetallicValue, ShaderUniformDataType.Float);
var floorRoughnessValue = floor.Materials[0].Maps[(int)MaterialMapIndex.Roughness].Value;
SetShaderValue(shader, roughnessValueLoc, &floorRoughnessValue, ShaderUniformDataType.Float);
DrawModel(floor, Vector3.Zero, 5.0f, Color.White); // Draw floor model
// Set old car model texture tiling, emissive color and emissive intensity parameters on shader
SetShaderValue(shader, textureTilingLoc, &carTextureTiling, ShaderUniformDataType.Vec2);
SetShaderValue(shader, textureTilingLoc, carTextureTiling, ShaderUniformDataType.Vec2);
var carEmissiveColor = ColorNormalize(car.Materials[0].Maps[(int)MaterialMapIndex.Emission].Color);
SetShaderValue(shader, emissiveColorLoc, &carEmissiveColor, ShaderUniformDataType.Vec4);
var emissiveIntensity = 0.01f;
SetShaderValue(shader, emissiveIntensityLoc, &emissiveIntensity, ShaderUniformDataType.Float);
// Set old car metallic and roughness values
var carMetallicValue = car.Materials[0].Maps[(int)MaterialMapIndex.Metalness].Value;
SetShaderValue(shader, metallicValueLoc, &carMetallicValue, ShaderUniformDataType.Float);
var carRoughnessValue = car.Materials[0].Maps[(int)MaterialMapIndex.Roughness].Value;
SetShaderValue(shader, roughnessValueLoc, &carRoughnessValue, ShaderUniformDataType.Float);
DrawModel(car, Vector3.Zero, 0.25f, Color.White); // Draw car model
// Draw spheres to show the lights positions
@ -263,8 +295,8 @@ public class BasicPbr
//----------------------------------------------------------------------------------
}
// De-Initialization
//--------------------------------------------------------------------------------------
public unsafe void Unload()
{
// Unbind (disconnect) shader from car.material[0]
// to avoid UnloadMaterial() trying to unload it automatically
car.Materials[0].Shader = new();
@ -278,7 +310,32 @@ public class BasicPbr
UnloadModel(floor);
UnloadShader(shader);
}
public static int Main()
{
// Initialization
//--------------------------------------------------------------------------------------
// Enable Multi Sampling Anti Aliasing 4x (if available)
SetConfigFlags(ConfigFlags.Msaa4xHint);
InitWindow(screenWidth, screenHeight, "raylib [shaders] example - basic pbr");
SetTargetFPS(60); // Set our game to run at 60 frames-per-second
//---------------------------------------------------------------------------------------
var game = new BasicPbr();
game.Init();
// Main game loop
while (!WindowShouldClose()) // Detect window close button or ESC key
{
game.Update();
}
game.Unload();
// De-Initialization
//--------------------------------------------------------------------------------------
CloseWindow();
//--------------------------------------------------------------------------------------
@ -287,8 +344,8 @@ public class BasicPbr
private static void UpdateLight(Shader shader, PbrLight light)
{
SetShaderValue(shader, light.EnabledLoc, light.Enabled, ShaderUniformDataType.Int);
SetShaderValue(shader, light.TypeLoc, light.Type, ShaderUniformDataType.Int);
SetShaderValue(shader, light.EnabledLoc, light.Enabled ? 1 : 0, ShaderUniformDataType.Int);
SetShaderValue(shader, light.TypeLoc, (int)light.Type, ShaderUniformDataType.Int);
// Send to shader light position values
SetShaderValue(shader, light.PositionLoc, light.Position, ShaderUniformDataType.Vec3);

View file

@ -1,18 +1,22 @@
/*******************************************************************************************
*
* raylib [shaders] example - Apply a postprocessing shader and connect a custom uniform variable
* raylib [shaders] example - custom uniform
*
* Example complexity rating: [] 2/4
*
* NOTE: This example requires raylib OpenGL 3.3 or ES2 versions for shaders support,
* OpenGL 1.1 does not support shaders, recompile raylib to OpenGL 3.3 version.
* OpenGL 1.1 does not support shaders, recompile raylib to OpenGL 3.3 version
*
* NOTE: Shaders used in this example are #version 330 (OpenGL 3.3), to test this example
* on OpenGL ES 2.0 platforms (Android, Raspberry Pi, HTML5), use #version 100 shaders
* raylib comes with shaders ready for both versions, check raylib/shaders install folder
*
* 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)
* Example originally created with raylib 1.3, last time updated with raylib 4.0
*
* Copyright (c) 2015 Ramon Santamaria (@raysan5)
* Example licensed under an unmodified zlib/libpng license, which is an OSI-certified,
* BSD-like license that allows static linking with closed source software
*
* Copyright (c) 2015-2025 Ramon Santamaria (@raysan5)
*
********************************************************************************************/
@ -21,89 +25,96 @@ using static Raylib_cs.Raylib;
namespace Examples.Shaders;
public class CustomUniform
public class CustomUniform : IExample
{
public static int Main()
#if BROWSER
const int GlslVersion = 100; // WebGL1 needs GLSL ES 100
#else
private const int GlslVersion = 330;
#endif
private const int screenWidth = 800;
private const int screenHeight = 450;
public string Name => "Shaders / Custom Uniform";
public string Title => "raylib [shaders] example - custom uniform";
public ConfigFlags ConfigFlags => ConfigFlags.Msaa4xHint;
private Camera3D camera;
private Model model;
private Texture2D texture;
private Vector3 position;
private Shader shader;
private int swirlCenterLoc;
private float[] swirlCenter;
private RenderTexture2D target;
public void Init()
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
// Enable Multi Sampling Anti Aliasing 4x (if available)
SetConfigFlags(ConfigFlags.Msaa4xHint);
InitWindow(screenWidth, screenHeight, "raylib [shaders] example - custom uniform variable");
// Define the camera to look into our 3d world
Camera3D camera = new();
camera.Position = new Vector3(8.0f, 8.0f, 8.0f);
camera.Target = new Vector3(0.0f, 1.5f, 0.0f);
camera.Up = new Vector3(0.0f, 1.0f, 0.0f);
camera.FovY = 45.0f;
camera.Projection = CameraProjection.Perspective;
camera = new();
camera.Position = new Vector3(8.0f, 8.0f, 8.0f); // Camera position
camera.Target = new Vector3(0.0f, 1.5f, 0.0f); // Camera looking at point
camera.Up = new Vector3(0.0f, 1.0f, 0.0f); // Camera up vector (rotation towards target)
camera.FovY = 45.0f; // Camera field-of-view Y
camera.Projection = CameraProjection.Perspective; // Camera projection type
Model model = LoadModel("resources/models/obj/barracks.obj");
Texture2D texture = LoadTexture("resources/models/obj/barracks_diffuse.png");
model = LoadModel("resources/models/obj/barracks.obj"); // Load OBJ model
texture = LoadTexture("resources/models/obj/barracks_diffuse.png"); // Load model texture (diffuse map)
// Set model diffuse texture
Raylib.SetMaterialTexture(ref model, 0, MaterialMapIndex.Albedo, ref texture);
Vector3 position = new(0.0f, 0.0f, 0.0f);
position = new(0.0f, 0.0f, 0.0f); // Set model position
// Load postpro shader
Shader shader = LoadShader("resources/shaders/glsl330/base.vs",
"resources/shaders/glsl330/swirl.fs");
// Load postprocessing shader
// NOTE: Defining 0 (NULL) for vertex shader forces usage of internal default vertex shader
shader = LoadShader(null, $"resources/shaders/glsl{GlslVersion}/swirl.fs");
// 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
int swirlCenterLoc = GetShaderLocation(shader, "center");
swirlCenterLoc = GetShaderLocation(shader, "center");
float[] swirlCenter = new float[2] { (float)screenWidth / 2, (float)screenHeight / 2 };
swirlCenter = new float[2] { (float)screenWidth / 2, (float)screenHeight / 2 };
// Create a RenderTexture2D to be used for render to texture
RenderTexture2D target = LoadRenderTexture(screenWidth, screenHeight);
target = LoadRenderTexture(screenWidth, screenHeight);
}
SetTargetFPS(60);
//--------------------------------------------------------------------------------------
// Main game loop
while (!WindowShouldClose())
public void Update()
{
// Update
//----------------------------------------------------------------------------------
Vector2 mousePosition = GetMousePosition();
UpdateCamera(ref camera, CameraMode.Orbital);
var mousePosition = GetMousePosition();
swirlCenter[0] = mousePosition.X;
swirlCenter[1] = screenHeight - mousePosition.Y;
// Send new value to the shader to be used on drawing
Raylib.SetShaderValue(shader, swirlCenterLoc, swirlCenter, ShaderUniformDataType.Vec2);
UpdateCamera(ref camera, CameraMode.Orbital);
//----------------------------------------------------------------------------------
// Draw
//----------------------------------------------------------------------------------
BeginDrawing();
ClearBackground(Color.RayWhite);
BeginTextureMode(target); // Enable drawing to texture
ClearBackground(Color.RayWhite); // Clear texture background
// Enable drawing to texture
BeginTextureMode(target);
ClearBackground(Color.RayWhite);
BeginMode3D(camera);
DrawModel(model, position, 0.5f, Color.White);
DrawGrid(10, 1.0f);
EndMode3D();
BeginMode3D(camera); // Begin 3d mode drawing
DrawModel(model, position, 0.5f, Color.White); // Draw 3d model with texture
DrawGrid(10, 1.0f); // Draw a grid
EndMode3D(); // End 3d mode drawing, returns to orthographic 2d mode
DrawText("TEXT DRAWN IN RENDER TEXTURE", 200, 10, 30, Color.Red);
EndTextureMode(); // End drawing to texture (now we have a texture available for next passes)
// End drawing to texture (now we have a texture available for next passes)
EndTextureMode();
BeginDrawing();
ClearBackground(Color.RayWhite); // Clear screen background
// Enable shader using the custom uniform
BeginShaderMode(shader);
// NOTE: Render texture must be y-flipped due to default OpenGL coordinates (left-bottom)
@ -116,6 +127,7 @@ public class CustomUniform
EndShaderMode();
// Draw some 2d text over drawn texture
DrawText(
"(c) Barracks 3D model by Alberto Cano",
screenWidth - 220,
@ -130,14 +142,39 @@ public class CustomUniform
//----------------------------------------------------------------------------------
}
public void Unload()
{
UnloadShader(shader); // Unload shader
UnloadTexture(texture); // Unload texture
UnloadModel(model); // Unload model
UnloadRenderTexture(target); // Unload render texture
}
public static int Main()
{
// Initialization
//--------------------------------------------------------------------------------------
SetConfigFlags(ConfigFlags.Msaa4xHint); // Enable Multi Sampling Anti Aliasing 4x (if available)
InitWindow(screenWidth, screenHeight, "raylib [shaders] example - custom uniform");
SetTargetFPS(60); // Set our game to run at 60 frames-per-second
//--------------------------------------------------------------------------------------
var game = new CustomUniform();
game.Init();
// Main game loop
while (!WindowShouldClose()) // Detect window close button or ESC key
{
game.Update();
}
game.Unload();
// De-Initialization
//--------------------------------------------------------------------------------------
UnloadShader(shader);
UnloadTexture(texture);
UnloadModel(model);
UnloadRenderTexture(target);
CloseWindow();
CloseWindow(); // Close window and OpenGL context
//--------------------------------------------------------------------------------------
return 0;

View file

@ -1,8 +1,10 @@
/*******************************************************************************************
*
* raylib [shaders] example - Sieve of Eratosthenes
* raylib [shaders] example - eratosthenes sieve
*
* Sieve of Eratosthenes, the earliest known (ancient Greek) prime number sieve.
* Example complexity rating: [] 3/4
*
* NOTE: Sieve of Eratosthenes, the earliest known (ancient Greek) prime number sieve
*
* "Sift the twos and sift the threes,
* The Sieve of Eratosthenes.
@ -10,16 +12,18 @@
* the numbers that are left are prime."
*
* NOTE: This example requires raylib OpenGL 3.3 or ES2 versions for shaders support,
* OpenGL 1.1 does not support shaders, recompile raylib to OpenGL 3.3 version.
* OpenGL 1.1 does not support shaders, recompile raylib to OpenGL 3.3 version
*
* NOTE: Shaders used in this example are #version 330 (OpenGL 3.3).
* NOTE: Shaders used in this example are #version 330 (OpenGL 3.3)
*
* This example has been created using raylib 2.5 (www.raylib.com)
* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details)
* Example originally created with raylib 2.5, last time updated with raylib 4.0
*
* Example contributed by ProfJski and reviewed by Ramon Santamaria (@raysan5)
* Example contributed by ProfJski (@ProfJski) and reviewed by Ramon Santamaria (@raysan5)
*
* Copyright (c) 2019 ProfJski and Ramon Santamaria (@raysan5)
* Example licensed under an unmodified zlib/libpng license, which is an OSI-certified,
* BSD-like license that allows static linking with closed source software
*
* Copyright (c) 2019-2025 ProfJski (@ProfJski) and Ramon Santamaria (@raysan5)
*
********************************************************************************************/
@ -28,30 +32,34 @@ using static Raylib_cs.Raylib;
namespace Examples.Shaders;
public class Eratosthenes
public class Eratosthenes : IExample
{
const int GlslVersion = 330;
#if BROWSER
const int GlslVersion = 100; // WebGL1 needs GLSL ES 100
#else
private const int GlslVersion = 330;
#endif
public static int Main()
private const int screenWidth = 800;
private const int screenHeight = 450;
public string Name => "Shaders / Eratosthenes";
public string Title => "raylib [shaders] example - eratosthenes sieve";
private RenderTexture2D target;
private Shader shader;
public void Init()
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [shaders] example - Sieve of Eratosthenes");
RenderTexture2D target = LoadRenderTexture(screenWidth, screenHeight);
target = LoadRenderTexture(screenWidth, screenHeight);
// Load Eratosthenes shader
// NOTE: Defining 0 (NULL) for vertex shader forces usage of internal default vertex shader
Shader shader = LoadShader(null, $"resources/shaders/glsl{GlslVersion}/eratosthenes.fs");
shader = LoadShader(null, $"resources/shaders/glsl{GlslVersion}/eratosthenes.fs");
}
SetTargetFPS(60);
//--------------------------------------------------------------------------------------
// Main game loop
while (!WindowShouldClose())
public void Update()
{
// Update
//----------------------------------------------------------------------------------
@ -60,21 +68,18 @@ public class Eratosthenes
// Draw
//----------------------------------------------------------------------------------
BeginDrawing();
ClearBackground(Color.RayWhite);
// Enable drawing to texture
BeginTextureMode(target);
ClearBackground(Color.Black);
BeginTextureMode(target); // Enable drawing to texture
ClearBackground(Color.Black); // Clear the render texture
// Draw a rectangle in shader mode to be used as shader canvas
// NOTE: Rectangle uses font white character texture coordinates,
// so shader can not be applied here directly because input vertexTexCoord
// do not represent full screen coordinates (space where want to apply shader)
DrawRectangle(0, 0, GetScreenWidth(), GetScreenHeight(), Color.Black);
EndTextureMode(); // End drawing to texture (now we have a blank texture available for the shader)
// End drawing to texture (now we have a blank texture available for the shader)
EndTextureMode();
BeginDrawing();
ClearBackground(Color.RayWhite); // Clear screen background
BeginShaderMode(shader);
// NOTE: Render texture must be y-flipped due to default OpenGL coordinates (left-bottom)
@ -90,11 +95,34 @@ public class Eratosthenes
//----------------------------------------------------------------------------------
}
// De-Initialization
//--------------------------------------------------------------------------------------
public void Unload()
{
UnloadShader(shader);
UnloadRenderTexture(target);
}
public static int Main()
{
// Initialization
//--------------------------------------------------------------------------------------
InitWindow(screenWidth, screenHeight, "raylib [shaders] example - eratosthenes sieve");
SetTargetFPS(60);
//--------------------------------------------------------------------------------------
var game = new Eratosthenes();
game.Init();
// Main game loop
while (!WindowShouldClose())
{
game.Update();
}
game.Unload();
// De-Initialization
//--------------------------------------------------------------------------------------
CloseWindow();
//--------------------------------------------------------------------------------------

View file

@ -1,27 +1,22 @@
/*******************************************************************************************
*
* raylib [shaders] example - fog
* raylib [shaders] example - fog rendering
*
* Example complexity rating: [] 3/4
*
* NOTE: This example requires raylib OpenGL 3.3 or ES2 versions for shaders support,
* OpenGL 1.1 does not support shaders, recompile raylib to OpenGL 3.3 version.
* OpenGL 1.1 does not support shaders, recompile raylib to OpenGL 3.3 version
*
* NOTE: Shaders used in this example are #version 330 (OpenGL 3.3).
* NOTE: Shaders used in this example are #version 330 (OpenGL 3.3)
*
* This example has been created using raylib 2.5 (www.raylib.com)
* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details)
* Example originally created with raylib 2.5, last time updated with raylib 3.7
*
* Example contributed by Chris Camacho (@codifies) and reviewed by Ramon Santamaria (@raysan5)
* Example contributed by Chris Camacho (@chriscamacho) and reviewed by Ramon Santamaria (@raysan5)
*
* Chris Camacho (@codifies - http://bedroomcoders.co.uk/) notes:
* Example licensed under an unmodified zlib/libpng license, which is an OSI-certified,
* BSD-like license that allows static linking with closed source software
*
* This is based on the PBR lighting example, but greatly simplified to aid learning...
* actually there is very little of the PBR example left!
* When I first looked at the bewildering complexity of the PBR example I feared
* I would never understand how I could do simple lighting with raylib however its
* a testement to the authors of raylib (including rlights.h) that the example
* came together fairly quickly.
*
* Copyright (c) 2019 Chris Camacho (@codifies) and Ramon Santamaria (@raysan5)
* Copyright (c) 2019-2025 Chris Camacho (@chriscamacho) and Ramon Santamaria (@raysan5)
*
********************************************************************************************/
@ -32,21 +27,36 @@ using Examples.Shared;
namespace Examples.Shaders;
public class Fog
public class Fog : IExample
{
public unsafe static int Main()
#if BROWSER
const int GlslVersion = 100; // WebGL1 needs GLSL ES 100
#else
private const int GlslVersion = 330;
#endif
private const int screenWidth = 800;
private const int screenHeight = 450;
public string Name => "Shaders / Fog";
public string Title => "raylib [shaders] example - fog rendering";
public ConfigFlags ConfigFlags => ConfigFlags.Msaa4xHint;
private Camera3D camera;
private Model modelA;
private Model modelB;
private Model modelC;
private Texture2D texture;
private Shader shader;
private int fogDensityLoc;
private float fogDensity;
public unsafe void Init()
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
// Enable Multi Sampling Anti Aliasing 4x (if available)
SetConfigFlags(ConfigFlags.Msaa4xHint);
InitWindow(screenWidth, screenHeight, "raylib [shaders] example - fog");
// Define the camera to look into our 3d world
Camera3D camera = new();
camera = new();
camera.Position = new Vector3(2.0f, 2.0f, 6.0f);
camera.Target = new Vector3(0.0f, 0.5f, 0.0f);
camera.Up = new Vector3(0.0f, 1.0f, 0.0f);
@ -54,10 +64,10 @@ public class Fog
camera.Projection = CameraProjection.Perspective;
// Load models and texture
Model modelA = LoadModelFromMesh(GenMeshTorus(0.4f, 1.0f, 16, 32));
Model modelB = LoadModelFromMesh(GenMeshCube(1.0f, 1.0f, 1.0f));
Model modelC = LoadModelFromMesh(GenMeshSphere(0.5f, 32, 32));
Texture2D texture = LoadTexture("resources/texel_checker.png");
modelA = LoadModelFromMesh(GenMeshTorus(0.4f, 1.0f, 16, 32));
modelB = LoadModelFromMesh(GenMeshCube(1.0f, 1.0f, 1.0f));
modelC = LoadModelFromMesh(GenMeshSphere(0.5f, 32, 32));
texture = LoadTexture("resources/texel_checker.png");
// Assign texture to default model material
Raylib.SetMaterialTexture(ref modelA, 0, MaterialMapIndex.Albedo, ref texture);
@ -65,12 +75,15 @@ public class Fog
Raylib.SetMaterialTexture(ref modelC, 0, MaterialMapIndex.Albedo, ref texture);
// Load shader and set up some uniforms
Shader shader = LoadShader("resources/shaders/glsl330/lighting.vs", "resources/shaders/glsl330/fog.fs");
shader = LoadShader(
$"resources/shaders/glsl{GlslVersion}/lighting.vs",
$"resources/shaders/glsl{GlslVersion}/fog.fs"
);
shader.Locs[(int)ShaderLocationIndex.MatrixModel] = GetShaderLocation(shader, "matModel");
shader.Locs[(int)ShaderLocationIndex.VectorView] = GetShaderLocation(shader, "viewPos");
// Ambient light level
int ambientLoc = GetShaderLocation(shader, "ambient");
var ambientLoc = GetShaderLocation(shader, "ambient");
Raylib.SetShaderValue(
shader,
ambientLoc,
@ -78,8 +91,12 @@ public class Fog
ShaderUniformDataType.Vec4
);
float fogDensity = 0.15f;
int fogDensityLoc = GetShaderLocation(shader, "fogDensity");
var fogColor = ColorNormalize(Color.Gray);
var fogColorLoc = GetShaderLocation(shader, "fogColor");
Raylib.SetShaderValue(shader, fogColorLoc, fogColor, ShaderUniformDataType.Vec4);
fogDensity = 0.15f;
fogDensityLoc = GetShaderLocation(shader, "fogDensity");
Raylib.SetShaderValue(shader, fogDensityLoc, fogDensity, ShaderUniformDataType.Float);
// NOTE: All models share the same shader
@ -89,12 +106,9 @@ public class Fog
// Using just 1 point lights
Rlights.CreateLight(0, LightType.Point, new Vector3(0, 2, 6), Vector3.Zero, Color.White, shader);
}
SetTargetFPS(60);
//--------------------------------------------------------------------------------------
// Main game loop
while (!WindowShouldClose())
public unsafe void Update()
{
// Update
//----------------------------------------------------------------------------------
@ -145,7 +159,7 @@ public class Fog
DrawModel(modelB, new Vector3(-2.6f, 0, 0), 1.0f, Color.White);
DrawModel(modelC, new Vector3(2.6f, 0, 0), 1.0f, Color.White);
for (int i = -20; i < 20; i += 2)
for (var i = -20; i < 20; i += 2)
{
DrawModel(modelA, new Vector3(i, 0, 2), 1.0f, Color.White);
}
@ -153,7 +167,7 @@ public class Fog
EndMode3D();
DrawText(
$"Use up/down to change fog density [{fogDensity:F2}]",
$"Use KEY_UP/KEY_DOWN to change fog density [{fogDensity:F2}]",
10,
10,
20,
@ -164,15 +178,40 @@ public class Fog
//----------------------------------------------------------------------------------
}
// De-Initialization
//--------------------------------------------------------------------------------------
public void Unload()
{
UnloadModel(modelA);
UnloadModel(modelB);
UnloadModel(modelC);
UnloadTexture(texture);
UnloadShader(shader);
}
public static int Main()
{
// Initialization
//--------------------------------------------------------------------------------------
// Enable Multi Sampling Anti Aliasing 4x (if available)
SetConfigFlags(ConfigFlags.Msaa4xHint);
InitWindow(screenWidth, screenHeight, "raylib [shaders] example - fog rendering");
SetTargetFPS(60);
//--------------------------------------------------------------------------------------
var game = new Fog();
game.Init();
// Main game loop
while (!WindowShouldClose())
{
game.Update();
}
game.Unload();
// De-Initialization
//--------------------------------------------------------------------------------------
CloseWindow();
//--------------------------------------------------------------------------------------

View file

@ -1,80 +1,105 @@
/*******************************************************************************************
*
* raylib [shaders] example - Hot reloading
* raylib [shaders] example - hot reloading
*
* Example complexity rating: [] 3/4
*
* NOTE: This example requires raylib OpenGL 3.3 for shaders support and only #version 330
* is currently supported. OpenGL ES 2.0 platforms are not supported at the moment.
* is currently supported. OpenGL ES 2.0 platforms are not supported at the moment
*
* This example has been created using raylib 3.0 (www.raylib.com)
* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details)
* Example originally created with raylib 3.0, last time updated with raylib 3.5
*
* Copyright (c) 2020 Ramon Santamaria (@raysan5)
* Example licensed under an unmodified zlib/libpng license, which is an OSI-certified,
* BSD-like license that allows static linking with closed source software
*
* Copyright (c) 2020-2025 Ramon Santamaria (@raysan5)
*
********************************************************************************************/
using System;
using System.Numerics;
using static Raylib_cs.Raylib;
namespace Examples.Shaders;
public class HotReloading
public class HotReloading : IExample
{
public static int Main()
#if BROWSER
const int GlslVersion = 100; // WebGL1 needs GLSL ES 100
#else
private const int GlslVersion = 330;
#endif
private const int screenWidth = 800;
private const int screenHeight = 450;
public string Name => "Shaders / Hot Reloading";
public string Title => "raylib [shaders] example - hot reloading";
private string fragShaderFileName;
private Shader shader;
private int resolutionLoc;
private int mouseLoc;
private int timeLoc;
private float[] resolution;
private float totalTime;
#if !BROWSER
private long fragShaderFileModTime;
private bool shaderAutoReloading;
#endif
public void Init()
{
// Initialization
//--------------------------------------------------------------------------------------
int screenWidth = 800;
int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [shaders] example - hot reloading");
string fragShaderFileName = "resources/shaders/glsl330/reload.fs";
long fragShaderFileModTime = GetFileModTime(fragShaderFileName);
fragShaderFileName = $"resources/shaders/glsl{GlslVersion}/reload.fs";
#if !BROWSER
fragShaderFileModTime = GetFileModTime(fragShaderFileName);
#endif
// Load raymarching shader
// NOTE: Defining 0 (NULL) for vertex shader forces usage of internal default vertex shader
Shader shader = LoadShader(null, fragShaderFileName);
shader = LoadShader(null, fragShaderFileName);
// Get shader locations for required uniforms
int resolutionLoc = GetShaderLocation(shader, "resolution");
int mouseLoc = GetShaderLocation(shader, "mouse");
int timeLoc = GetShaderLocation(shader, "time");
resolutionLoc = GetShaderLocation(shader, "resolution");
mouseLoc = GetShaderLocation(shader, "mouse");
timeLoc = GetShaderLocation(shader, "time");
float[] resolution = new[] { (float)screenWidth, (float)screenHeight };
resolution = new[] { (float)screenWidth, (float)screenHeight };
Raylib.SetShaderValue(shader, resolutionLoc, resolution, ShaderUniformDataType.Vec2);
float totalTime = 0.0f;
bool shaderAutoReloading = false;
totalTime = 0.0f;
#if !BROWSER
shaderAutoReloading = false;
#endif
}
SetTargetFPS(60);
//--------------------------------------------------------------------------------------
// Main game loop
while (!WindowShouldClose())
public void Update()
{
// Update
//----------------------------------------------------------------------------------
totalTime += GetFrameTime();
Vector2 mouse = GetMousePosition();
float[] mousePos = new[] { mouse.X, mouse.Y };
var mouse = GetMousePosition();
var mousePos = new[] { mouse.X, mouse.Y };
// Set shader required uniform values
Raylib.SetShaderValue(shader, timeLoc, totalTime, ShaderUniformDataType.Float);
Raylib.SetShaderValue(shader, mouseLoc, mousePos, ShaderUniformDataType.Vec2);
#if !BROWSER
// Hot shader reloading
if (shaderAutoReloading || (IsMouseButtonPressed(MouseButton.Left)))
{
long currentFragShaderModTime = GetFileModTime(fragShaderFileName);
var currentFragShaderModTime = GetFileModTime(fragShaderFileName);
// Check if shader file has been modified
if (currentFragShaderModTime != fragShaderFileModTime)
{
// Try reloading updated shader
Shader updatedShader = LoadShader(null, fragShaderFileName);
var updatedShader = LoadShader(null, fragShaderFileName);
// It was correctly loaded
if (updatedShader.Id != 0) //rlGetShaderIdDefault())
if (updatedShader.Id != Rlgl.GetShaderIdDefault())
{
UnloadShader(shader);
shader = updatedShader;
@ -101,6 +126,7 @@ public class HotReloading
{
shaderAutoReloading = !shaderAutoReloading;
}
#endif
//----------------------------------------------------------------------------------
// Draw
@ -113,23 +139,51 @@ public class HotReloading
DrawRectangle(0, 0, screenWidth, screenHeight, Color.White);
EndShaderMode();
string info = $"PRESS [A] to TOGGLE SHADER AUTOLOADING: {(shaderAutoReloading ? "AUTO" : "MANUAL")}";
#if BROWSER
DrawText("Shader generates the frame in real time", 10, 10, 10, Color.Black);
#else
var info = $"PRESS [A] to TOGGLE SHADER AUTOLOADING: {(shaderAutoReloading ? "AUTO" : "MANUAL")}";
DrawText(info, 10, 10, 10, shaderAutoReloading ? Color.Red : Color.Black);
if (!shaderAutoReloading)
{
DrawText("MOUSE CLICK to SHADER RE-LOADING", 10, 30, 10, Color.Black);
}
// DrawText($"Shader last modification: ", 10, 430, 10, Color.BLACK);
var lastModification = DateTimeOffset.FromUnixTimeSeconds(fragShaderFileModTime).LocalDateTime.ToString();
DrawText($"Shader last modification: {lastModification}", 10, 430, 10, Color.Black);
#endif
EndDrawing();
//----------------------------------------------------------------------------------
}
public void Unload()
{
UnloadShader(shader);
}
public static int Main()
{
// Initialization
//--------------------------------------------------------------------------------------
InitWindow(screenWidth, screenHeight, "raylib [shaders] example - hot reloading");
SetTargetFPS(60);
//--------------------------------------------------------------------------------------
var game = new HotReloading();
game.Init();
// Main game loop
while (!WindowShouldClose())
{
game.Update();
}
game.Unload();
// De-Initialization
//--------------------------------------------------------------------------------------
UnloadShader(shader);
CloseWindow();
//--------------------------------------------------------------------------------------

View file

@ -1,6 +1,8 @@
/*******************************************************************************************
*
* raylib [shaders] example - Hybrid Rendering
* raylib [shaders] example - hybrid rendering
*
* Example complexity rating: [] 4/4
*
* Example originally created with raylib 4.2, last time updated with raylib 4.2
*
@ -9,7 +11,7 @@
* Example licensed under an unmodified zlib/libpng license, which is an OSI-certified,
* BSD-like license that allows static linking with closed source software
*
* Copyright (c) 2022-2023 Buğra Alptekin Sarı (@BugraAlptekinSari)
* Copyright (c) 2022-2025 Buğra Alptekin Sarı (@BugraAlptekinSari)
*
********************************************************************************************/
@ -19,43 +21,54 @@ using static Raylib_cs.Raylib;
namespace Examples.Shaders;
public class HybridRender
public class HybridRender : IExample
{
struct RayLocs
private struct RayLocs
{
public int CamPos;
public int CamDir;
public int ScreenCenter;
}
const int GLSL_VERSION = 330;
#if BROWSER
const int GlslVersion = 100; // WebGL1 needs GLSL ES 100
#else
private const int GlslVersion = 330;
#endif
public static int Main()
private const int screenWidth = 800;
private const int screenHeight = 450;
public string Name => "Shaders / Hybrid Render";
public string Title => "raylib [shaders] example - hybrid rendering";
private Shader shdrRaymarch;
private Shader shdrRaster;
private RayLocs marchLocs;
private RenderTexture2D target;
private Camera3D camera;
private float camDist;
public void Init()
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [shaders] example - hybrid render");
// This shader calculates pixel depth and color using raymarch
Shader shdrRaymarch = LoadShader(null, $"resources/shaders/glsl{GLSL_VERSION}/hybrid_raymarch.fs");
// This Shader calculates pixel depth and color using raymarch
shdrRaymarch = LoadShader(null, $"resources/shaders/glsl{GlslVersion}/hybrid_raymarch.fs");
// This Shader is a standard rasterization fragment shader with the addition of depth writing
// You are required to write depth for all shaders if one shader does it
Shader shdrRaster = LoadShader(null, $"resources/shaders/glsl{GLSL_VERSION}/hybrid_raster.fs");
shdrRaster = LoadShader(null, $"resources/shaders/glsl{GlslVersion}/hybrid_raster.fs");
// Declare struct used to store camera locs
RayLocs marchLocs = new();
// Declare Struct used to store camera locs
marchLocs = new();
// Fill the struct with shader locs.
// Fill the struct with shader locs
marchLocs.CamPos = GetShaderLocation(shdrRaymarch, "camPos");
marchLocs.CamDir = GetShaderLocation(shdrRaymarch, "camDir");
marchLocs.ScreenCenter = GetShaderLocation(shdrRaymarch, "screenCenter");
// Transfer screenCenter position to shader. Which is used to calculate ray direction.
Vector2 screenCenter = new(screenWidth / 2, screenHeight / 2);
// Transfer screenCenter position to shader. Which is used to calculate ray direction
Vector2 screenCenter = new(screenWidth / 2.0f, screenHeight / 2.0f);
SetShaderValue(
shdrRaymarch,
marchLocs.ScreenCenter,
@ -63,31 +76,28 @@ public class HybridRender
ShaderUniformDataType.Vec2
);
// Use customized function to create writable depth texture buffer
RenderTexture2D target = LoadRenderTextureDepthTex(screenWidth, screenHeight);
// Use Customized function to create writable depth texture buffer
target = LoadRenderTextureDepthTex(screenWidth, screenHeight);
// Define the camera to look into our 3d world
Camera3D camera;
camera.Position = new Vector3(0.5f, 1.0f, 1.5f);
camera.Target = new Vector3(0.0f, 0.5f, 0.0f);
camera.Up = new Vector3(0.0f, 1.0f, 0.0f);
camera.FovY = 45.0f;
camera.Projection = CameraProjection.Perspective;
camera = new();
camera.Position = new Vector3(0.5f, 1.0f, 1.5f); // Camera position
camera.Target = new Vector3(0.0f, 0.5f, 0.0f); // Camera looking at point
camera.Up = new Vector3(0.0f, 1.0f, 0.0f); // Camera up vector (rotation towards target)
camera.FovY = 45.0f; // Camera field-of-view Y
camera.Projection = CameraProjection.Perspective; // Camera projection type
// Camera FOV is pre-calculated in the camera Distance.
float camDist = 1.0f / (MathF.Tan(camera.FovY * 0.5f * Raylib.DEG2RAD));
// Camera FOV is pre-calculated in the camera distance
camDist = 1.0f / (MathF.Tan(camera.FovY * 0.5f * Raylib.DEG2RAD));
}
SetTargetFPS(60);
//--------------------------------------------------------------------------------------
// Main game loop
while (!WindowShouldClose())
public void Update()
{
// Update
//----------------------------------------------------------------------------------
UpdateCamera(ref camera, CameraMode.Orbital);
// Update Camera Postion in the ray march shader.
// Update Camera Postion in the ray march shader
SetShaderValue(
shdrRaymarch,
marchLocs.CamPos,
@ -95,8 +105,8 @@ public class HybridRender
ShaderUniformDataType.Vec3
);
// Update Camera Looking Vector. Vector length determines FOV.
Vector3 camDir = Vector3.Normalize(camera.Target - camera.Position) * camDist;
// Update Camera Looking Vector. Vector length determines FOV
var camDir = Vector3.Normalize(camera.Target - camera.Position) * camDist;
SetShaderValue(shdrRaymarch, marchLocs.CamDir, camDir, ShaderUniformDataType.Vec3);
//----------------------------------------------------------------------------------
@ -107,7 +117,7 @@ public class HybridRender
ClearBackground(Color.White);
// Raymarch Scene
// Manually enable Depth Test to handle multiple rendering methods.
// Manually enable Depth Test to handle multiple rendering methods
Rlgl.EnableDepthTest();
BeginShaderMode(shdrRaymarch);
DrawRectangleRec(new Rectangle(0, 0, screenWidth, screenHeight), Color.White);
@ -142,12 +152,35 @@ public class HybridRender
//----------------------------------------------------------------------------------
}
// De-Initialization
//--------------------------------------------------------------------------------------
public void Unload()
{
UnloadRenderTextureDepthTex(target);
UnloadShader(shdrRaymarch);
UnloadShader(shdrRaster);
}
public static int Main()
{
// Initialization
//--------------------------------------------------------------------------------------
InitWindow(screenWidth, screenHeight, "raylib [shaders] example - hybrid rendering");
SetTargetFPS(60);
//--------------------------------------------------------------------------------------
var game = new HybridRender();
game.Init();
// Main game loop
while (!WindowShouldClose())
{
game.Update();
}
game.Unload();
// De-Initialization
//--------------------------------------------------------------------------------------
CloseWindow();
//--------------------------------------------------------------------------------------
@ -203,7 +236,7 @@ public class HybridRender
);
// Check if fbo is complete with attachments (valid)
if (Rlgl.FramebufferComplete(target.Id))
if (Rlgl.FramebufferComplete(target.Id) != 0)
{
TraceLog(TraceLogLevel.Info, $"FBO: [ID {target.Id}] Framebuffer object created successfully");
}

View file

@ -1,18 +1,22 @@
/*******************************************************************************************
*
* raylib [shaders] example - julia sets
* raylib [shaders] example - julia set
*
* Example complexity rating: [] 3/4
*
* NOTE: This example requires raylib OpenGL 3.3 or ES2 versions for shaders support,
* OpenGL 1.1 does not support shaders, recompile raylib to OpenGL 3.3 version.
* OpenGL 1.1 does not support shaders, recompile raylib to OpenGL 3.3 version
*
* NOTE: Shaders used in this example are #version 330 (OpenGL 3.3).
* NOTE: Shaders used in this example are #version 330 (OpenGL 3.3)
*
* This example has been created using raylib 2.5 (www.raylib.com)
* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details)
* Example originally created with raylib 2.5, last time updated with raylib 4.0
*
* Example contributed by eggmund (@eggmund) and reviewed by Ramon Santamaria (@raysan5)
* Example contributed by Josh Colclough (@joshcol9232) and reviewed by Ramon Santamaria (@raysan5)
*
* Copyright (c) 2019 eggmund (@eggmund) and Ramon Santamaria (@raysan5)
* Example licensed under an unmodified zlib/libpng license, which is an OSI-certified,
* BSD-like license that allows static linking with closed source software
*
* Copyright (c) 2019-2025 Josh Colclough (@joshcol9232) and Ramon Santamaria (@raysan5)
*
********************************************************************************************/
@ -21,12 +25,27 @@ using static Raylib_cs.Raylib;
namespace Examples.Shaders;
public class JuliaSet
public class JuliaSet : IExample
{
const int GlslVersion = 330;
private const int screenWidth = 800;
private const int screenHeight = 450;
private const float zoomSpeed = 1.01f;
private const float offsetSpeedMul = 2.0f;
private const float startingZoom = 0.75f;
#if BROWSER
const int GlslVersion = 100; // WebGL1 needs GLSL ES 100
#else
private const int GlslVersion = 330;
#endif
public string Name => "Shaders / Julia Set";
public string Title => "raylib [shaders] example - julia set";
// A few good julia sets
static float[][] PointsOfInterest = new float[][] {
private float[][] PointsOfInterest = new float[][] {
new float[] { -0.348827f, 0.607167f },
new float[] { -0.786268f, 0.169728f },
new float[] { -0.8f, 0.156f },
@ -35,38 +54,38 @@ public class JuliaSet
new float[] { -0.70176f, -0.3842f },
};
public static int Main()
private Shader shader;
private RenderTexture2D target;
private float[] c;
private float[] offset;
private float zoom;
private int cLoc;
private int zoomLoc;
private int offsetLoc;
private int incrementSpeed;
private bool showControls;
public void Init()
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
const float zoomSpeed = 1.01f;
const float offsetSpeedMul = 2.0f;
const float startingZoom = 0.75f;
InitWindow(screenWidth, screenHeight, "raylib [shaders] example - julia sets");
// Load julia set shader
// NOTE: Defining 0 (NULL) for vertex shader forces usage of internal default vertex shader
Shader shader = LoadShader(null, $"resources/shaders/glsl{GlslVersion}/julia_set.fs");
shader = LoadShader(null, $"resources/shaders/glsl{GlslVersion}/julia_set.fs");
// Create a RenderTexture2D to be used for render to texture
RenderTexture2D target = LoadRenderTexture(screenWidth, screenHeight);
target = LoadRenderTexture(screenWidth, screenHeight);
// c constant to use in z^2 + c
float[] c = { PointsOfInterest[0][0], PointsOfInterest[0][1] };
c = new float[] { PointsOfInterest[0][0], PointsOfInterest[0][1] };
// Offset and zoom to draw the julia set at. (centered on screen and default size)
float[] offset = { 0, 0 };
float zoom = startingZoom;
offset = new float[] { 0, 0 };
zoom = startingZoom;
// 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
int cLoc = GetShaderLocation(shader, "c");
int zoomLoc = GetShaderLocation(shader, "zoom");
int offsetLoc = GetShaderLocation(shader, "offset");
cLoc = GetShaderLocation(shader, "c");
zoomLoc = GetShaderLocation(shader, "zoom");
offsetLoc = GetShaderLocation(shader, "offset");
// Upload the shader uniform values!
Raylib.SetShaderValue(shader, cLoc, c, ShaderUniformDataType.Vec2);
@ -74,15 +93,12 @@ public class JuliaSet
Raylib.SetShaderValue(shader, offsetLoc, offset, ShaderUniformDataType.Vec2);
// Multiplier of speed to change c value
int incrementSpeed = 0;
incrementSpeed = 0;
// Show controls
bool showControls = true;
showControls = true;
}
SetTargetFPS(60);
//--------------------------------------------------------------------------------------
// Main game loop
while (!WindowShouldClose())
public void Update()
{
// Update
//----------------------------------------------------------------------------------
@ -128,11 +144,12 @@ public class JuliaSet
Raylib.SetShaderValue(shader, cLoc, c, ShaderUniformDataType.Vec2);
}
// If "R" is pressed, reset zoom and offset
if (IsKeyPressed(KeyboardKey.R))
{
zoom = startingZoom;
offset[0] = 1f;
offset[1] = 1f;
offset[0] = 0.0f;
offset[1] = 0.0f;
Raylib.SetShaderValue(shader, zoomLoc, zoom, ShaderUniformDataType.Float);
Raylib.SetShaderValue(shader, offsetLoc, offset, ShaderUniformDataType.Vec2);
}
@ -171,8 +188,8 @@ public class JuliaSet
zoom *= 1.0f / zoomSpeed;
}
Vector2 mousePos = GetMousePosition();
Vector2 offsetVelocity = Vector2.Zero;
var mousePos = GetMousePosition();
var offsetVelocity = Vector2.Zero;
offsetVelocity.X = (mousePos.X / screenWidth - 0.5f) * offsetSpeedMul / zoom;
offsetVelocity.Y = (mousePos.Y / screenHeight - 0.5f) * offsetSpeedMul / zoom;
@ -186,33 +203,35 @@ public class JuliaSet
}
// Increment c value with time
float amount = GetFrameTime() * incrementSpeed * 0.0005f;
c[0] += amount;
c[1] += amount;
var dc = GetFrameTime() * incrementSpeed * 0.0005f;
c[0] += dc;
c[1] += dc;
Raylib.SetShaderValue(shader, cLoc, c, ShaderUniformDataType.Vec2);
//----------------------------------------------------------------------------------
// Draw
//----------------------------------------------------------------------------------
// Using a render texture to draw Julia set
// Enable drawing to texture
BeginTextureMode(target);
ClearBackground(Color.Black);
// Draw a rectangle in shader mode to be used as shader canvas
// NOTE: Rectangle uses font Color.white character texture coordinates,
// NOTE: Rectangle uses font white character texture coordinates,
// so shader can not be applied here directly because input vertexTexCoord
// do not represent full screen coordinates (space where want to apply shader)
DrawRectangle(0, 0, GetScreenWidth(), GetScreenHeight(), Color.Black);
EndTextureMode();
// Draw
//----------------------------------------------------------------------------------
BeginDrawing();
ClearBackground(Color.Black);
// Draw the saved texture and rendered julia set with shader
// NOTE: We do not invert texture on Y, already considered inside shader
BeginShaderMode(shader);
DrawTexture(target.Texture, 0, 0, Color.White);
// WARNING: If FLAG_WINDOW_HIGHDPI is enabled, HighDPI monitor scaling should be considered
// when rendering the RenderTexture2D to fit in the HighDPI scaled Window
DrawTextureEx(target.Texture, new Vector2(0.0f, 0.0f), 0.0f, 1.0f, Color.White);
EndShaderMode();
if (showControls)
@ -221,7 +240,7 @@ public class JuliaSet
DrawText("Press KEY_F1 to toggle these controls", 10, 30, 10, Color.RayWhite);
DrawText("Press KEYS [1 - 6] to change point of interest", 10, 45, 10, Color.RayWhite);
DrawText("Press KEY_LEFT | KEY_RIGHT to change speed", 10, 60, 10, Color.RayWhite);
DrawText("Press KEY_SPACE to pause movement animation", 10, 75, 10, Color.RayWhite);
DrawText("Press KEY_SPACE to stop movement animation", 10, 75, 10, Color.RayWhite);
DrawText("Press KEY_R to recenter the camera", 10, 90, 10, Color.RayWhite);
}
@ -229,11 +248,34 @@ public class JuliaSet
//----------------------------------------------------------------------------------
}
// De-Initialization
//--------------------------------------------------------------------------------------
public void Unload()
{
UnloadShader(shader);
UnloadRenderTexture(target);
}
public static int Main()
{
// Initialization
//--------------------------------------------------------------------------------------
InitWindow(screenWidth, screenHeight, "raylib [shaders] example - julia set");
SetTargetFPS(60);
//--------------------------------------------------------------------------------------
var game = new JuliaSet();
game.Init();
// Main game loop
while (!WindowShouldClose())
{
game.Update();
}
game.Unload();
// De-Initialization
//--------------------------------------------------------------------------------------
CloseWindow();
//--------------------------------------------------------------------------------------

View file

@ -1,112 +1,97 @@
/*******************************************************************************************
*
* raylib [shaders] example - rlgl module usage for instanced meshes
* raylib [shaders] example - mesh instancing
*
* This example uses [rlgl] module funtionality (pseudo-OpenGL 1.1 style coding)
* Example complexity rating: [] 4/4
*
* This example has been created using raylib 3.5 (www.raylib.com)
* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details)
* Example originally created with raylib 3.7, last time updated with raylib 4.2
*
* Example contributed by @seanpringle and reviewed by Ramon Santamaria (@raysan5)
* Example contributed by seanpringle (@seanpringle) and reviewed by Max (@moliad) and Ramon Santamaria (@raysan5)
*
* Copyright (c) 2020 @seanpringle
* Example licensed under an unmodified zlib/libpng license, which is an OSI-certified,
* BSD-like license that allows static linking with closed source software
*
* Copyright (c) 2020-2025 seanpringle (@seanpringle), Max (@moliad) and Ramon Santamaria (@raysan5)
*
********************************************************************************************/
using System;
using System.Numerics;
using static Raylib_cs.Raylib;
using Examples.Shared;
namespace Examples.Shaders;
public class MeshInstancing
public class MeshInstancing : IExample
{
public static int Main()
private const int screenWidth = 800;
private const int screenHeight = 450;
#if BROWSER
const int GlslVersion = 100; // WebGL1 needs GLSL ES 100
#else
private const int GlslVersion = 330;
#endif
private const int MaxInstances = 10000;
public string Name => "Shaders / Mesh Instancing";
public string Title => "raylib [shaders] example - mesh instancing";
private Camera3D camera;
private Mesh cube;
private Matrix4x4[] transforms;
private Shader shader;
private Material matInstances;
private Material matDefault;
public unsafe void Init()
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
const int fps = 60;
// Enable Multi Sampling Anti Aliasing 4x (if available)
SetConfigFlags(ConfigFlags.Msaa4xHint);
InitWindow(screenWidth, screenHeight, "raylib [shaders] example - rlgl mesh instanced");
// Speed of jump animation
int speed = 30;
// Count of separate groups jumping around
int groups = 2;
// Maximum amplitude of jump
float amp = 10;
// Global variance in jump height
float variance = 0.8f;
// Individual cube's computed loop timer
float loop = 0.0f;
// Used for various 3D coordinate & vector ops
float x = 0.0f;
float y = 0.0f;
float z = 0.0f;
// Define the camera to look into our 3d world
Camera3D camera = new();
camera.Position = new Vector3(-125.0f, 125.0f, -125.0f);
camera.Target = new Vector3(0.0f, 0.0f, 0.0f);
camera.Up = new Vector3(0.0f, 1.0f, 0.0f);
camera.FovY = 45.0f;
camera.Projection = CameraProjection.Perspective;
camera = new();
camera.Position = new Vector3(-125.0f, 125.0f, -125.0f); // Camera position
camera.Target = new Vector3(0.0f, 0.0f, 0.0f); // Camera looking at point
camera.Up = new Vector3(0.0f, 1.0f, 0.0f); // Camera up vector (rotation towards target)
camera.FovY = 45.0f; // Camera field-of-view Y
camera.Projection = CameraProjection.Perspective; // Camera projection type
// Number of instances to display
const int instances = 10000;
Mesh cube = GenMeshCube(1.0f, 1.0f, 1.0f);
// Define mesh to be instanced
cube = GenMeshCube(1.0f, 1.0f, 1.0f);
// Rotation state of instances
Matrix4x4[] rotations = new Matrix4x4[instances];
// Per-frame rotation animation of instances
Matrix4x4[] rotationsInc = new Matrix4x4[instances];
// Locations of instances
Matrix4x4[] translations = new Matrix4x4[instances];
// Define transforms to be uploaded to GPU for instances
transforms = new Matrix4x4[MaxInstances]; // Pre-multiplied transformations passed to rlgl
// Scatter random cubes around
for (int i = 0; i < instances; i++)
// Translate and rotate cubes randomly
for (var i = 0; i < MaxInstances; i++)
{
x = GetRandomValue(-50, 50);
y = GetRandomValue(-50, 50);
z = GetRandomValue(-50, 50);
translations[i] = Matrix4x4.CreateTranslation(x, y, z);
var translation = Matrix4x4.CreateTranslation(
GetRandomValue(-50, 50),
GetRandomValue(-50, 50),
GetRandomValue(-50, 50)
);
var axis = Vector3.Normalize(new Vector3(
GetRandomValue(0, 360),
GetRandomValue(0, 360),
GetRandomValue(0, 360)
));
var angle = GetRandomValue(0, 180) * DEG2RAD;
var rotation = Matrix4x4.CreateFromAxisAngle(axis, angle);
x = GetRandomValue(0, 360);
y = GetRandomValue(0, 360);
z = GetRandomValue(0, 360);
Vector3 axis = Vector3.Normalize(new Vector3(x, y, z));
float angle = (float)GetRandomValue(0, 10) * DEG2RAD;
rotationsInc[i] = Matrix4x4.CreateFromAxisAngle(axis, angle);
rotations[i] = Matrix4x4.Identity;
transforms[i] = Matrix4x4.Transpose(Matrix4x4.Multiply(rotation, translation));
}
// Pre-multiplied transformations passed to rlgl
Matrix4x4[] transforms = new Matrix4x4[instances];
Shader shader = LoadShader(
"resources/shaders/glsl330/lighting_instancing.vs",
"resources/shaders/glsl330/lighting.fs"
// Load lighting shader
shader = LoadShader(
$"resources/shaders/glsl{GlslVersion}/lighting_instancing.vs",
$"resources/shaders/glsl{GlslVersion}/lighting.fs"
);
// Get shader locations
shader.Locs[(int)ShaderLocationIndex.MatrixMvp] = GetShaderLocation(shader, "mvp");
shader.Locs[(int)ShaderLocationIndex.VectorView] = GetShaderLocation(shader, "viewPos");
// Get some shader loactions
unsafe
{
int* locs = (int*)shader.Locs;
locs[(int)ShaderLocationIndex.MatrixMvp] = GetShaderLocation(shader, "mvp");
locs[(int)ShaderLocationIndex.VectorView] = GetShaderLocation(shader, "viewPos");
locs[(int)ShaderLocationIndex.MatrixModel] = GetShaderLocationAttrib(
shader,
"instanceTransform"
);
}
// Ambient light level
int ambientLoc = GetShaderLocation(shader, "ambient");
// Set shader value: ambient light level
var ambientLoc = GetShaderLocation(shader, "ambient");
Raylib.SetShaderValue(
shader,
ambientLoc,
@ -114,211 +99,105 @@ public class MeshInstancing
ShaderUniformDataType.Vec4
);
// Create one light
Rlights.CreateLight(
0,
LightType.Directorional,
new Vector3(50, 50, 0),
new Vector3(50.0f, 50.0f, 0.0f),
Vector3.Zero,
Color.White,
shader
);
Material material = LoadMaterialDefault();
material.Shader = shader;
unsafe
{
material.Maps[(int)MaterialMapIndex.Diffuse].Color = Color.Red;
// NOTE: We are assigning the intancing shader to material.shader
// to be used on mesh drawing with DrawMeshInstanced()
matInstances = LoadMaterialDefault();
matInstances.Shader = shader;
matInstances.Maps[(int)MaterialMapIndex.Diffuse].Color = Color.Red;
// Load default material (using raylib intenral default shader) for non-instanced mesh drawing
// WARNING: Default shader enables vertex color attribute BUT GenMeshCube() does not generate vertex colors, so,
// when drawing the color attribute is disabled and a default color value is provided as input for thevertex attribute
matDefault = LoadMaterialDefault();
matDefault.Maps[(int)MaterialMapIndex.Diffuse].Color = Color.Blue;
}
int textPositionY = 300;
// Simple frames counter to manage animation
int framesCounter = 0;
SetTargetFPS(fps);
//--------------------------------------------------------------------------------------
// Main game loop
while (!WindowShouldClose())
public unsafe void Update()
{
// Update
//----------------------------------------------------------------------------------
UpdateCamera(ref camera, CameraMode.Free);
textPositionY = 300;
framesCounter += 1;
if (IsKeyDown(KeyboardKey.Up))
{
amp += 0.5f;
}
if (IsKeyDown(KeyboardKey.Down))
{
amp = (amp <= 1) ? 1.0f : (amp - 1.0f);
}
if (IsKeyDown(KeyboardKey.Left))
{
variance = (variance <= 0.0f) ? 0.0f : (variance - 0.01f);
}
if (IsKeyDown(KeyboardKey.Right))
{
variance = (variance >= 1.0f) ? 1.0f : (variance + 0.01f);
}
if (IsKeyDown(KeyboardKey.One))
{
groups = 1;
}
if (IsKeyDown(KeyboardKey.Two))
{
groups = 2;
}
if (IsKeyDown(KeyboardKey.Three))
{
groups = 3;
}
if (IsKeyDown(KeyboardKey.Four))
{
groups = 4;
}
if (IsKeyDown(KeyboardKey.Five))
{
groups = 5;
}
if (IsKeyDown(KeyboardKey.Six))
{
groups = 6;
}
if (IsKeyDown(KeyboardKey.Seven))
{
groups = 7;
}
if (IsKeyDown(KeyboardKey.Eight))
{
groups = 8;
}
if (IsKeyDown(KeyboardKey.Nine))
{
groups = 9;
}
if (IsKeyDown(KeyboardKey.W))
{
groups = 7;
amp = 25;
speed = 18;
variance = 0.70f;
}
if (IsKeyDown(KeyboardKey.Equal))
{
speed = (speed <= (int)(fps * 0.25f)) ? (int)(fps * 0.25f) : (int)(speed * 0.95f);
}
if (IsKeyDown(KeyboardKey.KpAdd))
{
speed = (speed <= (int)(fps * 0.25f)) ? (int)(fps * 0.25f) : (int)(speed * 0.95f);
}
if (IsKeyDown(KeyboardKey.Minus))
{
speed = (int)MathF.Max(speed * 1.02f, speed + 1);
}
if (IsKeyDown(KeyboardKey.KpSubtract))
{
speed = (int)MathF.Max(speed * 1.02f, speed + 1);
}
UpdateCamera(ref camera, CameraMode.Orbital);
// Update the light shader with the camera view position
float[] cameraPos = { camera.Position.X, camera.Position.Y, camera.Position.Z };
Raylib.SetShaderValue(
shader,
(int)ShaderLocationIndex.VectorView,
shader.Locs[(int)ShaderLocationIndex.VectorView],
cameraPos,
ShaderUniformDataType.Vec3
);
// Apply per-instance transformations
for (int i = 0; i < instances; i++)
{
rotations[i] = Matrix4x4.Multiply(rotations[i], rotationsInc[i]);
transforms[i] = Matrix4x4.Multiply(rotations[i], translations[i]);
// Get the animation cycle's framesCounter for this instance
loop = (float)((framesCounter + (int)(((float)(i % groups) / groups) * speed)) % speed) / speed;
// Calculate the y according to loop cycle
y = (MathF.Sin(loop * MathF.PI * 2)) * amp * ((1 - variance) + (variance * (float)(i % (groups * 10)) / (groups * 10)));
// Clamp to floor
y = (y < 0) ? 0.0f : y;
transforms[i] = Matrix4x4.Multiply(transforms[i], Matrix4x4.CreateTranslation(0.0f, y, 0.0f));
transforms[i] = Matrix4x4.Transpose(transforms[i]);
}
//----------------------------------------------------------------------------------
// Draw
//----------------------------------------------------------------------------------
BeginDrawing();
ClearBackground(Color.RayWhite);
BeginMode3D(camera);
DrawMeshInstanced(cube, material, transforms, instances);
// Draw cube mesh with default material (BLUE)
DrawMesh(cube, matDefault, Matrix4x4.Transpose(Matrix4x4.CreateTranslation(-10.0f, 0.0f, 0.0f)));
// Draw meshes instanced using material containing instancing shader (RED + lighting),
// transforms[] for the instances should be provided, they are dynamically
// updated in GPU every frame, so we can animate the different mesh instances
DrawMeshInstanced(cube, matInstances, transforms, MaxInstances);
// Draw cube mesh with default material (BLUE)
DrawMesh(cube, matDefault, Matrix4x4.Transpose(Matrix4x4.CreateTranslation(10.0f, 0.0f, 0.0f)));
EndMode3D();
DrawText("A CUBE OF DANCING CUBES!", 490, 10, 20, Color.Maroon);
DrawText("PRESS KEYS:", 10, textPositionY, 20, Color.Black);
DrawText("1 - 9", 10, textPositionY += 25, 10, Color.Black);
DrawText(": Number of groups", 50, textPositionY, 10, Color.Black);
DrawText($": {groups}", 160, textPositionY, 10, Color.Black);
DrawText("UP", 10, textPositionY += 15, 10, Color.Black);
DrawText(": increase amplitude", 50, textPositionY, 10, Color.Black);
DrawText($": {amp}%.2f", 160, textPositionY, 10, Color.Black);
DrawText("DOWN", 10, textPositionY += 15, 10, Color.Black);
DrawText(": decrease amplitude", 50, textPositionY, 10, Color.Black);
DrawText("LEFT", 10, textPositionY += 15, 10, Color.Black);
DrawText(": decrease variance", 50, textPositionY, 10, Color.Black);
DrawText($": {variance}.2f", 160, textPositionY, 10, Color.Black);
DrawText("RIGHT", 10, textPositionY += 15, 10, Color.Black);
DrawText(": increase variance", 50, textPositionY, 10, Color.Black);
DrawText("+/=", 10, textPositionY += 15, 10, Color.Black);
DrawText(": increase speed", 50, textPositionY, 10, Color.Black);
DrawText($": {speed} = {((float)fps / speed)} loops/sec", 160, textPositionY, 10, Color.Black);
DrawText("-", 10, textPositionY += 15, 10, Color.Black);
DrawText(": decrease speed", 50, textPositionY, 10, Color.Black);
DrawText("W", 10, textPositionY += 15, 10, Color.Black);
DrawText(": Wild setup!", 50, textPositionY, 10, Color.Black);
DrawFPS(10, 10);
EndDrawing();
//----------------------------------------------------------------------------------
}
public void Unload()
{
// Detach shader so UnloadMaterial does not also unload it, then free everything.
matInstances.Shader = new();
UnloadMaterial(matInstances);
UnloadMaterial(matDefault);
UnloadMesh(cube);
UnloadShader(shader);
}
public static int Main()
{
// Initialization
//--------------------------------------------------------------------------------------
InitWindow(screenWidth, screenHeight, "raylib [shaders] example - mesh instancing");
SetTargetFPS(60); // Set our game to run at 60 frames-per-second
//--------------------------------------------------------------------------------------
var game = new MeshInstancing();
game.Init();
// Main game loop
while (!WindowShouldClose()) // Detect window close button or ESC key
{
game.Update();
}
game.Unload();
// De-Initialization
//--------------------------------------------------------------------------------------
CloseWindow();
CloseWindow(); // Close window and OpenGL context
//--------------------------------------------------------------------------------------
return 0;

View file

@ -1,18 +1,22 @@
/*******************************************************************************************
*
* raylib [shaders] example - Apply a shader to a 3d model
* raylib [shaders] example - model shader
*
* Example complexity rating: [] 2/4
*
* NOTE: This example requires raylib OpenGL 3.3 or ES2 versions for shaders support,
* OpenGL 1.1 does not support shaders, recompile raylib to OpenGL 3.3 version.
* OpenGL 1.1 does not support shaders, recompile raylib to OpenGL 3.3 version
*
* NOTE: Shaders used in this example are #version 330 (OpenGL 3.3), to test this example
* on OpenGL ES 2.0 platforms (Android, Raspberry Pi, HTML5), use #version 100 shaders
* raylib comes with shaders ready for both versions, check raylib/shaders install folder
*
* 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)
* Example originally created with raylib 1.3, last time updated with raylib 3.7
*
* Copyright (c) 2014 Ramon Santamaria (@raysan5)
* Example licensed under an unmodified zlib/libpng license, which is an OSI-certified,
* BSD-like license that allows static linking with closed source software
*
* Copyright (c) 2014-2025 Ramon Santamaria (@raysan5)
*
********************************************************************************************/
@ -21,43 +25,55 @@ using static Raylib_cs.Raylib;
namespace Examples.Shaders;
public class ModelShader
public class ModelShader : IExample
{
public static int Main()
private const int screenWidth = 800;
private const int screenHeight = 450;
#if BROWSER
const int GlslVersion = 100; // WebGL1 needs GLSL ES 100
#else
private const int GlslVersion = 330;
#endif
public string Name => "Shaders / Model Shader";
public string Title => "raylib [shaders] example - model shader";
public ConfigFlags ConfigFlags => ConfigFlags.Msaa4xHint;
public bool CursorDisabled => true;
private Camera3D camera;
private Model model;
private Texture2D texture;
private Shader shader;
private Vector3 position;
public void Init()
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
// Enable Multi Sampling Anti Aliasing 4x (if available)
SetConfigFlags(ConfigFlags.Msaa4xHint);
InitWindow(screenWidth, screenHeight, "raylib [shaders] example - model shader");
// Define the camera to look into our 3d world
Camera3D camera = new();
camera.Position = new Vector3(4.0f, 4.0f, 4.0f);
camera.Target = new Vector3(0.0f, 1.0f, -1.0f);
camera.Up = new Vector3(0.0f, 1.0f, 0.0f);
camera.FovY = 45.0f;
camera.Projection = CameraProjection.Perspective;
camera = new();
camera.Position = new Vector3(4.0f, 4.0f, 4.0f); // Camera position
camera.Target = new Vector3(0.0f, 1.0f, -1.0f); // Camera looking at point
camera.Up = new Vector3(0.0f, 1.0f, 0.0f); // Camera up vector (rotation towards target)
camera.FovY = 45.0f; // Camera field-of-view Y
camera.Projection = CameraProjection.Perspective; // Camera projection type
Model model = LoadModel("resources/models/obj/watermill.obj");
Texture2D texture = LoadTexture("resources/models/obj/watermill_diffuse.png");
Shader shader = LoadShader("resources/shaders/glsl330/base.vs",
"resources/shaders/glsl330/grayscale.fs");
model = LoadModel("resources/models/obj/watermill.obj"); // Load OBJ model
texture = LoadTexture("resources/models/obj/watermill_diffuse.png"); // Load model texture
Raylib.SetMaterialShader(ref model, 0, ref shader);
Raylib.SetMaterialTexture(ref model, 0, MaterialMapIndex.Albedo, ref texture);
// Load shader for model
// NOTE: Defining 0 (NULL) for vertex shader forces usage of internal default vertex shader
shader = LoadShader(null, $"resources/shaders/glsl{GlslVersion}/grayscale.fs");
Vector3 position = new(0.0f, 0.0f, 0.0f);
Raylib.SetMaterialShader(ref model, 0, ref shader); // Set shader effect to 3d model
Raylib.SetMaterialTexture(ref model, 0, MaterialMapIndex.Albedo, ref texture); // Bind texture to model
SetTargetFPS(60);
//--------------------------------------------------------------------------------------
position = new(0.0f, 0.0f, 0.0f); // Set model position
}
// Main game loop
while (!WindowShouldClose())
public void Update()
{
// Update
//----------------------------------------------------------------------------------
@ -67,13 +83,14 @@ public class ModelShader
// Draw
//----------------------------------------------------------------------------------
BeginDrawing();
ClearBackground(Color.RayWhite);
BeginMode3D(camera);
DrawModel(model, position, 0.2f, Color.White);
DrawModel(model, position, 0.2f, Color.White); // Draw 3d model with texture
DrawGrid(10, 1.0f);
DrawGrid(10, 1.0f); // Draw a grid
EndMode3D();
@ -85,22 +102,45 @@ public class ModelShader
Color.Gray
);
DrawText($"Camera3D position: ({camera.Position})", 600, 20, 10, Color.Black);
DrawText($"Camera3D target: ({camera.Position})", 600, 40, 10, Color.Gray);
DrawFPS(10, 10);
EndDrawing();
//----------------------------------------------------------------------------------
}
public void Unload()
{
UnloadShader(shader); // Unload shader
UnloadTexture(texture); // Unload texture
UnloadModel(model); // Unload model
}
public static int Main()
{
// Initialization
//--------------------------------------------------------------------------------------
SetConfigFlags(ConfigFlags.Msaa4xHint); // Enable Multi Sampling Anti Aliasing 4x (if available)
InitWindow(screenWidth, screenHeight, "raylib [shaders] example - model shader");
DisableCursor(); // Limit cursor to relative movement inside the window
SetTargetFPS(60); // Set our game to run at 60 frames-per-second
//--------------------------------------------------------------------------------------
var game = new ModelShader();
game.Init();
// Main game loop
while (!WindowShouldClose()) // Detect window close button or ESC key
{
game.Update();
}
game.Unload();
// De-Initialization
//--------------------------------------------------------------------------------------
UnloadShader(shader);
UnloadTexture(texture);
UnloadModel(model);
CloseWindow();
CloseWindow(); // Close window and OpenGL context
//--------------------------------------------------------------------------------------
return 0;

View file

@ -1,18 +1,22 @@
/*******************************************************************************************
*
* raylib [shaders] example - Multiple sample2D with default batch system
* raylib [shaders] example - multi sample2d
*
* Example complexity rating: [] 2/4
*
* NOTE: This example requires raylib OpenGL 3.3 or ES2 versions for shaders support,
* OpenGL 1.1 does not support shaders, recompile raylib to OpenGL 3.3 version.
* OpenGL 1.1 does not support shaders, recompile raylib to OpenGL 3.3 version
*
* NOTE: Shaders used in this example are #version 330 (OpenGL 3.3), to test this example
* on OpenGL ES 2.0 platforms (Android, Raspberry Pi, HTML5), use #version 100 shaders
* raylib comes with shaders ready for both versions, check raylib/shaders install folder
*
* This example has been created using raylib 3.5 (www.raylib.com)
* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details)
* Example originally created with raylib 3.5, last time updated with raylib 3.5
*
* Copyright (c) 2020 Ramon Santamaria (@raysan5)
* Example licensed under an unmodified zlib/libpng license, which is an OSI-certified,
* BSD-like license that allows static linking with closed source software
*
* Copyright (c) 2020-2025 Ramon Santamaria (@raysan5)
*
********************************************************************************************/
@ -20,39 +24,49 @@ using static Raylib_cs.Raylib;
namespace Examples.Shaders;
public class MultiSample2d
public class MultiSample2d : IExample
{
public static int Main()
private const int screenWidth = 800;
private const int screenHeight = 450;
#if BROWSER
const int GlslVersion = 100; // WebGL1 needs GLSL ES 100
#else
private const int GlslVersion = 330;
#endif
public string Name => "Shaders / Multi Sample 2D";
public string Title => "raylib [shaders] example - multi sample2d";
private Texture2D texRed;
private Texture2D texBlue;
private Shader shader;
private int texBlueLoc;
private int dividerLoc;
private float dividerValue;
public void Init()
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib - multiple sample2D");
Image imRed = GenImageColor(800, 450, new Color(255, 0, 0, 255));
Texture2D texRed = LoadTextureFromImage(imRed);
var imRed = GenImageColor(800, 450, new Color(255, 0, 0, 255));
texRed = LoadTextureFromImage(imRed);
UnloadImage(imRed);
Image imBlue = GenImageColor(800, 450, new Color(0, 0, 255, 255));
Texture2D texBlue = LoadTextureFromImage(imBlue);
var imBlue = GenImageColor(800, 450, new Color(0, 0, 255, 255));
texBlue = LoadTextureFromImage(imBlue);
UnloadImage(imBlue);
Shader shader = LoadShader(null, "resources/shaders/glsl330/color_mix.fs");
shader = LoadShader(null, $"resources/shaders/glsl{GlslVersion}/color_mix.fs");
// Get an additional sampler2D location to be enabled on drawing
int texBlueLoc = GetShaderLocation(shader, "texture1");
texBlueLoc = GetShaderLocation(shader, "texture1");
// Get shader uniform for divider
int dividerLoc = GetShaderLocation(shader, "divider");
float dividerValue = 0.5f;
dividerLoc = GetShaderLocation(shader, "divider");
dividerValue = 0.5f;
}
SetTargetFPS(60);
//--------------------------------------------------------------------------------------
// Main game loop
while (!WindowShouldClose())
public void Update()
{
// Update
//----------------------------------------------------------------------------------
@ -84,30 +98,55 @@ public class MultiSample2d
BeginShaderMode(shader);
// WARNING: Additional samplers are enabled for all draw calls in the batch,
// EndShaderMode() forces batch drawing and consequently resets active textures
// to let other sampler2D to be activated on consequent drawings (if required)
// WARNING: Additional textures (sampler2D) are enabled for ALL draw calls in the batch,
// but EndShaderMode() forces batch drawing and resets active textures, this way
// other textures (sampler2D) can be activated on consequent drawings (if required)
// The downside of this approach is that SetShaderValue() must be called inside the loop,
// to be set again after every EndShaderMode() reset
SetShaderValueTexture(shader, texBlueLoc, texBlue);
// We are drawing texRed using default sampler2D texture0 but
// an additional texture units is enabled for texBlue (sampler2D texture1)
// We are drawing texRed using default [sampler2D texture0] but
// an additional texture units is enabled for texBlue [sampler2D texture1]
DrawTexture(texRed, 0, 0, Color.White);
EndShaderMode();
EndShaderMode(); // Texture sampler2D is reseted, needs to be set again for next frame
int y = GetScreenHeight() - 40;
var y = GetScreenHeight() - 40;
DrawText("Use KEY_LEFT/KEY_RIGHT to move texture mixing in shader!", 80, y, 20, Color.RayWhite);
EndDrawing();
//----------------------------------------------------------------------------------
}
// De-Initialization
//--------------------------------------------------------------------------------------
public void Unload()
{
UnloadShader(shader);
UnloadTexture(texRed);
UnloadTexture(texBlue);
}
public static int Main()
{
// Initialization
//--------------------------------------------------------------------------------------
InitWindow(screenWidth, screenHeight, "raylib [shaders] example - multi sample2d");
SetTargetFPS(60);
//--------------------------------------------------------------------------------------
var game = new MultiSample2d();
game.Init();
// Main game loop
while (!WindowShouldClose())
{
game.Update();
}
game.Unload();
// De-Initialization
//--------------------------------------------------------------------------------------
CloseWindow();
//--------------------------------------------------------------------------------------

View file

@ -1,20 +1,24 @@
/*******************************************************************************************
*
* raylib [shaders] example - Color palette switch
* raylib [shaders] example - palette switch
*
* Example complexity rating: [] 3/4
*
* NOTE: This example requires raylib OpenGL 3.3 or ES2 versions for shaders support,
* OpenGL 1.1 does not support shaders, recompile raylib to OpenGL 3.3 version.
* OpenGL 1.1 does not support shaders, recompile raylib to OpenGL 3.3 version
*
* NOTE: Shaders used in this example are #version 330 (OpenGL 3.3), to test this example
* on OpenGL ES 2.0 platforms (Android, Raspberry Pi, HTML5), use #version 100 shaders
* raylib comes with shaders ready for both versions, check raylib/shaders install folder
*
* This example has been created using raylib 2.3 (www.raylib.com)
* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details)
* Example originally created with raylib 2.5, last time updated with raylib 3.7
*
* Example contributed by Marco Lizza (@MarcoLizza) and reviewed by Ramon Santamaria (@raysan5)
*
* Copyright (c) 2019 Marco Lizza (@MarcoLizza) and Ramon Santamaria (@raysan5)
* Example licensed under an unmodified zlib/libpng license, which is an OSI-certified,
* BSD-like license that allows static linking with closed source software
*
* Copyright (c) 2019-2025 Marco Lizza (@MarcoLizza) and Ramon Santamaria (@raysan5)
*
********************************************************************************************/
@ -22,13 +26,24 @@ using static Raylib_cs.Raylib;
namespace Examples.Shaders;
public class PaletteSwitch
public class PaletteSwitch : IExample
{
const int GlslVersion = 330;
const int ColorsPerPalette = 8;
const int VALUES_PER_COLOR = 3;
private const int screenWidth = 800;
private const int screenHeight = 450;
static int[][] Palettes = new int[][] {
#if BROWSER
const int GlslVersion = 100; // WebGL1 needs GLSL ES 100
#else
private const int GlslVersion = 330;
#endif
private const int ColorsPerPalette = 8;
private const int VALUES_PER_COLOR = 3;
public string Name => "Shaders / Palette Switch";
public string Title => "raylib [shaders] example - palette switch";
private int[][] Palettes = new int[][] {
// 3-BIT RGB
new int[] {
0, 0, 0,
@ -64,38 +79,33 @@ public class PaletteSwitch
}
};
static string[] PaletteText = new string[] {
private string[] PaletteText = new string[] {
"3-BIT RGB",
"AMMO-8 (GameBoy-like)",
"RKBV (2-strip film)"
};
public static int Main()
private Shader shader;
private int paletteLoc;
private int currentPalette;
private int lineHeight;
public void Init()
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [shaders] example - color palette switch");
// 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 2: Defining 0 (NULL) for vertex shader forces usage of internal default vertex shader
Shader shader = LoadShader(null, $"resources/shaders/glsl{GlslVersion}/palette_switch.fs");
shader = LoadShader(null, $"resources/shaders/glsl{GlslVersion}/palette_switch.fs");
// 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
int paletteLoc = GetShaderLocation(shader, "palette");
paletteLoc = GetShaderLocation(shader, "palette");
int currentPalette = 0;
int lineHeight = screenHeight / ColorsPerPalette;
currentPalette = 0;
lineHeight = screenHeight / ColorsPerPalette;
}
SetTargetFPS(60);
//--------------------------------------------------------------------------------------
// Main game loop
while (!WindowShouldClose())
public void Update()
{
// Update
//----------------------------------------------------------------------------------
@ -117,7 +127,7 @@ public class PaletteSwitch
currentPalette = Palettes.Length - 1;
}
// Send new value to the shader to be used on drawing.
// Send palette data to the shader to be used on drawing
// NOTE: We are sending RGB triplets w/o the alpha channel
Raylib.SetShaderValueV(
shader,
@ -135,7 +145,7 @@ public class PaletteSwitch
BeginShaderMode(shader);
for (int i = 0; i < ColorsPerPalette; i++)
for (var i = 0; i < ColorsPerPalette; i++)
{
// Draw horizontal screen-wide rectangles with increasing "palette index"
// The used palette index is encoded in the RGB components of the pixel
@ -154,11 +164,34 @@ public class PaletteSwitch
//----------------------------------------------------------------------------------
}
public void Unload()
{
UnloadShader(shader); // Unload shader
}
public static int Main()
{
// Initialization
//--------------------------------------------------------------------------------------
InitWindow(screenWidth, screenHeight, "raylib [shaders] example - palette switch");
SetTargetFPS(60); // Set our game to run at 60 frames-per-second
//--------------------------------------------------------------------------------------
var game = new PaletteSwitch();
game.Init();
// Main game loop
while (!WindowShouldClose()) // Detect window close button or ESC key
{
game.Update();
}
game.Unload();
// De-Initialization
//--------------------------------------------------------------------------------------
UnloadShader(shader);
CloseWindow();
CloseWindow(); // Close window and OpenGL context
//--------------------------------------------------------------------------------------
return 0;

View file

@ -1,18 +1,22 @@
/*******************************************************************************************
*
* raylib [shaders] example - Apply a postprocessing shader to a scene
* raylib [shaders] example - postprocessing
*
* Example complexity rating: [] 3/4
*
* NOTE: This example requires raylib OpenGL 3.3 or ES2 versions for shaders support,
* OpenGL 1.1 does not support shaders, recompile raylib to OpenGL 3.3 version.
* OpenGL 1.1 does not support shaders, recompile raylib to OpenGL 3.3 version
*
* NOTE: Shaders used in this example are #version 330 (OpenGL 3.3), to test this example
* on OpenGL ES 2.0 platforms (Android, Raspberry Pi, HTML5), use #version 100 shaders
* raylib comes with shaders ready for both versions, check raylib/shaders install folder
*
* 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)
* Example originally created with raylib 1.3, last time updated with raylib 4.0
*
* Copyright (c) 2015 Ramon Santamaria (@raysan5)
* Example licensed under an unmodified zlib/libpng license, which is an OSI-certified,
* BSD-like license that allows static linking with closed source software
*
* Copyright (c) 2015-2025 Ramon Santamaria (@raysan5)
*
********************************************************************************************/
@ -21,11 +25,24 @@ using static Raylib_cs.Raylib;
namespace Examples.Shaders;
public class PostProcessing
public class PostProcessing : IExample
{
public const int GLSL_VERSION = 330;
private const int screenWidth = 800;
private const int screenHeight = 450;
enum PostproShader
#if BROWSER
const int GlslVersion = 100; // WebGL1 needs GLSL ES 100
#else
private const int GlslVersion = 330;
#endif
public string Name => "Shaders / Post Processing";
public string Title => "raylib [shaders] example - postprocessing";
public ConfigFlags ConfigFlags => ConfigFlags.Msaa4xHint;
private enum PostproShader
{
FxGrayScale = 0,
FxPosterization,
@ -43,7 +60,7 @@ public class PostProcessing
Max
}
static string[] postproShaderText = new string[] {
private string[] postproShaderText = new string[] {
"GRAYSCALE",
"POSTERIZATION",
"DREAM_VISION",
@ -59,40 +76,39 @@ public class PostProcessing
//"FXAA"
};
public static int Main()
private Camera3D camera;
private Model model;
private Texture2D texture;
private Vector3 position;
private Shader[] shaders;
private int currentShader;
private RenderTexture2D target;
public void Init()
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
// Enable Multi Sampling Anti Aliasing 4x (if available)
SetConfigFlags(ConfigFlags.Msaa4xHint);
InitWindow(screenWidth, screenHeight, "raylib [shaders] example - postprocessing shader");
// Define the camera to look into our 3d world
Camera3D camera = new();
camera.Position = new Vector3(2.0f, 3.0f, 2.0f);
camera.Target = new Vector3(0.0f, 1.0f, 0.0f);
camera.Up = new Vector3(0.0f, 1.0f, 0.0f);
camera.FovY = 45.0f;
camera.Projection = CameraProjection.Perspective;
camera = new();
camera.Position = new Vector3(2.0f, 3.0f, 2.0f); // Camera position
camera.Target = new Vector3(0.0f, 1.0f, 0.0f); // Camera looking at point
camera.Up = new Vector3(0.0f, 1.0f, 0.0f); // Camera up vector (rotation towards target)
camera.FovY = 45.0f; // Camera field-of-view Y
camera.Projection = CameraProjection.Perspective; // Camera projection type
Model model = LoadModel("resources/models/obj/church.obj");
Texture2D texture = LoadTexture("resources/models/obj/church_diffuse.png");
model = LoadModel("resources/models/church.obj"); // Load OBJ model
texture = LoadTexture("resources/models/church_diffuse.png"); // Load model texture (diffuse map)
// Set model diffuse texture
Raylib.SetMaterialTexture(ref model, 0, MaterialMapIndex.Albedo, ref texture);
Vector3 position = new(0.0f, 0.0f, 0.0f);
position = new(0.0f, 0.0f, 0.0f); // Set model position
// Load all postpro shaders
// NOTE 1: All postpro shader use the base vertex shader (DEFAULT_VERTEX_SHADER)
// NOTE 2: We load the correct shader depending on GLSL version
Shader[] shaders = new Shader[(int)PostproShader.Max];
shaders = new Shader[(int)PostproShader.Max];
// NOTE: Defining null (NULL) for vertex shader forces usage of internal default vertex shader
string shaderPath = "resources/shaders/glsl330";
var shaderPath = $"resources/shaders/glsl{GlslVersion}";
shaders[(int)PostproShader.FxGrayScale] = LoadShader(null, $"{shaderPath}/grayscale.fs");
shaders[(int)PostproShader.FxPosterization] = LoadShader(null, $"{shaderPath}/posterization.fs");
shaders[(int)PostproShader.FxDreamVision] = LoadShader(null, $"{shaderPath}/dream_vision.fs");
@ -106,16 +122,13 @@ public class PostProcessing
shaders[(int)PostproShader.FxBloom] = LoadShader(null, $"{shaderPath}/bloom.fs");
shaders[(int)PostproShader.FxBlur] = LoadShader(null, $"{shaderPath}/blur.fs");
int currentShader = (int)PostproShader.FxGrayScale;
currentShader = (int)PostproShader.FxGrayScale;
// Create a RenderTexture2D to be used for render to texture
RenderTexture2D target = LoadRenderTexture(screenWidth, screenHeight);
target = LoadRenderTexture(screenWidth, screenHeight);
}
SetTargetFPS(60);
//--------------------------------------------------------------------------------------
// Main game loop
while (!WindowShouldClose())
public void Update()
{
// Update
//----------------------------------------------------------------------------------
@ -160,7 +173,7 @@ public class PostProcessing
// End drawing to texture (now we have a texture available for next passes)
EndTextureMode();
// Render previously generated texture using selected postpro shader
// Render generated texture using selected postprocessing shader
BeginShaderMode(shaders[currentShader]);
// NOTE: Render texture must be y-flipped due to default OpenGL coordinates (left-bottom)
@ -173,7 +186,7 @@ public class PostProcessing
EndShaderMode();
DrawRectangle(0, 9, 580, 30, ColorAlpha(Color.LightGray, 0.7f));
DrawRectangle(0, 9, 580, 30, Fade(Color.LightGray, 0.7f));
DrawText("(c) Church 3D model by Alberto Cano", screenWidth - 200, screenHeight - 20, 10, Color.Gray);
@ -187,18 +200,44 @@ public class PostProcessing
//----------------------------------------------------------------------------------
}
// De-Initialization
//--------------------------------------------------------------------------------------
for (int i = 0; i < (int)PostproShader.Max; i++)
public void Unload()
{
// Unload all postpro shaders
for (var i = 0; i < (int)PostproShader.Max; i++)
{
UnloadShader(shaders[i]);
}
UnloadTexture(texture);
UnloadModel(model);
UnloadRenderTexture(target);
UnloadTexture(texture); // Unload texture
UnloadModel(model); // Unload model
UnloadRenderTexture(target); // Unload render texture
}
CloseWindow();
public static int Main()
{
// Initialization
//--------------------------------------------------------------------------------------
SetConfigFlags(ConfigFlags.Msaa4xHint); // Enable Multi Sampling Anti Aliasing 4x (if available)
InitWindow(screenWidth, screenHeight, "raylib [shaders] example - postprocessing");
SetTargetFPS(60); // Set our game to run at 60 frames-per-second
//--------------------------------------------------------------------------------------
var game = new PostProcessing();
game.Init();
// Main game loop
while (!WindowShouldClose()) // Detect window close button or ESC key
{
game.Update();
}
game.Unload();
// De-Initialization
//--------------------------------------------------------------------------------------
CloseWindow(); // Close window and OpenGL context
//--------------------------------------------------------------------------------------
return 0;

View file

@ -1,18 +1,18 @@
/*******************************************************************************************
*
* raylib [shaders] example - Raymarching shapes generation
* raylib [shaders] example - raymarching rendering
*
* NOTE: This example requires raylib OpenGL 3.3 or ES2 versions for shaders support,
* OpenGL 1.1 does not support shaders, recompile raylib to OpenGL 3.3 version.
* Example complexity rating: [] 4/4
*
* NOTE: Shaders used in this example are #version 330 (OpenGL 3.3), to test this example
* on OpenGL ES 2.0 platforms (Android, Raspberry Pi, HTML5), use #version 100 shaders
* raylib comes with shaders ready for both versions, check raylib/shaders install folder
* NOTE: This example requires raylib OpenGL 3.3 for shaders support and only #version 330
* is currently supported. OpenGL ES 2.0 platforms are not supported at the moment
*
* This example has been created using raylib 2.0 (www.raylib.com)
* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details)
* Example originally created with raylib 2.0, last time updated with raylib 4.2
*
* Copyright (c) 2018 Ramon Santamaria (@raysan5)
* Example licensed under an unmodified zlib/libpng license, which is an OSI-certified,
* BSD-like license that allows static linking with closed source software
*
* Copyright (c) 2018-2025 Ramon Santamaria (@raysan5)
*
********************************************************************************************/
@ -22,68 +22,83 @@ using static Raylib_cs.ConfigFlags;
namespace Examples.Shaders;
public class Raymarching
public class Raymarching : IExample
{
#if BROWSER
public const int GlslVersion = 100; // WebGL1 needs GLSL ES 100
#else
public const int GlslVersion = 330;
#endif
public static int Main()
public string Name => "Shaders / Raymarching";
public string Title => "raylib [shaders] example - raymarching rendering";
public ConfigFlags ConfigFlags => ConfigFlags.ResizableWindow;
public bool CursorDisabled => true;
private int screenWidth;
private int screenHeight;
private Camera3D camera;
private Shader shader;
private int viewEyeLoc;
private int viewCenterLoc;
private int runTimeLoc;
private int resolutionLoc;
private float runTime;
public void Init()
{
// Initialization
//--------------------------------------------------------------------------------------
int screenWidth = 800;
int screenHeight = 450;
screenWidth = GetScreenWidth();
screenHeight = GetScreenHeight();
SetConfigFlags(ResizableWindow);
InitWindow(screenWidth, screenHeight, "raylib [shaders] example - raymarching shapes");
Camera3D camera = new();
camera.Position = new Vector3(2.5f, 2.5f, 3.0f);
camera.Target = new Vector3(0.0f, 0.0f, 0.7f);
camera.Up = new Vector3(0.0f, 1.0f, 0.0f);
camera.FovY = 65.0f;
camera = new();
camera.Position = new Vector3(2.5f, 2.5f, 3.0f); // Camera position
camera.Target = new Vector3(0.0f, 0.0f, 0.7f); // Camera looking at point
camera.Up = new Vector3(0.0f, 1.0f, 0.0f); // Camera up vector (rotation towards target)
camera.FovY = 65.0f; // Camera field-of-view Y
camera.Projection = CameraProjection.Perspective; // Camera projection type
// Load raymarching shader
// NOTE: Defining 0 (NULL) for vertex shader forces usage of internal default vertex shader
Shader shader = LoadShader(null, $"resources/shaders/glsl{GlslVersion}/raymarching.fs");
shader = LoadShader(null, $"resources/shaders/glsl{GlslVersion}/raymarching.fs");
// Get shader locations for required uniforms
int viewEyeLoc = GetShaderLocation(shader, "viewEye");
int viewCenterLoc = GetShaderLocation(shader, "viewCenter");
int runTimeLoc = GetShaderLocation(shader, "runTime");
int resolutionLoc = GetShaderLocation(shader, "resolution");
viewEyeLoc = GetShaderLocation(shader, "viewEye");
viewCenterLoc = GetShaderLocation(shader, "viewCenter");
runTimeLoc = GetShaderLocation(shader, "runTime");
resolutionLoc = GetShaderLocation(shader, "resolution");
float[] resolution = { (float)screenWidth, (float)screenHeight };
Raylib.SetShaderValue(shader, resolutionLoc, resolution, ShaderUniformDataType.Vec2);
float runTime = 0.0f;
SetTargetFPS(60);
//--------------------------------------------------------------------------------------
// Main game loop
while (!WindowShouldClose())
{
// Check if screen is resized
//----------------------------------------------------------------------------------
if (IsWindowResized())
{
screenWidth = GetScreenWidth();
screenHeight = GetScreenHeight();
resolution = new float[] { (float)screenWidth, (float)screenHeight };
Raylib.SetShaderValue(shader, resolutionLoc, resolution, ShaderUniformDataType.Vec2);
runTime = 0.0f;
}
public void Update()
{
// Update
//----------------------------------------------------------------------------------
UpdateCamera(ref camera, CameraMode.Free);
UpdateCamera(ref camera, CameraMode.FirstPerson);
float deltaTime = GetFrameTime();
var deltaTime = GetFrameTime();
runTime += deltaTime;
// Set shader required uniform values
Raylib.SetShaderValue(shader, viewEyeLoc, camera.Position, ShaderUniformDataType.Vec3);
Raylib.SetShaderValue(shader, viewCenterLoc, camera.Target, ShaderUniformDataType.Vec3);
Raylib.SetShaderValue(shader, runTimeLoc, runTime, ShaderUniformDataType.Float);
// Check if screen is resized
if (IsWindowResized())
{
screenWidth = GetScreenWidth();
screenHeight = GetScreenHeight();
var resolution = new float[] { (float)screenWidth, (float)screenHeight };
Raylib.SetShaderValue(shader, resolutionLoc, resolution, ShaderUniformDataType.Vec2);
}
//----------------------------------------------------------------------------------
// Draw
@ -109,11 +124,36 @@ public class Raymarching
//----------------------------------------------------------------------------------
}
public void Unload()
{
UnloadShader(shader); // Unload shader
}
public static int Main()
{
// Initialization
//--------------------------------------------------------------------------------------
SetConfigFlags(ResizableWindow);
InitWindow(800, 450, "raylib [shaders] example - raymarching rendering");
DisableCursor(); // Limit cursor to relative movement inside the window
SetTargetFPS(60); // Set our game to run at 60 frames-per-second
//--------------------------------------------------------------------------------------
var game = new Raymarching();
game.Init();
// Main game loop
while (!WindowShouldClose()) // Detect window close button or ESC key
{
game.Update();
}
game.Unload();
// De-Initialization
//--------------------------------------------------------------------------------------
UnloadShader(shader);
CloseWindow();
CloseWindow(); // Close window and OpenGL context
//--------------------------------------------------------------------------------------
return 0;

View file

@ -1,18 +1,22 @@
/*******************************************************************************************
*
* raylib [shaders] example - Apply a shader to some shape or texture
* raylib [shaders] example - shapes textures
*
* Example complexity rating: [] 2/4
*
* NOTE: This example requires raylib OpenGL 3.3 or ES2 versions for shaders support,
* OpenGL 1.1 does not support shaders, recompile raylib to OpenGL 3.3 version.
* OpenGL 1.1 does not support shaders, recompile raylib to OpenGL 3.3 version
*
* NOTE: Shaders used in this example are #version 330 (OpenGL 3.3), to test this example
* on OpenGL ES 2.0 platforms (Android, Raspberry Pi, HTML5), use #version 100 shaders
* raylib comes with shaders ready for both versions, check raylib/shaders install folder
*
* This example has been created using raylib 1.7 (www.raylib.com)
* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details)
* Example originally created with raylib 1.7, last time updated with raylib 3.7
*
* Copyright (c) 2015 Ramon Santamaria (@raysan5)
* Example licensed under an unmodified zlib/libpng license, which is an OSI-certified,
* BSD-like license that allows static linking with closed source software
*
* Copyright (c) 2015-2025 Ramon Santamaria (@raysan5)
*
********************************************************************************************/
@ -21,36 +25,36 @@ using static Raylib_cs.Raylib;
namespace Examples.Shaders;
public class ShapesTextures
public class ShapesTextures : IExample
{
public static int Main()
private const int screenWidth = 800;
private const int screenHeight = 450;
#if BROWSER
const int GlslVersion = 100; // WebGL1 needs GLSL ES 100
#else
private const int GlslVersion = 330;
#endif
public string Name => "Shaders / Shapes Textures";
public string Title => "raylib [shaders] example - shapes textures";
private Texture2D fudesumi;
private Shader shader;
public void Init()
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
fudesumi = LoadTexture("resources/fudesumi.png");
InitWindow(screenWidth, screenHeight, "raylib [shaders] example - shapes and texture shaders");
// 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 2: Defining null (NULL) for vertex shader forces usage of internal default vertex shader
shader = LoadShader(null, $"resources/shaders/glsl{GlslVersion}/grayscale.fs");
}
Texture2D fudesumi = LoadTexture("resources/fudesumi.png");
// NOTE: Using GLSL 330 shader version, on OpenGL ES 2.0 use GLSL 100 shader version
Shader shader = LoadShader(
"resources/shaders/glsl330/base.vs",
"resources/shaders/glsl330/grayscale.fs"
);
SetTargetFPS(60);
//--------------------------------------------------------------------------------------
// Main game loop
while (!WindowShouldClose())
public void Update()
{
// Update
//----------------------------------------------------------------------------------
// TODO: Update your variables here
//----------------------------------------------------------------------------------
// Draw
//----------------------------------------------------------------------------------
BeginDrawing();
@ -107,15 +111,37 @@ public class ShapesTextures
//----------------------------------------------------------------------------------
}
public void Unload()
{
UnloadShader(shader); // Unload shader
UnloadTexture(fudesumi); // Unload texture
}
public static int Main()
{
// Initialization
//--------------------------------------------------------------------------------------
InitWindow(screenWidth, screenHeight, "raylib [shaders] example - shapes textures");
SetTargetFPS(60); // Set our game to run at 60 frames-per-second
//--------------------------------------------------------------------------------------
var game = new ShapesTextures();
game.Init();
// Main game loop
while (!WindowShouldClose()) // Detect window close button or ESC key
{
game.Update();
}
game.Unload();
// De-Initialization
//--------------------------------------------------------------------------------------
UnloadShader(shader);
UnloadTexture(fudesumi);
CloseWindow();
CloseWindow(); // Close window and OpenGL context
//--------------------------------------------------------------------------------------
return 0;
}
}

View file

@ -1,13 +1,17 @@
/*******************************************************************************************
*
* raylib [shaders] example - Simple shader mask
* raylib [shaders] example - simple mask
*
* This example has been created using raylib 2.5 (www.raylib.com)
* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details)
* Example complexity rating: [] 2/4
*
* Example contributed by Chris Camacho (@codifies) and reviewed by Ramon Santamaria (@raysan5)
* Example originally created with raylib 2.5, last time updated with raylib 3.7
*
* Copyright (c) 2019 Chris Camacho (@codifies) and Ramon Santamaria (@raysan5)
* Example contributed by Chris Camacho (@chriscamacho) and reviewed by Ramon Santamaria (@raysan5)
*
* Example licensed under an unmodified zlib/libpng license, which is an OSI-certified,
* BSD-like license that allows static linking with closed source software
*
* Copyright (c) 2019-2025 Chris Camacho (@chriscamacho) and Ramon Santamaria (@raysan5)
*
********************************************************************************************
*
@ -24,54 +28,72 @@ using static Raylib_cs.Raymath;
namespace Examples.Shaders;
public class SimpleMask
public class SimpleMask : IExample
{
public unsafe static int Main()
private const int screenWidth = 800;
private const int screenHeight = 450;
#if BROWSER
const int GlslVersion = 100; // WebGL1 needs GLSL ES 100
#else
private const int GlslVersion = 330;
#endif
public string Name => "Shaders / Simple Mask";
public string Title => "raylib [shaders] example - simple mask";
public bool CursorDisabled => true;
private Camera3D camera;
private Model model1;
private Model model2;
private Model model3;
private Shader shader;
private Texture2D texDiffuse;
private Texture2D texMask;
private int shaderFrame;
private int framesCounter;
private Vector3 rotation;
public unsafe void Init()
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib - simple shader mask");
// Define the camera to look into our 3d world
Camera3D camera = new();
camera.Position = new Vector3(0.0f, 1.0f, 2.0f);
camera.Target = new Vector3(0.0f, 0.0f, 0.0f);
camera.Up = new Vector3(0.0f, 1.0f, 0.0f);
camera.FovY = 45.0f;
camera.Projection = CameraProjection.Perspective;
camera = new();
camera.Position = new Vector3(0.0f, 1.0f, 2.0f); // Camera position
camera.Target = new Vector3(0.0f, 0.0f, 0.0f); // Camera looking at point
camera.Up = new Vector3(0.0f, 1.0f, 0.0f); // Camera up vector (rotation towards target)
camera.FovY = 45.0f; // Camera field-of-view Y
camera.Projection = CameraProjection.Perspective; // Camera projection type
// Define our three models to show the shader on
Mesh torus = GenMeshTorus(.3f, 1, 16, 32);
Model model1 = LoadModelFromMesh(torus);
var torus = GenMeshTorus(.3f, 1, 16, 32);
model1 = LoadModelFromMesh(torus);
Mesh cube = GenMeshCube(.8f, .8f, .8f);
Model model2 = LoadModelFromMesh(cube);
var cube = GenMeshCube(.8f, .8f, .8f);
model2 = LoadModelFromMesh(cube);
// Generate model to be shaded just to see the gaps in the other two
Mesh sphere = GenMeshSphere(1, 16, 16);
Model model3 = LoadModelFromMesh(sphere);
var sphere = GenMeshSphere(1, 16, 16);
model3 = LoadModelFromMesh(sphere);
// Load the shader
Shader shader = LoadShader("resources/shaders/glsl330/mask.vs", "resources/shaders/glsl330/mask.fs");
shader = LoadShader(null, $"resources/shaders/glsl{GlslVersion}/mask.fs");
// Load and apply the diffuse texture (colour map)
Texture2D texDiffuse = LoadTexture("resources/plasma.png");
texDiffuse = LoadTexture("resources/plasma.png");
Material* materials = model1.Materials;
MaterialMap* maps = materials[0].Maps;
var materials = model1.Materials;
var maps = materials[0].Maps;
model1.Materials[0].Maps[(int)MaterialMapIndex.Albedo].Texture = texDiffuse;
materials = model2.Materials;
maps = materials[0].Maps;
maps[(int)MaterialMapIndex.Albedo].Texture = texDiffuse;
// Using MAP_EMISSION as a spare slot to use for 2nd texture
// NOTE: Don't use MAP_IRRADIANCE, MAP_PREFILTER or MAP_CUBEMAP
// as they are bound as cube maps
Texture2D texMask = LoadTexture("resources/mask.png");
// Using MATERIAL_MAP_EMISSION as a spare slot to use for 2nd texture
// NOTE: Don't use MATERIAL_MAP_IRRADIANCE, MATERIAL_MAP_PREFILTER or MATERIAL_MAP_CUBEMAP as they are bound as cube maps
texMask = LoadTexture("resources/mask.png");
materials = model1.Materials;
maps = (MaterialMap*)materials[0].Maps;
@ -81,11 +103,11 @@ public class SimpleMask
maps = (MaterialMap*)materials[0].Maps;
maps[(int)MaterialMapIndex.Emission].Texture = texMask;
int* locs = shader.Locs;
var locs = shader.Locs;
locs[(int)ShaderLocationIndex.MapEmission] = GetShaderLocation(shader, "mask");
// Frame is incremented each frame to animate the shader
int shaderFrame = GetShaderLocation(shader, "framesCounter");
shaderFrame = GetShaderLocation(shader, "frame");
// Apply the shader to the two models
materials = model1.Materials;
@ -94,19 +116,16 @@ public class SimpleMask
materials = (Material*)model2.Materials;
materials[0].Shader = shader;
int framesCounter = 0;
framesCounter = 0;
rotation = new(0, 0, 0); // Model rotation angles
}
// Model rotation angles
Vector3 rotation = new(0, 0, 0);
SetTargetFPS(60);
//--------------------------------------------------------------------------------------
// Main game loop
while (!WindowShouldClose())
public void Update()
{
// Update
//----------------------------------------------------------------------------------
UpdateCamera(ref camera, CameraMode.FirstPerson);
framesCounter++;
rotation.X += 0.01f;
rotation.Y += 0.005f;
@ -117,8 +136,6 @@ public class SimpleMask
// Rotate one of the models
model1.Transform = MatrixRotateXYZ(rotation);
UpdateCamera(ref camera, CameraMode.Custom);
//----------------------------------------------------------------------------------
// Draw
@ -131,11 +148,11 @@ public class SimpleMask
DrawModel(model1, new Vector3(0.5f, 0, 0), 1, Color.White);
DrawModelEx(model2, new Vector3(-.5f, 0, 0), new Vector3(1, 1, 0), 50, new Vector3(1, 1, 1), Color.White);
DrawModel(model3, new Vector3(0, 0, -1.5f), 1, Color.White);
DrawGrid(10, 1.0f);
DrawGrid(10, 1.0f); // Draw a grid
EndMode3D();
string frameText = $"Frame: {framesCounter}";
var frameText = $"Frame: {framesCounter}";
DrawRectangle(16, 698, MeasureText(frameText, 20) + 8, 42, Color.Blue);
DrawText(frameText, 20, 700, 20, Color.White);
@ -145,18 +162,42 @@ public class SimpleMask
//----------------------------------------------------------------------------------
}
// De-Initialization
//--------------------------------------------------------------------------------------
public void Unload()
{
UnloadModel(model1);
UnloadModel(model2);
UnloadModel(model3);
UnloadTexture(texDiffuse);
UnloadTexture(texMask);
UnloadTexture(texDiffuse); // Unload default diffuse texture
UnloadTexture(texMask); // Unload texture mask
UnloadShader(shader);
UnloadShader(shader); // Unload shader
}
CloseWindow();
public static int Main()
{
// Initialization
//--------------------------------------------------------------------------------------
InitWindow(screenWidth, screenHeight, "raylib [shaders] example - simple mask");
DisableCursor(); // Limit cursor to relative movement inside the window
SetTargetFPS(60); // Set to run at 60 frames-per-second
//--------------------------------------------------------------------------------------
var game = new SimpleMask();
game.Init();
// Main game loop
while (!WindowShouldClose()) // Detect window close button or ESC key
{
game.Update();
}
game.Unload();
// De-Initialization
//--------------------------------------------------------------------------------------
CloseWindow(); // Close window and OpenGL context
//--------------------------------------------------------------------------------------
return 0;

View file

@ -1,29 +1,32 @@
/*******************************************************************************************
*
* raylib [shaders] example - Simple shader mask
* raylib [shaders] example - spotlight rendering
*
* This example has been created using raylib 2.5 (www.raylib.com)
* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details)
* Example complexity rating: [] 2/4
*
* Example contributed by Chris Camacho (@chriscamacho - http://bedroomcoders.co.uk/)
* and reviewed by Ramon Santamaria (@raysan5)
* Example originally created with raylib 2.5, last time updated with raylib 3.7
*
* Copyright (c) 2019 Chris Camacho (@chriscamacho) and Ramon Santamaria (@raysan5)
* Example contributed by Chris Camacho (@chriscamacho) and reviewed by Ramon Santamaria (@raysan5)
*
* Example licensed under an unmodified zlib/libpng license, which is an OSI-certified,
* BSD-like license that allows static linking with closed source software
*
* Copyright (c) 2019-2025 Chris Camacho (@chriscamacho) and Ramon Santamaria (@raysan5)
*
********************************************************************************************
*
* The shader makes alpha holes in the forground to give the apearance of a top
* The shader makes alpha holes in the forground to give the appearance of a top
* down look at a spotlight casting a pool of light...
*
* The right hand side of the screen there is just enough light to see whats
* going on without the spot light, great for a stealth type game where you
* have to avoid the spotlights.
* have to avoid the spotlights
*
* The left hand side of the screen is in pitch dark except for where the spotlights are.
* The left hand side of the screen is in pitch dark except for where the spotlights are
*
* Although this example doesn't scale like the letterbox example, you could integrate
* the two techniques, but by scaling the actual colour of the render texture rather
* than using alpha as a mask.
* than using alpha as a mask
*
********************************************************************************************/
@ -33,14 +36,29 @@ using static Raylib_cs.Raylib;
namespace Examples.Shaders;
public class Spotlight
public class Spotlight : IExample
{
private const int screenWidth = 800;
private const int screenHeight = 450;
#if BROWSER
const int GlslVersion = 100; // WebGL1 needs GLSL ES 100
#else
private const int GlslVersion = 330;
#endif
// NOTE: It must be the same as define in shader
const int MaxSpots = 3;
const int MaxStars = 400;
private const int MaxSpots = 3;
private const int MaxStars = 400;
public string Name => "Shaders / Spotlight";
public string Title => "raylib [shaders] example - spotlight rendering";
public bool CursorHidden => true;
// Spot data
struct Spot
private struct Spot
{
public Vector2 pos;
public Vector2 vel;
@ -54,53 +72,51 @@ public class Spotlight
}
// Stars in the star field have a position and velocity
struct Star
private struct Star
{
public Vector2 pos;
public Vector2 vel;
}
public static int Main()
private Texture2D texRay;
private Star[] stars;
private int frameCounter;
private Shader shdrSpot;
private Spot[] spots;
public void Init()
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
texRay = LoadTexture("resources/raysan.png");
InitWindow(screenWidth, screenHeight, "raylib - shader spotlight");
HideCursor();
stars = new Star[MaxStars];
Texture2D texRay = LoadTexture("resources/raysan.png");
Star[] stars = new Star[MaxStars];
for (int n = 0; n < MaxStars; n++)
for (var n = 0; n < MaxStars; n++)
{
ResetStar(ref stars[n]);
}
// Progress all the stars on, so they don't all start in the centre
for (int m = 0; m < screenWidth / 2.0; m++)
for (var m = 0; m < screenWidth / 2.0; m++)
{
for (int n = 0; n < MaxStars; n++)
for (var n = 0; n < MaxStars; n++)
{
UpdateStar(ref stars[n]);
}
}
int frameCounter = 0;
frameCounter = 0;
// Use default vert shader
Shader shdrSpot = LoadShader(null, "resources/shaders/glsl330/spotlight.fs");
shdrSpot = LoadShader(null, $"resources/shaders/glsl{GlslVersion}/spotlight.fs");
// Get the locations of spots in the shader
Spot[] spots = new Spot[MaxSpots];
spots = new Spot[MaxSpots];
for (int i = 0; i < MaxSpots; i++)
for (var i = 0; i < MaxSpots; i++)
{
string posName = $"spots[{i}].pos";
string innerName = $"spots[{i}].inner";
string radiusName = $"spots[{i}].radius";
var posName = $"spots[{i}].pos";
var innerName = $"spots[{i}].inner";
var radiusName = $"spots[{i}].radius";
spots[i].posLoc = GetShaderLocation(shdrSpot, posName);
spots[i].innerLoc = GetShaderLocation(shdrSpot, innerName);
@ -108,14 +124,14 @@ public class Spotlight
}
// Tell the shader how wide the screen is so we can have
// a pitch Color.black half and a dimly lit half.
int wLoc = GetShaderLocation(shdrSpot, "screenWidth");
float sw = (float)GetScreenWidth();
// a pitch black half and a dimly lit half
var wLoc = GetShaderLocation(shdrSpot, "screenWidth");
var sw = (float)GetScreenWidth();
Raylib.SetShaderValue(shdrSpot, wLoc, sw, ShaderUniformDataType.Float);
// Randomise the locations and velocities of the spotlights
// and initialise the shader locations
for (int i = 0; i < MaxSpots; i++)
// Randomize the locations and velocities of the spotlights
// and initialize the shader locations
for (var i = 0; i < MaxSpots; i++)
{
spots[i].pos.X = GetRandomValue(64, screenWidth - 64);
spots[i].pos.Y = GetRandomValue(64, screenHeight - 64);
@ -123,8 +139,8 @@ public class Spotlight
while ((MathF.Abs(spots[i].vel.X) + MathF.Abs(spots[i].vel.Y)) < 2)
{
spots[i].vel.X = GetRandomValue(-40, 40) / 10.0f;
spots[i].vel.Y = GetRandomValue(-40, 40) / 10.0f;
spots[i].vel.X = GetRandomValue(-400, 40) / 25.0f;
spots[i].vel.Y = GetRandomValue(-400, 40) / 25.0f;
}
spots[i].inner = 28.0f * (i + 1);
@ -149,29 +165,26 @@ public class Spotlight
ShaderUniformDataType.Float
);
}
}
SetTargetFPS(60);
//--------------------------------------------------------------------------------------
// Main game loop
while (!WindowShouldClose())
public void Update()
{
// Update
//----------------------------------------------------------------------------------
frameCounter++;
// Move the stars, resetting them if the go offscreen
for (int n = 0; n < MaxStars; n++)
for (var n = 0; n < MaxStars; n++)
{
UpdateStar(ref stars[n]);
}
// Update the spots, send them to the shader
for (int i = 0; i < MaxSpots; i++)
for (var i = 0; i < MaxSpots; i++)
{
if (i == 0)
{
Vector2 mp = GetMousePosition();
var mp = GetMousePosition();
spots[i].pos.X = mp.X;
spots[i].pos.Y = screenHeight - mp.Y;
}
@ -215,13 +228,13 @@ public class Spotlight
ClearBackground(Color.DarkBlue);
// Draw stars and bobs
for (int n = 0; n < MaxStars; n++)
for (var n = 0; n < MaxStars; n++)
{
// MathF.Single pixel is just too small these days!
// Single pixel is just too small these days!
DrawRectangle((int)stars[n].pos.X, (int)stars[n].pos.Y, 2, 2, Color.White);
}
for (int i = 0; i < 16; i++)
for (var i = 0; i < 16; i++)
{
DrawTexture(
texRay,
@ -242,25 +255,20 @@ public class Spotlight
DrawFPS(10, 10);
DrawText("Move the mouse!", 10, 30, 20, Color.Green);
DrawText("Pitch Color.Black", (int)(screenWidth * 0.2f), screenHeight / 2, 20, Color.Green);
DrawText("Pitch Black", (int)(screenWidth * 0.2f), screenHeight / 2, 20, Color.Green);
DrawText("Dark", (int)(screenWidth * 0.66f), screenHeight / 2, 20, Color.Green);
EndDrawing();
//----------------------------------------------------------------------------------
}
// De-Initialization
//--------------------------------------------------------------------------------------
public void Unload()
{
UnloadTexture(texRay);
UnloadShader(shdrSpot);
CloseWindow();
//--------------------------------------------------------------------------------------
return 0;
}
static void ResetStar(ref Star s)
private static void ResetStar(ref Star s)
{
s.pos = new Vector2(GetScreenWidth() / 2.0f, GetScreenHeight() / 2.0f);
@ -270,10 +278,10 @@ public class Spotlight
s.vel.Y = (float)GetRandomValue(-1000, 1000) / 100.0f;
} while (!((MathF.Abs(s.vel.X) + (MathF.Abs(s.vel.Y)) > 1)));
s.pos += s.pos + (s.vel * new Vector2(8.0f, 8.0f));
s.pos += s.vel * new Vector2(8.0f, 8.0f);
}
static void UpdateStar(ref Star s)
private static void UpdateStar(ref Star s)
{
s.pos += s.vel;
@ -283,4 +291,33 @@ public class Spotlight
ResetStar(ref s);
}
}
public static int Main()
{
// Initialization
//--------------------------------------------------------------------------------------
InitWindow(screenWidth, screenHeight, "raylib [shaders] example - spotlight rendering");
HideCursor();
SetTargetFPS(60); // Set to run at 60 frames-per-second
//--------------------------------------------------------------------------------------
var game = new Spotlight();
game.Init();
// Main game loop
while (!WindowShouldClose()) // Detect window close button or ESC key
{
game.Update();
}
game.Unload();
// De-Initialization
//--------------------------------------------------------------------------------------
CloseWindow();
//--------------------------------------------------------------------------------------
return 0;
}
}

View file

@ -1,15 +1,17 @@
/*******************************************************************************************
*
* raylib [textures] example - Texture drawing
* raylib [shaders] example - texture rendering
*
* This example illustrates how to draw on a blank texture using a shader
* Example complexity rating: [] 2/4
*
* This example has been created using raylib 2.0 (www.raylib.com)
* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details)
* Example originally created with raylib 2.0, last time updated with raylib 3.7
*
* Example contributed by Michał Ciesielski and reviewed by Ramon Santamaria (@raysan5)
* Example contributed by Michał Ciesielski (@ciessielski) and reviewed by Ramon Santamaria (@raysan5)
*
* Copyright (c) 2019 Michał Ciesielski and Ramon Santamaria (@raysan5)
* Example licensed under an unmodified zlib/libpng license, which is an OSI-certified,
* BSD-like license that allows static linking with closed source software
*
* Copyright (c) 2019-2025 Michał Ciesielski (@ciessielski) and Ramon Santamaria (@raysan5)
*
********************************************************************************************/
@ -17,36 +19,41 @@ using static Raylib_cs.Raylib;
namespace Examples.Shaders;
public class TextureDrawing
public class TextureDrawing : IExample
{
const int GlslVersion = 330;
private const int screenWidth = 800;
private const int screenHeight = 450;
public static int Main()
#if BROWSER
const int GlslVersion = 100; // WebGL1 needs GLSL ES 100
#else
private const int GlslVersion = 330;
#endif
public string Name => "Shaders / Texture Drawing";
public string Title => "raylib [shaders] example - texture rendering";
private Texture2D texture;
private Shader shader;
private float time;
private int timeLoc;
public void Init()
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [shaders] example - texture drawing");
// Load blank texture to fill on shader
Image imBlank = GenImageColor(1024, 1024, Color.Blank);
Texture2D texture = LoadTextureFromImage(imBlank);
var imBlank = GenImageColor(1024, 1024, Color.Blank);
texture = LoadTextureFromImage(imBlank); // Load blank texture to fill on shader
UnloadImage(imBlank);
// NOTE: Using GLSL 330 shader version, on OpenGL ES 2.0 use GLSL 100 shader version
Shader shader = LoadShader(null, $"resources/shaders/glsl{GlslVersion}/cubes_panning.fs");
shader = LoadShader(null, $"resources/shaders/glsl{GlslVersion}/cubes_panning.fs");
float time = 0.0f;
int timeLoc = GetShaderLocation(shader, "uTime");
time = 0.0f;
timeLoc = GetShaderLocation(shader, "uTime");
Raylib.SetShaderValue(shader, timeLoc, time, ShaderUniformDataType.Float);
}
SetTargetFPS(60);
//--------------------------------------------------------------------------------------
// Main game loop
while (!WindowShouldClose())
public void Update()
{
// Update
//----------------------------------------------------------------------------------
@ -59,14 +66,9 @@ public class TextureDrawing
BeginDrawing();
ClearBackground(Color.RayWhite);
// Enable our custom shader for next shapes/textures drawings
BeginShaderMode(shader);
// Drawing blank texture, all magic happens on shader
DrawTexture(texture, 0, 0, Color.White);
// Disable our custom shader, return to default shader
EndShaderMode();
BeginShaderMode(shader); // Enable our custom shader for next shapes/textures drawings
DrawTexture(texture, 0, 0, Color.White); // Drawing BLANK texture, all rendering magic happens on shader
EndShaderMode(); // Disable our custom shader, return to default shader
DrawText("BACKGROUND is PAINTED and ANIMATED on SHADER!", 10, 10, 20, Color.Maroon);
@ -74,11 +76,35 @@ public class TextureDrawing
//----------------------------------------------------------------------------------
}
public void Unload()
{
UnloadShader(shader);
UnloadTexture(texture);
}
public static int Main()
{
// Initialization
//--------------------------------------------------------------------------------------
InitWindow(screenWidth, screenHeight, "raylib [shaders] example - texture rendering");
SetTargetFPS(60); // Set our game to run at 60 frames-per-second
//--------------------------------------------------------------------------------------
var game = new TextureDrawing();
game.Init();
// Main game loop
while (!WindowShouldClose()) // Detect window close button or ESC key
{
game.Update();
}
game.Unload();
// De-Initialization
//--------------------------------------------------------------------------------------
UnloadShader(shader);
CloseWindow();
CloseWindow(); // Close window and OpenGL context
//--------------------------------------------------------------------------------------
return 0;

View file

@ -1,15 +1,20 @@
/*******************************************************************************************
*
* raylib [textures] example - Texture drawing
* raylib [shaders] example - texture outline
*
* This example illustrates how to draw on a blank texture using a shader
* Example complexity rating: [] 3/4
*
* This example has been created using raylib 2.0 (www.raylib.com)
* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details)
* NOTE: This example requires raylib OpenGL 3.3 or ES2 versions for shaders support,
* OpenGL 1.1 does not support shaders, recompile raylib to OpenGL 3.3 version
*
* Example contributed by Michał Ciesielski and reviewed by Ramon Santamaria (@raysan5)
* Example originally created with raylib 4.0, last time updated with raylib 4.0
*
* Copyright (c) 2019 Michał Ciesielski and Ramon Santamaria (@raysan5)
* Example contributed by Serenity Skiff (@GoldenThumbs) and reviewed by Ramon Santamaria (@raysan5)
*
* Example licensed under an unmodified zlib/libpng license, which is an OSI-certified,
* BSD-like license that allows static linking with closed source software
*
* Copyright (c) 2021-2025 Serenity Skiff (@GoldenThumbs) and Ramon Santamaria (@raysan5)
*
********************************************************************************************/
@ -17,32 +22,41 @@ using static Raylib_cs.Raylib;
namespace Examples.Shaders;
public class TextureOutline
public class TextureOutline : IExample
{
const int GLSL_VERSION = 330;
private const int screenWidth = 800;
private const int screenHeight = 450;
public static int Main()
#if BROWSER
const int GlslVersion = 100; // WebGL1 needs GLSL ES 100
#else
private const int GlslVersion = 330;
#endif
public string Name => "Shaders / Texture Outline";
public string Title => "raylib [shaders] example - texture outline";
private Texture2D texture;
private Shader shdrOutline;
private float outlineSize;
private int outlineSizeLoc;
public void Init()
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
texture = LoadTexture("resources/fudesumi.png");
shdrOutline = LoadShader(null, $"resources/shaders/glsl{GlslVersion}/outline.fs");
InitWindow(screenWidth, screenHeight, "raylib [shaders] example - Apply an outline to a texture");
outlineSize = 2.0f;
Texture2D texture = LoadTexture("resources/fudesumi.png");
Shader shdrOutline = LoadShader(null, $"resources/shaders/glsl{GLSL_VERSION}/outline.fs");
float outlineSize = 2.0f;
// Normalized red color
float[] outlineColor = new[] { 1.0f, 0.0f, 0.0f, 1.0f };
// Normalized RED color
var outlineColor = new[] { 1.0f, 0.0f, 0.0f, 1.0f };
float[] textureSize = { (float)texture.Width, (float)texture.Height };
// Get shader locations
int outlineSizeLoc = GetShaderLocation(shdrOutline, "outlineSize");
int outlineColorLoc = GetShaderLocation(shdrOutline, "outlineColor");
int textureSizeLoc = GetShaderLocation(shdrOutline, "textureSize");
outlineSizeLoc = GetShaderLocation(shdrOutline, "outlineSize");
var outlineColorLoc = GetShaderLocation(shdrOutline, "outlineColor");
var textureSizeLoc = GetShaderLocation(shdrOutline, "textureSize");
// Set shader values (they can be changed later)
Raylib.SetShaderValue(
@ -63,12 +77,9 @@ public class TextureOutline
textureSize,
ShaderUniformDataType.Vec2
);
}
SetTargetFPS(60);
//--------------------------------------------------------------------------------------
// Main game loop
while (!WindowShouldClose())
public void Update()
{
// Update
//----------------------------------------------------------------------------------
@ -97,8 +108,8 @@ public class TextureOutline
EndShaderMode();
DrawText("Shader-based\ntexture\noutline", 10, 10, 20, Color.Gray);
DrawText($"Outline size: {outlineSize} px", 10, 120, 20, Color.Maroon);
DrawText("Scroll mouse wheel to\nchange outline size", 10, 72, 20, Color.Gray);
DrawText($"Outline size: {(int)outlineSize} px", 10, 120, 20, Color.Maroon);
DrawFPS(710, 10);
@ -106,12 +117,35 @@ public class TextureOutline
//----------------------------------------------------------------------------------
}
// De-Initialization
//--------------------------------------------------------------------------------------
public void Unload()
{
UnloadTexture(texture);
UnloadShader(shdrOutline);
}
CloseWindow();
public static int Main()
{
// Initialization
//--------------------------------------------------------------------------------------
InitWindow(screenWidth, screenHeight, "raylib [shaders] example - texture outline");
SetTargetFPS(60); // Set our game to run at 60 frames-per-second
//--------------------------------------------------------------------------------------
var game = new TextureOutline();
game.Init();
// Main game loop
while (!WindowShouldClose()) // Detect window close button or ESC key
{
game.Update();
}
game.Unload();
// De-Initialization
//--------------------------------------------------------------------------------------
CloseWindow(); // Close window and OpenGL context
//--------------------------------------------------------------------------------------
return 0;

View file

@ -1,20 +1,24 @@
/*******************************************************************************************
*
* raylib [shaders] example - Texture Waves
* raylib [shaders] example - texture waves
*
* Example complexity rating: [] 2/4
*
* NOTE: This example requires raylib OpenGL 3.3 or ES2 versions for shaders support,
* OpenGL 1.1 does not support shaders, recompile raylib to OpenGL 3.3 version.
* OpenGL 1.1 does not support shaders, recompile raylib to OpenGL 3.3 version
*
* NOTE: Shaders used in this example are #version 330 (OpenGL 3.3), to test this example
* on OpenGL ES 2.0 platforms (Android, Raspberry Pi, HTML5), use #version 100 shaders
* raylib comes with shaders ready for both versions, check raylib/shaders install folder
*
* This example has been created using raylib 2.5 (www.raylib.com)
* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details)
* Example originally created with raylib 2.5, last time updated with raylib 3.7
*
* Example contributed by Anata (@anatagawa) and reviewed by Ramon Santamaria (@raysan5)
*
* Copyright (c) 2019 Anata (@anatagawa) and Ramon Santamaria (@raysan5)
* Example licensed under an unmodified zlib/libpng license, which is an OSI-certified,
* BSD-like license that allows static linking with closed source software
*
* Copyright (c) 2019-2025 Anata (@anatagawa) and Ramon Santamaria (@raysan5)
*
********************************************************************************************/
@ -22,40 +26,49 @@ using static Raylib_cs.Raylib;
namespace Examples.Shaders;
public class TextureWaves
public class TextureWaves : IExample
{
const int GlslVersion = 330;
private const int screenWidth = 800;
private const int screenHeight = 450;
public static int Main()
#if BROWSER
const int GlslVersion = 100; // WebGL1 needs GLSL ES 100
#else
private const int GlslVersion = 330;
#endif
public string Name => "Shaders / Texture Waves";
public string Title => "raylib [shaders] example - texture waves";
private Texture2D texture;
private Shader shader;
private int secondsLoc;
private float seconds;
public void Init()
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [shaders] example - texture waves");
// Load texture texture to apply shaders
Texture2D texture = LoadTexture("resources/space.png");
texture = LoadTexture("resources/space.png");
// Load shader and setup location points and values
Shader shader = LoadShader(null, $"resources/shaders/glsl{GlslVersion}/wave.fs");
shader = LoadShader(null, $"resources/shaders/glsl{GlslVersion}/wave.fs");
int secondsLoc = GetShaderLocation(shader, "secondes");
int freqXLoc = GetShaderLocation(shader, "freqX");
int freqYLoc = GetShaderLocation(shader, "freqY");
int ampXLoc = GetShaderLocation(shader, "ampX");
int ampYLoc = GetShaderLocation(shader, "ampY");
int speedXLoc = GetShaderLocation(shader, "speedX");
int speedYLoc = GetShaderLocation(shader, "speedY");
secondsLoc = GetShaderLocation(shader, "seconds");
var freqXLoc = GetShaderLocation(shader, "freqX");
var freqYLoc = GetShaderLocation(shader, "freqY");
var ampXLoc = GetShaderLocation(shader, "ampX");
var ampYLoc = GetShaderLocation(shader, "ampY");
var speedXLoc = GetShaderLocation(shader, "speedX");
var speedYLoc = GetShaderLocation(shader, "speedY");
// Shader uniform values that can be updated at any time
float freqX = 25.0f;
float freqY = 25.0f;
float ampX = 5.0f;
float ampY = 5.0f;
float speedX = 8.0f;
float speedY = 8.0f;
var freqX = 25.0f;
var freqY = 25.0f;
var ampX = 5.0f;
var ampY = 5.0f;
var speedX = 8.0f;
var speedY = 8.0f;
float[] screenSize = { (float)GetScreenWidth(), (float)GetScreenHeight() };
Raylib.SetShaderValue(
@ -71,13 +84,10 @@ public class TextureWaves
Raylib.SetShaderValue(shader, speedXLoc, speedX, ShaderUniformDataType.Float);
Raylib.SetShaderValue(shader, speedYLoc, speedY, ShaderUniformDataType.Float);
float seconds = 0.0f;
seconds = 0.0f;
}
SetTargetFPS(60);
//--------------------------------------------------------------------------------------
// Main game loop
while (!WindowShouldClose())
public void Update()
{
// Update
//----------------------------------------------------------------------------------
@ -102,12 +112,35 @@ public class TextureWaves
//----------------------------------------------------------------------------------
}
public void Unload()
{
UnloadShader(shader); // Unload shader
UnloadTexture(texture); // Unload texture
}
public static int Main()
{
// Initialization
//--------------------------------------------------------------------------------------
InitWindow(screenWidth, screenHeight, "raylib [shaders] example - texture waves");
SetTargetFPS(60); // Set our game to run at 60 frames-per-second
//--------------------------------------------------------------------------------------
var game = new TextureWaves();
game.Init();
// Main game loop
while (!WindowShouldClose()) // Detect window close button or ESC key
{
game.Update();
}
game.Unload();
// De-Initialization
//--------------------------------------------------------------------------------------
UnloadShader(shader);
UnloadTexture(texture);
CloseWindow();
CloseWindow(); // Close window and OpenGL context
//--------------------------------------------------------------------------------------
return 0;

View file

@ -1,6 +1,8 @@
/*******************************************************************************************
*
* raylib [shaders] example - Depth buffer writing
* raylib [shaders] example - depth writing
*
* Example complexity rating: [] 2/4
*
* Example originally created with raylib 4.2, last time updated with raylib 4.2
*
@ -9,7 +11,7 @@
* Example licensed under an unmodified zlib/libpng license, which is an OSI-certified,
* BSD-like license that allows static linking with closed source software
*
* Copyright (c) 2022-2023 Buğra Alptekin Sarı (@BugraAlptekinSari)
* Copyright (c) 2022-2025 Buğra Alptekin Sarı (@BugraAlptekinSari)
*
********************************************************************************************/
@ -18,38 +20,44 @@ using static Raylib_cs.Raylib;
namespace Examples.Shaders;
public class WriteDepth
public class WriteDepth : IExample
{
const int GLSL_VERSION = 330;
private const int screenWidth = 800;
private const int screenHeight = 450;
public static int Main()
#if BROWSER
const int GlslVersion = 100; // WebGL1 needs GLSL ES 100
#else
private const int GlslVersion = 330;
#endif
public string Name => "Shaders / Write Depth";
public string Title => "raylib [shaders] example - depth writing";
private Camera3D camera;
private RenderTexture2D target;
private Shader shader;
public void Init()
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [shaders] example - write depth buffer");
// The shader inverts the depth buffer by writing into it by `gl_FragDepth = 1 - gl_FragCoord.z;`
Shader shader = LoadShader(null, $"resources/shaders/glsl{GLSL_VERSION}/write_depth.fs");
// Use customized function to create writable depth texture buffer
RenderTexture2D target = LoadRenderTextureDepthTex(screenWidth, screenHeight);
// Define the camera to look into our 3d world
Camera3D camera;
camera.Position = new Vector3(2.0f, 2.0f, 3.0f);
camera.Target = new Vector3(0.0f, 0.5f, 0.0f);
camera.Up = new Vector3(0.0f, 1.0f, 0.0f);
camera.FovY = 45.0f;
camera.Projection = CameraProjection.Perspective;
camera = new();
camera.Position = new Vector3(2.0f, 2.0f, 3.0f); // Camera position
camera.Target = new Vector3(0.0f, 0.5f, 0.0f); // Camera looking at point
camera.Up = new Vector3(0.0f, 1.0f, 0.0f); // Camera up vector (rotation towards target)
camera.FovY = 45.0f; // Camera field-of-view Y
camera.Projection = CameraProjection.Perspective; // Camera projection type
SetTargetFPS(60);
//--------------------------------------------------------------------------------------
// Load custom render texture with writable depth texture buffer
target = LoadRenderTextureDepthTex(screenWidth, screenHeight);
// Main game loop
while (!WindowShouldClose())
// Load depth writing shader
// NOTE: The shader inverts the depth buffer by writing into it by `gl_FragDepth = 1 - gl_FragCoord.z;`
shader = LoadShader(null, $"resources/shaders/glsl{GlslVersion}/depth_write.fs");
}
public void Update()
{
// Update
//----------------------------------------------------------------------------------
@ -59,7 +67,7 @@ public class WriteDepth
// Draw
//----------------------------------------------------------------------------------
// Draw into our custom render texture (framebuffer)
// Draw into our custom render texture
BeginTextureMode(target);
ClearBackground(Color.White);
@ -76,7 +84,7 @@ public class WriteDepth
EndMode3D();
EndTextureMode();
// Draw custom render texture
// Draw into screen our custom render texture
BeginDrawing();
ClearBackground(Color.RayWhite);
@ -92,12 +100,35 @@ public class WriteDepth
//----------------------------------------------------------------------------------
}
// De-Initialization
//--------------------------------------------------------------------------------------
public void Unload()
{
UnloadRenderTextureDepthTex(target);
UnloadShader(shader);
}
CloseWindow();
public static int Main()
{
// Initialization
//--------------------------------------------------------------------------------------
InitWindow(screenWidth, screenHeight, "raylib [shaders] example - depth writing");
SetTargetFPS(60); // Set our game to run at 60 frames-per-second
//--------------------------------------------------------------------------------------
var game = new WriteDepth();
game.Init();
// Main game loop
while (!WindowShouldClose()) // Detect window close button or ESC key
{
game.Update();
}
game.Unload();
// De-Initialization
//--------------------------------------------------------------------------------------
CloseWindow(); // Close window and OpenGL context
//--------------------------------------------------------------------------------------
return 0;
@ -152,7 +183,7 @@ public class WriteDepth
);
// Check if fbo is complete with attachments (valid)
if (Rlgl.FramebufferComplete(target.Id))
if (Rlgl.FramebufferComplete(target.Id) != 0)
{
TraceLog(TraceLogLevel.Info, $"FBO: [ID {target.Id}] Framebuffer object created successfully");
}

View file

@ -1,11 +1,15 @@
/*******************************************************************************************
*
* raylib [shapes] example - Draw basic shapes 2d (rectangle, circle, line...)
* raylib [shapes] example - basic shapes
*
* 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)
* Example complexity rating: [] 1/4
*
* Copyright (c) 2014 Ramon Santamaria (@raysan5)
* Example originally created with raylib 1.0, last time updated with raylib 4.2
*
* Example licensed under an unmodified zlib/libpng license, which is an OSI-certified,
* BSD-like license that allows static linking with closed source software
*
* Copyright (c) 2014-2025 Ramon Santamaria (@raysan5)
*
********************************************************************************************/
@ -14,26 +18,27 @@ using static Raylib_cs.Raylib;
namespace Examples.Shapes;
public class BasicShapes
public partial class BasicShapes : IExample
{
public static int Main()
private const int screenWidth = 800;
private const int screenHeight = 450;
public string Name => "Shapes / Basic Shapes";
public string Title => "raylib [shapes] example - basic shapes";
private float rotation;
public void Init()
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
rotation = 0.0f;
}
InitWindow(screenWidth, screenHeight, "raylib [shapes] example - basic shapes drawing");
SetTargetFPS(60);
//--------------------------------------------------------------------------------------
// Main game loop
while (!WindowShouldClose())
public void Update()
{
// Update
//----------------------------------------------------------------------------------
// TODO: Update your variables here
rotation += 0.2f;
//----------------------------------------------------------------------------------
// Draw
@ -43,37 +48,71 @@ public class BasicShapes
DrawText("some basic shapes available on raylib", 20, 20, 20, Color.DarkGray);
DrawLine(18, 42, screenWidth - 18, 42, Color.Black);
DrawCircle(screenWidth / 4, 120, 35, Color.DarkBlue);
DrawCircleGradient(new Vector2(screenWidth / 4, 220), 60, Color.Green, Color.SkyBlue);
DrawCircleLines(screenWidth / 4, 340, 80, Color.DarkBlue);
// Circle shapes and lines
DrawCircle(screenWidth / 5, 120, 35, Color.DarkBlue);
DrawCircleGradient(new Vector2(screenWidth / 5.0f, 220.0f), 60, Color.Green, Color.SkyBlue);
DrawCircleLines(screenWidth / 5, 340, 80, Color.DarkBlue);
DrawEllipse(screenWidth / 5, 120, 25, 20, Color.Yellow);
DrawEllipseLines(screenWidth / 5, 120, 30, 25, Color.Yellow);
// Rectangle shapes and lines
DrawRectangle(screenWidth / 4 * 2 - 60, 100, 120, 60, Color.Red);
DrawRectangleGradientH(screenWidth / 4 * 2 - 90, 170, 180, 130, Color.Maroon, Color.Gold);
DrawRectangleLines(screenWidth / 4 * 2 - 40, 320, 80, 60, Color.Orange);
DrawRectangleLines(screenWidth / 4 * 2 - 40, 320, 80, 60, Color.Orange); // NOTE: Uses QUADS internally, not lines
// Triangle shapes and lines
DrawTriangle(
new Vector2(screenWidth / 4 * 3, 80),
new Vector2(screenWidth / 4 * 3 - 60, 150),
new Vector2(screenWidth / 4 * 3 + 60, 150), Color.Violet
new Vector2(screenWidth / 4.0f * 3.0f, 80.0f),
new Vector2(screenWidth / 4.0f * 3.0f - 60.0f, 150.0f),
new Vector2(screenWidth / 4.0f * 3.0f + 60.0f, 150.0f), Color.Violet
);
DrawTriangleLines(
new Vector2(screenWidth / 4 * 3, 160),
new Vector2(screenWidth / 4 * 3 - 20, 230),
new Vector2(screenWidth / 4 * 3 + 20, 230), Color.DarkBlue
new Vector2(screenWidth / 4.0f * 3.0f, 160.0f),
new Vector2(screenWidth / 4.0f * 3.0f - 20.0f, 230.0f),
new Vector2(screenWidth / 4.0f * 3.0f + 20.0f, 230.0f), Color.DarkBlue
);
DrawPoly(new Vector2(screenWidth / 4 * 3, 320), 6, 80, 0, Color.Brown);
// Polygon shapes and lines
DrawPoly(new Vector2(screenWidth / 4.0f * 3, 330), 6, 80, rotation, Color.Brown);
DrawPolyLines(new Vector2(screenWidth / 4.0f * 3, 330), 6, 90, rotation, Color.Brown);
DrawPolyLinesEx(new Vector2(screenWidth / 4.0f * 3, 330), 6, 85, rotation, 6, Color.Beige);
// NOTE: We draw all LINES based shapes together to optimize internal drawing,
// this way, all LINES are rendered in a single draw pass
DrawLine(18, 42, screenWidth - 18, 42, Color.Black);
EndDrawing();
//----------------------------------------------------------------------------------
}
public void Unload()
{
}
public static int Main()
{
// Initialization
//--------------------------------------------------------------------------------------
InitWindow(screenWidth, screenHeight, "raylib [shapes] example - basic shapes");
SetTargetFPS(60); // Set our game to run at 60 frames-per-second
//--------------------------------------------------------------------------------------
var game = new BasicShapes();
game.Init();
// Main game loop
while (!WindowShouldClose()) // Detect window close button or ESC key
{
game.Update();
}
game.Unload();
// De-Initialization
//--------------------------------------------------------------------------------------
CloseWindow();
CloseWindow(); // Close window and OpenGL context
//--------------------------------------------------------------------------------------
return 0;

View file

@ -2,10 +2,16 @@
*
* raylib [shapes] example - bouncing ball
*
* 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)
* Example complexity rating: [] 1/4
*
* Copyright (c) 2013 Ramon Santamaria (@raysan5)
* Example originally created with raylib 2.5, last time updated with raylib 2.5
*
* Example contributed by Ramon Santamaria (@raysan5), reviewed by Jopestpe (@jopestpe)
*
* Example licensed under an unmodified zlib/libpng license, which is an OSI-certified,
* BSD-like license that allows static linking with closed source software
*
* Copyright (c) 2013-2025 Ramon Santamaria (@raysan5)
*
********************************************************************************************/
@ -14,32 +20,46 @@ using static Raylib_cs.Raylib;
namespace Examples.Shapes;
public class BouncingBall
public partial class BouncingBall : IExample
{
public static int Main()
private const int screenWidth = 800;
private const int screenHeight = 450;
public string Name => "Shapes / Bouncing Ball";
public string Title => "raylib [shapes] example - bouncing ball";
public ConfigFlags ConfigFlags => ConfigFlags.Msaa4xHint;
private Vector2 ballPosition;
private Vector2 ballSpeed;
private int ballRadius;
private float gravity;
private bool useGravity;
private bool pause;
private int framesCounter;
public void Init()
{
// Initialization
//---------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
ballPosition = new(GetScreenWidth() / 2.0f, GetScreenHeight() / 2.0f);
ballSpeed = new(5.0f, 4.0f);
ballRadius = 20;
gravity = 0.2f;
InitWindow(screenWidth, screenHeight, "raylib [shapes] example - bouncing ball");
useGravity = true;
pause = false;
framesCounter = 0;
}
Vector2 ballPosition = new(GetScreenWidth() / 2, GetScreenHeight() / 2);
Vector2 ballSpeed = new(5.0f, 4.0f);
int ballRadius = 20;
bool pause = false;
int framesCounter = 0;
SetTargetFPS(60);
//----------------------------------------------------------
// Main game loop
while (!WindowShouldClose())
public void Update()
{
// Update
//-----------------------------------------------------
if (IsKeyPressed(KeyboardKey.G))
{
useGravity = !useGravity;
}
if (IsKeyPressed(KeyboardKey.Space))
{
pause = !pause;
@ -50,6 +70,11 @@ public class BouncingBall
ballPosition.X += ballSpeed.X;
ballPosition.Y += ballSpeed.Y;
if (useGravity)
{
ballSpeed.Y += gravity;
}
// Check walls collision for bouncing
if ((ballPosition.X >= (GetScreenWidth() - ballRadius)) || (ballPosition.X <= ballRadius))
{
@ -57,12 +82,12 @@ public class BouncingBall
}
if ((ballPosition.Y >= (GetScreenHeight() - ballRadius)) || (ballPosition.Y <= ballRadius))
{
ballSpeed.Y *= -1.0f;
ballSpeed.Y *= -0.95f;
}
}
else
{
framesCounter += 1;
framesCounter++;
}
//-----------------------------------------------------
@ -71,26 +96,60 @@ public class BouncingBall
BeginDrawing();
ClearBackground(Color.RayWhite);
DrawCircleV(ballPosition, ballRadius, Color.Maroon);
DrawCircleV(ballPosition, (float)ballRadius, Color.Maroon);
DrawText("PRESS SPACE to PAUSE BALL MOVEMENT", 10, GetScreenHeight() - 25, 20, Color.LightGray);
if (useGravity)
{
DrawText("GRAVITY: ON (Press G to disable)", 10, GetScreenHeight() - 50, 20, Color.DarkGreen);
}
else
{
DrawText("GRAVITY: OFF (Press G to enable)", 10, GetScreenHeight() - 50, 20, Color.Red);
}
// On pause, we draw a blinking message
if (pause && ((framesCounter / 30) % 2) == 0)
if (pause && ((framesCounter / 30) % 2) != 0)
{
DrawText("PAUSED", 350, 200, 30, Color.Gray);
}
DrawFPS(10, 10);
EndDrawing();
//-----------------------------------------------------
}
public void Unload()
{
}
public static int Main()
{
// Initialization
//---------------------------------------------------------
SetConfigFlags(ConfigFlags.Msaa4xHint);
InitWindow(screenWidth, screenHeight, "raylib [shapes] example - bouncing ball");
SetTargetFPS(60); // Set our game to run at 60 frames-per-second
//----------------------------------------------------------
var game = new BouncingBall();
game.Init();
// Main game loop
while (!WindowShouldClose()) // Detect window close button or ESC key
{
game.Update();
}
game.Unload();
// De-Initialization
//---------------------------------------------------------
CloseWindow();
CloseWindow(); // Close window and OpenGL context
//----------------------------------------------------------
return 0;
}
}

View file

@ -2,10 +2,14 @@
*
* raylib [shapes] example - collision area
*
* This example has been created using raylib 2.5 (www.raylib.com)
* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details)
* Example complexity rating: [] 2/4
*
* Copyright (c) 2013-2019 Ramon Santamaria (@raysan5)
* Example originally created with raylib 2.5, last time updated with raylib 2.5
*
* Example licensed under an unmodified zlib/libpng license, which is an OSI-certified,
* BSD-like license that allows static linking with closed source software
*
* Copyright (c) 2013-2025 Ramon Santamaria (@raysan5)
*
********************************************************************************************/
@ -13,36 +17,41 @@ using static Raylib_cs.Raylib;
namespace Examples.Shapes;
public class CollisionArea
public partial class CollisionArea : IExample
{
public static int Main()
private const int screenWidth = 800;
private const int screenHeight = 450;
public string Name => "Shapes / Collision Area";
public string Title => "raylib [shapes] example - collision area";
private Rectangle boxA;
private int boxASpeedX;
private Rectangle boxB;
private Rectangle boxCollision;
private int screenUpperLimit;
private bool pause;
private bool collision;
public void Init()
{
// Initialization
//---------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [shapes] example - collision area");
// Box A: Moving box
Rectangle boxA = new(10, GetScreenHeight() / 2 - 50, 200, 100);
int boxASpeedX = 4;
boxA = new(10, GetScreenHeight() / 2.0f - 50, 200, 100);
boxASpeedX = 4;
// Box B: Mouse moved box
Rectangle boxB = new(GetScreenWidth() / 2 - 30, GetScreenHeight() / 2 - 30, 60, 60);
Rectangle boxCollision = new();
boxB = new(GetScreenWidth() / 2.0f - 30, GetScreenHeight() / 2.0f - 30, 60, 60);
int screenUpperLimit = 40;
boxCollision = new(); // Collision rectangle
// Movement pause
bool pause = false;
bool collision = false;
screenUpperLimit = 40; // Top menu limits
SetTargetFPS(60);
//----------------------------------------------------------
pause = false; // Movement pause
collision = false; // Collision detection
}
// Main game loop
while (!WindowShouldClose())
public void Update()
{
// Update
//-----------------------------------------------------
@ -113,24 +122,51 @@ public class CollisionArea
DrawRectangleRec(boxCollision, Color.Lime);
// Draw collision message
int cx = GetScreenWidth() / 2 - MeasureText("COLLISION!", 20) / 2;
int cy = screenUpperLimit / 2 - 10;
var cx = GetScreenWidth() / 2 - MeasureText("COLLISION!", 20) / 2;
var cy = screenUpperLimit / 2 - 10;
DrawText("COLLISION!", cx, cy, 20, Color.Black);
// Draw collision area
string text = $"Collision Area: {(int)boxCollision.Width * (int)boxCollision.Height}";
var text = $"Collision Area: {(int)boxCollision.Width * (int)boxCollision.Height}";
DrawText(text, GetScreenWidth() / 2 - 100, screenUpperLimit + 10, 20, Color.Black);
}
// Draw help instructions
DrawText("Press SPACE to PAUSE/RESUME", 20, screenHeight - 35, 20, Color.LightGray);
DrawFPS(10, 10);
EndDrawing();
//-----------------------------------------------------
}
public void Unload()
{
}
public static int Main()
{
// Initialization
//---------------------------------------------------------
InitWindow(screenWidth, screenHeight, "raylib [shapes] example - collision area");
SetTargetFPS(60); // Set our game to run at 60 frames-per-second
//----------------------------------------------------------
var game = new CollisionArea();
game.Init();
// Main game loop
while (!WindowShouldClose()) // Detect window close button or ESC key
{
game.Update();
}
game.Unload();
// De-Initialization
//---------------------------------------------------------
CloseWindow();
CloseWindow(); // Close window and OpenGL context
//----------------------------------------------------------
return 0;

View file

@ -1,11 +1,15 @@
/*******************************************************************************************
*
* raylib [shapes] example - Colors palette
* raylib [shapes] example - colors palette
*
* This example has been created using raylib 2.5 (www.raylib.com)
* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details)
* Example complexity rating: [] 2/4
*
* Copyright (c) 2014-2019 Ramon Santamaria (@raysan5)
* Example originally created with raylib 1.0, last time updated with raylib 2.5
*
* Example licensed under an unmodified zlib/libpng license, which is an OSI-certified,
* BSD-like license that allows static linking with closed source software
*
* Copyright (c) 2014-2025 Ramon Santamaria (@raysan5)
*
********************************************************************************************/
@ -14,18 +18,26 @@ using static Raylib_cs.Raylib;
namespace Examples.Shapes;
public class ColorsPalette
public partial class ColorsPalette : IExample
{
public static int Main()
private const int screenWidth = 800;
private const int screenHeight = 450;
public const int MaxColorsCount = 21; // Number of colors available
public string Name => "Shapes / Colors Palette";
public string Title => "raylib [shapes] example - colors palette";
private Color[] colors;
private string[] colorNames;
private Rectangle[] colorsRecs;
private int[] colorState;
private Vector2 mousePoint;
public void Init()
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [shapes] example - colors palette");
Color[] colors = new[]
colors = new[]
{
Color.DarkGray,
Color.Maroon,
@ -50,7 +62,7 @@ public class ColorsPalette
Color.Beige
};
string[] colorNames = new[]
colorNames = new[]
{
"DARKGRAY",
"MAROON",
@ -76,10 +88,10 @@ public class ColorsPalette
};
// Rectangles array
Rectangle[] colorsRecs = new Rectangle[colors.Length];
colorsRecs = new Rectangle[colors.Length];
// Fills colorsRecs data (for every rectangle)
for (int i = 0; i < colorsRecs.Length; i++)
for (var i = 0; i < colorsRecs.Length; i++)
{
colorsRecs[i].X = 20 + 100 * (i % 7) + 10 * (i % 7);
colorsRecs[i].Y = 80 + 100 * (i / 7) + 10 * (i / 7);
@ -88,21 +100,18 @@ public class ColorsPalette
}
// Color state: 0-DEFAULT, 1-MOUSE_HOVER
int[] colorState = new int[colors.Length];
colorState = new int[colors.Length];
Vector2 mousePoint = new(0.0f, 0.0f);
mousePoint = new(0.0f, 0.0f);
}
SetTargetFPS(60);
//--------------------------------------------------------------------------------------
// Main game loop
while (!WindowShouldClose())
public void Update()
{
// Update
//----------------------------------------------------------------------------------
mousePoint = GetMousePosition();
for (int i = 0; i < colors.Length; i++)
for (var i = 0; i < colors.Length; i++)
{
if (CheckCollisionPointRec(mousePoint, colorsRecs[i]))
{
@ -129,10 +138,9 @@ public class ColorsPalette
Color.Gray
);
// Draw all rectangles
for (int i = 0; i < colorsRecs.Length; i++)
for (var i = 0; i < colorsRecs.Length; i++) // Draw all rectangles
{
DrawRectangleRec(colorsRecs[i], ColorAlpha(colors[i], colorState[i] != 0 ? 0.6f : 1.0f));
DrawRectangleRec(colorsRecs[i], Fade(colors[i], colorState[i] != 0 ? 0.6f : 1.0f));
if (IsKeyDown(KeyboardKey.Space) || colorState[i] != 0)
{
@ -143,7 +151,7 @@ public class ColorsPalette
20,
Color.Black
);
DrawRectangleLinesEx(colorsRecs[i], 6, ColorAlpha(Color.Black, 0.3f));
DrawRectangleLinesEx(colorsRecs[i], 6, Fade(Color.Black, 0.3f));
DrawText(
colorNames[i],
(int)(colorsRecs[i].X + colorsRecs[i].Width - MeasureText(colorNames[i], 10) - 12),
@ -158,12 +166,35 @@ public class ColorsPalette
//----------------------------------------------------------------------------------
}
public void Unload()
{
}
public static int Main()
{
// Initialization
//--------------------------------------------------------------------------------------
InitWindow(screenWidth, screenHeight, "raylib [shapes] example - colors palette");
SetTargetFPS(60); // Set our game to run at 60 frames-per-second
//--------------------------------------------------------------------------------------
var game = new ColorsPalette();
game.Init();
// Main game loop
while (!WindowShouldClose()) // Detect window close button or ESC key
{
game.Update();
}
game.Unload();
// De-Initialization
//--------------------------------------------------------------------------------------
CloseWindow();
CloseWindow(); // Close window and OpenGL context
//--------------------------------------------------------------------------------------
return 0;
}
}

View file

@ -1,13 +1,17 @@
/*******************************************************************************************
*
* raylib [shapes] example - draw circle sector (with gui options)
* raylib [shapes] example - circle sector drawing
*
* This example has been created using raylib 2.5 (www.raylib.com)
* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details)
* Example complexity rating: [] 3/4
*
* Example originally created with raylib 2.5, last time updated with raylib 2.5
*
* Example contributed by Vlad Adrian (@demizdor) and reviewed by Ramon Santamaria (@raysan5)
*
* Copyright (c) 2018 Vlad Adrian (@demizdor) and Ramon Santamaria (@raysan5)
* Example licensed under an unmodified zlib/libpng license, which is an OSI-certified,
* BSD-like license that allows static linking with closed source software
*
* Copyright (c) 2018-2025 Vlad Adrian (@demizdor) and Ramon Santamaria (@raysan5)
*
********************************************************************************************/
@ -17,30 +21,34 @@ using static Raylib_cs.Raylib;
namespace Examples.Shapes;
public class DrawCircleSector
public partial class DrawCircleSector : IExample
{
public static int Main()
private const int screenWidth = 800;
private const int screenHeight = 450;
public string Name => "Shapes / Draw Circle Sector";
public string Title => "raylib [shapes] example - circle sector drawing";
private Vector2 center;
private float outerRadius;
private float startAngle;
private float endAngle;
private float segments;
private float minSegments;
public void Init()
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
center = new((GetScreenWidth() - 300) / 2.0f, GetScreenHeight() / 2.0f);
InitWindow(screenWidth, screenHeight, "raylib [shapes] example - draw circle sector");
outerRadius = 180.0f;
startAngle = 0.0f;
endAngle = 180.0f;
segments = 10.0f;
minSegments = 4;
}
Vector2 center = new((GetScreenWidth() - 300) / 2, GetScreenHeight() / 2);
float outerRadius = 180.0f;
int startAngle = 0;
int endAngle = 180;
int segments = 0;
int minSegments = 4;
SetTargetFPS(60);
//--------------------------------------------------------------------------------------
// Main game loop
while (!WindowShouldClose())
public void Update()
{
// Update
//----------------------------------------------------------------------------------
@ -52,31 +60,31 @@ public class DrawCircleSector
BeginDrawing();
ClearBackground(Color.RayWhite);
DrawLine(500, 0, 500, GetScreenHeight(), ColorAlpha(Color.LightGray, 0.6f));
DrawRectangle(500, 0, GetScreenWidth() - 500, GetScreenHeight(), ColorAlpha(Color.LightGray, 0.3f));
DrawLine(500, 0, 500, GetScreenHeight(), Fade(Color.LightGray, 0.6f));
DrawRectangle(500, 0, GetScreenWidth() - 500, GetScreenHeight(), Fade(Color.LightGray, 0.3f));
DrawCircleSector(center, outerRadius, startAngle, endAngle, segments, ColorAlpha(Color.Maroon, 0.3f));
DrawCircleSector(center, outerRadius, startAngle, endAngle, (int)segments, Fade(Color.Maroon, 0.3f));
DrawCircleSectorLines(
center,
outerRadius,
startAngle,
endAngle,
segments,
ColorAlpha(Color.Maroon, 0.6f)
(int)segments,
Fade(Color.Maroon, 0.6f)
);
// Draw GUI controls
//------------------------------------------------------------------------------
/*startAngle = GuiSliderBar(new Rectangle( 600, 40, 120, 20), "StartAngle", startAngle, 0, 720, true );
endAngle = GuiSliderBar(new Rectangle( 600, 70, 120, 20), "EndAngle", endAngle, 0, 720, true);
/*GuiSliderBar(new Rectangle( 600, 40, 120, 20), "StartAngle", TextFormat("%.2f", startAngle), ref startAngle, 0, 720);
GuiSliderBar(new Rectangle( 600, 70, 120, 20), "EndAngle", TextFormat("%.2f", endAngle), ref endAngle, 0, 720);
outerRadius = GuiSliderBar(new Rectangle( 600, 140, 120, 20), "Radius", outerRadius, 0, 200, true);
segments = GuiSliderBar(new Rectangle( 600, 170, 120, 20), "Segments", segments, 0, 100, true);*/
GuiSliderBar(new Rectangle( 600, 140, 120, 20), "Radius", TextFormat("%.2f", outerRadius), ref outerRadius, 0, 200);
GuiSliderBar(new Rectangle( 600, 170, 120, 20), "Segments", TextFormat("%.2f", segments), ref segments, 0, 100);*/
//------------------------------------------------------------------------------
minSegments = (int)MathF.Ceiling((endAngle - startAngle) / 90);
Color color = (segments >= minSegments) ? Color.Maroon : Color.DarkGray;
DrawText($"MODE: {((segments >= minSegments) ? "MANUAL" : "AUTO")}", 600, 270, 10, color);
minSegments = MathF.Truncate(MathF.Ceiling((endAngle - startAngle) / 90));
var color = (segments >= minSegments) ? Color.Maroon : Color.DarkGray;
DrawText($"MODE: {((segments >= minSegments) ? "MANUAL" : "AUTO")}", 600, 200, 10, color);
DrawFPS(10, 10);
@ -84,12 +92,35 @@ public class DrawCircleSector
//----------------------------------------------------------------------------------
}
public void Unload()
{
}
public static int Main()
{
// Initialization
//--------------------------------------------------------------------------------------
InitWindow(screenWidth, screenHeight, "raylib [shapes] example - circle sector drawing");
SetTargetFPS(60); // Set our game to run at 60 frames-per-second
//--------------------------------------------------------------------------------------
var game = new DrawCircleSector();
game.Init();
// Main game loop
while (!WindowShouldClose()) // Detect window close button or ESC key
{
game.Update();
}
game.Unload();
// De-Initialization
//--------------------------------------------------------------------------------------
CloseWindow();
CloseWindow(); // Close window and OpenGL context
//--------------------------------------------------------------------------------------
return 0;
}
}

View file

@ -1,13 +1,17 @@
/*******************************************************************************************
*
* raylib [shapes] example - draw rectangle rounded (with gui options)
* raylib [shapes] example - rounded rectangle drawing
*
* This example has been created using raylib 2.5 (www.raylib.com)
* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details)
* Example complexity rating: [] 3/4
*
* Example originally created with raylib 2.5, last time updated with raylib 2.5
*
* Example contributed by Vlad Adrian (@demizdor) and reviewed by Ramon Santamaria (@raysan5)
*
* Copyright (c) 2018 Vlad Adrian (@demizdor) and Ramon Santamaria (@raysan5)
* Example licensed under an unmodified zlib/libpng license, which is an OSI-certified,
* BSD-like license that allows static linking with closed source software
*
* Copyright (c) 2018-2025 Vlad Adrian (@demizdor) and Ramon Santamaria (@raysan5)
*
********************************************************************************************/
@ -15,37 +19,44 @@ using static Raylib_cs.Raylib;
namespace Examples.Shapes;
public class DrawRectangleRounded
public partial class DrawRectangleRounded : IExample
{
public static int Main()
private const int screenWidth = 800;
private const int screenHeight = 450;
public string Name => "Shapes / Draw Rectangle Rounded";
public string Title => "raylib [shapes] example - rounded rectangle drawing";
private float roundness;
private float width;
private float height;
private float segments;
private float lineThick;
private bool drawRect;
private bool drawRoundedRect;
private bool drawRoundedLines;
public void Init()
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
roundness = 0.2f;
width = 200.0f;
height = 100.0f;
segments = 0.0f;
lineThick = 1.0f;
InitWindow(screenWidth, screenHeight, "raylib [shapes] example - draw rectangle rounded");
drawRect = false;
drawRoundedRect = true;
drawRoundedLines = false;
}
float roundness = 0.2f;
int width = 400;
int height = 200;
int segments = 0;
int lineThick = 10;
bool drawRect = false;
bool drawRoundedRect = false;
bool drawRoundedLines = true;
SetTargetFPS(60);
//--------------------------------------------------------------------------------------
// Main game loop
while (!WindowShouldClose())
public void Update()
{
// Update
//----------------------------------------------------------------------------------
Rectangle rec = new(
(GetScreenWidth() - width - 250) / 2.0f,
((float)GetScreenWidth() - width - 250) / 2,
(GetScreenHeight() - height) / 2.0f,
(float)width,
(float)height
@ -57,36 +68,36 @@ public class DrawRectangleRounded
BeginDrawing();
ClearBackground(Color.RayWhite);
DrawLine(560, 0, 560, GetScreenHeight(), ColorAlpha(Color.LightGray, 0.6f));
DrawRectangle(560, 0, GetScreenWidth() - 500, GetScreenHeight(), ColorAlpha(Color.LightGray, 0.3f));
DrawLine(560, 0, 560, GetScreenHeight(), Fade(Color.LightGray, 0.6f));
DrawRectangle(560, 0, GetScreenWidth() - 500, GetScreenHeight(), Fade(Color.LightGray, 0.3f));
if (drawRect)
{
DrawRectangleRec(rec, ColorAlpha(Color.Gold, 0.6f));
DrawRectangleRec(rec, Fade(Color.Gold, 0.6f));
}
if (drawRoundedRect)
{
DrawRectangleRounded(rec, roundness, segments, ColorAlpha(Color.Maroon, 0.2f));
DrawRectangleRounded(rec, roundness, (int)segments, Fade(Color.Maroon, 0.2f));
}
if (drawRoundedLines)
{
DrawRectangleRoundedLinesEx(rec, roundness, segments, (float)lineThick, ColorAlpha(Color.Maroon, 0.4f));
DrawRectangleRoundedLinesEx(rec, roundness, (int)segments, lineThick, Fade(Color.Maroon, 0.4f));
}
// Draw GUI controls
//------------------------------------------------------------------------------
/*width = GuiSliderBar(new Rectangle( 640, 40, 105, 20 ), "Width", width, 0, GetScreenWidth() - 300, true );
height = GuiSliderBar(new Rectangle( 640, 70, 105, 20 ), "Height", height, 0, GetScreenHeight() - 50, true);
roundness = GuiSliderBar(new Rectangle( 640, 140, 105, 20 ), "Roundness", roundness, 0.0f, 1.0f, true);
lineThick = GuiSliderBar(new Rectangle( 640, 170, 105, 20 ), "Thickness", lineThick, 0, 20, true);
segments = GuiSliderBar(new Rectangle( 640, 240, 105, 20), "Segments", segments, 0, 60, true);
/*GuiSliderBar(new Rectangle( 640, 40, 105, 20 ), "Width", TextFormat("%.2f", width), ref width, 0, (float)GetScreenWidth() - 300);
GuiSliderBar(new Rectangle( 640, 70, 105, 20 ), "Height", TextFormat("%.2f", height), ref height, 0, (float)GetScreenHeight() - 50);
GuiSliderBar(new Rectangle( 640, 140, 105, 20 ), "Roundness", TextFormat("%.2f", roundness), ref roundness, 0.0f, 1.0f);
GuiSliderBar(new Rectangle( 640, 170, 105, 20 ), "Thickness", TextFormat("%.2f", lineThick), ref lineThick, 0, 20);
GuiSliderBar(new Rectangle( 640, 240, 105, 20), "Segments", TextFormat("%.2f", segments), ref segments, 0, 60);
drawRoundedRect = GuiCheckBox(new Rectangle( 640, 320, 20, 20 ), "DrawRoundedRect", drawRoundedRect);
drawRoundedLines = GuiCheckBox(new Rectangle( 640, 350, 20, 20 ), "DrawRoundedLines", drawRoundedLines);
drawRect = GuiCheckBox(new Rectangle( 640, 380, 20, 20), "DrawRect", drawRect);*/
GuiCheckBox(new Rectangle( 640, 320, 20, 20 ), "DrawRoundedRect", ref drawRoundedRect);
GuiCheckBox(new Rectangle( 640, 350, 20, 20 ), "DrawRoundedLines", ref drawRoundedLines);
GuiCheckBox(new Rectangle( 640, 380, 20, 20), "DrawRect", ref drawRect);*/
//------------------------------------------------------------------------------
string text = $"MODE: {((segments >= 4) ? "MANUAL" : "AUTO")}";
var text = $"MODE: {((segments >= 4) ? "MANUAL" : "AUTO")}";
DrawText(text, 640, 280, 10, (segments >= 4) ? Color.Maroon : Color.DarkGray);
DrawFPS(10, 10);
@ -94,12 +105,35 @@ public class DrawRectangleRounded
//----------------------------------------------------------------------------------
}
public void Unload()
{
}
public static int Main()
{
// Initialization
//--------------------------------------------------------------------------------------
InitWindow(screenWidth, screenHeight, "raylib [shapes] example - rounded rectangle drawing");
SetTargetFPS(60); // Set our game to run at 60 frames-per-second
//--------------------------------------------------------------------------------------
var game = new DrawRectangleRounded();
game.Init();
// Main game loop
while (!WindowShouldClose()) // Detect window close button or ESC key
{
game.Update();
}
game.Unload();
// De-Initialization
//--------------------------------------------------------------------------------------
CloseWindow();
CloseWindow(); // Close window and OpenGL context
//--------------------------------------------------------------------------------------
return 0;
}
}

View file

@ -1,13 +1,17 @@
/*******************************************************************************************
*
* raylib [shapes] example - draw ring (with gui options)
* raylib [shapes] example - ring drawing
*
* This example has been created using raylib 2.5 (www.raylib.com)
* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details)
* Example complexity rating: [] 3/4
*
* Example originally created with raylib 2.5, last time updated with raylib 2.5
*
* Example contributed by Vlad Adrian (@demizdor) and reviewed by Ramon Santamaria (@raysan5)
*
* Copyright (c) 2018 Vlad Adrian (@demizdor) and Ramon Santamaria (@raysan5)
* Example licensed under an unmodified zlib/libpng license, which is an OSI-certified,
* BSD-like license that allows static linking with closed source software
*
* Copyright (c) 2018-2025 Vlad Adrian (@demizdor) and Ramon Santamaria (@raysan5)
*
********************************************************************************************/
@ -17,36 +21,45 @@ using static Raylib_cs.Raylib;
namespace Examples.Shapes;
public class DrawRing
public partial class DrawRing : IExample
{
public static int Main()
private const int screenWidth = 800;
private const int screenHeight = 450;
public string Name => "Shapes / Draw Ring";
public string Title => "raylib [shapes] example - ring drawing";
private Vector2 center;
private float innerRadius;
private float outerRadius;
private float startAngle;
private float endAngle;
private float segments;
private bool drawRing;
private bool drawRingLines;
private bool drawCircleLines;
public void Init()
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
center = new((GetScreenWidth() - 300) / 2.0f, GetScreenHeight() / 2.0f);
InitWindow(screenWidth, screenHeight, "raylib [shapes] example - draw ring");
innerRadius = 80.0f;
outerRadius = 190.0f;
Vector2 center = new((GetScreenWidth() - 300) / 2, GetScreenHeight() / 2);
startAngle = 0.0f;
endAngle = 360.0f;
segments = 0.0f;
float innerRadius = 80.0f;
float outerRadius = 190.0f;
drawRing = true;
drawRingLines = false;
drawCircleLines = false;
}
int startAngle = 0;
int endAngle = 360;
int segments = 0;
int minSegments = 4;
bool drawRing = true;
bool drawRingLines = false;
bool drawCircleLines = false;
SetTargetFPS(60);
//--------------------------------------------------------------------------------------
// Main game loop
while (!WindowShouldClose())
public void Update()
{
// Update
//----------------------------------------------------------------------------------
@ -58,8 +71,8 @@ public class DrawRing
BeginDrawing();
ClearBackground(Color.RayWhite);
DrawLine(500, 0, 500, GetScreenHeight(), ColorAlpha(Color.LightGray, 0.6f));
DrawRectangle(500, 0, GetScreenWidth() - 500, GetScreenHeight(), ColorAlpha(Color.LightGray, 0.3f));
DrawLine(500, 0, 500, GetScreenHeight(), Fade(Color.LightGray, 0.6f));
DrawRectangle(500, 0, GetScreenWidth() - 500, GetScreenHeight(), Fade(Color.LightGray, 0.3f));
if (drawRing)
{
@ -69,8 +82,8 @@ public class DrawRing
outerRadius,
startAngle,
endAngle,
segments,
ColorAlpha(Color.Maroon, 0.3f)
(int)segments,
Fade(Color.Maroon, 0.3f)
);
}
if (drawRingLines)
@ -81,8 +94,8 @@ public class DrawRing
outerRadius,
startAngle,
endAngle,
segments,
ColorAlpha(Color.Black, 0.4f)
(int)segments,
Fade(Color.Black, 0.4f)
);
}
if (drawCircleLines)
@ -92,28 +105,28 @@ public class DrawRing
outerRadius,
startAngle,
endAngle,
segments,
ColorAlpha(Color.Black, 0.4f)
(int)segments,
Fade(Color.Black, 0.4f)
);
}
// Draw GUI controls
//------------------------------------------------------------------------------
/*startAngle = GuiSliderBar(new Rectangle( 600, 40, 120, 20 ), "StartAngle", startAngle, -450, 450, true);
endAngle = GuiSliderBar(new Rectangle( 600, 70, 120, 20 ), "EndAngle", endAngle, -450, 450, true);
/*GuiSliderBar(new Rectangle( 600, 40, 120, 20 ), "StartAngle", TextFormat("%.2f", startAngle), ref startAngle, -450, 450);
GuiSliderBar(new Rectangle( 600, 70, 120, 20 ), "EndAngle", TextFormat("%.2f", endAngle), ref endAngle, -450, 450);
innerRadius = GuiSliderBar(new Rectangle( 600, 140, 120, 20 ), "InnerRadius", innerRadius, 0, 100, true);
outerRadius = GuiSliderBar(new Rectangle( 600, 170, 120, 20 ), "OuterRadius", outerRadius, 0, 200, true);
GuiSliderBar(new Rectangle( 600, 140, 120, 20 ), "InnerRadius", TextFormat("%.2f", innerRadius), ref innerRadius, 0, 100);
GuiSliderBar(new Rectangle( 600, 170, 120, 20 ), "OuterRadius", TextFormat("%.2f", outerRadius), ref outerRadius, 0, 200);
segments = GuiSliderBar(new Rectangle( 600, 240, 120, 20 ), "Segments", segments, 0, 100, true);
GuiSliderBar(new Rectangle( 600, 240, 120, 20 ), "Segments", TextFormat("%.2f", segments), ref segments, 0, 100);
drawRing = GuiCheckBox(new Rectangle( 600, 320, 20, 20 ), "Draw Ring", drawRing);
drawRingLines = GuiCheckBox(new Rectangle( 600, 350, 20, 20 ), "Draw RingLines", drawRingLines);
drawCircleLines = GuiCheckBox(new Rectangle( 600, 380, 20, 20 ), "Draw CircleLines", drawCircleLines);*/
GuiCheckBox(new Rectangle( 600, 320, 20, 20 ), "Draw Ring", ref drawRing);
GuiCheckBox(new Rectangle( 600, 350, 20, 20 ), "Draw RingLines", ref drawRingLines);
GuiCheckBox(new Rectangle( 600, 380, 20, 20 ), "Draw CircleLines", ref drawCircleLines);*/
//------------------------------------------------------------------------------
minSegments = (int)MathF.Ceiling((endAngle - startAngle) / 90);
Color color = (segments >= minSegments) ? Color.Maroon : Color.DarkGray;
var minSegments = (int)MathF.Ceiling((endAngle - startAngle) / 90);
var color = (segments >= minSegments) ? Color.Maroon : Color.DarkGray;
DrawText($"MODE: {((segments >= minSegments) ? "MANUAL" : "AUTO")}", 600, 270, 10, color);
DrawFPS(10, 10);
@ -122,9 +135,33 @@ public class DrawRing
//----------------------------------------------------------------------------------
}
public void Unload()
{
}
public static int Main()
{
// Initialization
//--------------------------------------------------------------------------------------
InitWindow(screenWidth, screenHeight, "raylib [shapes] example - ring drawing");
SetTargetFPS(60); // Set our game to run at 60 frames-per-second
//--------------------------------------------------------------------------------------
var game = new DrawRing();
game.Init();
// Main game loop
while (!WindowShouldClose()) // Detect window close button or ESC key
{
game.Update();
}
game.Unload();
// De-Initialization
//--------------------------------------------------------------------------------------
CloseWindow();
CloseWindow(); // Close window and OpenGL context
//--------------------------------------------------------------------------------------
return 0;

View file

@ -1,11 +1,15 @@
/*******************************************************************************************
*
* raylib [shapes] example - easings ball anim
* raylib [shapes] example - easings ball
*
* This example has been created using raylib 2.5 (www.raylib.com)
* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details)
* Example complexity rating: [] 2/4
*
* Copyright (c) 2014-2019 Ramon Santamaria (@raysan5)
* Example originally created with raylib 2.5, last time updated with raylib 2.5
*
* Example licensed under an unmodified zlib/libpng license, which is an OSI-certified,
* BSD-like license that allows static linking with closed source software
*
* Copyright (c) 2014-2025 Ramon Santamaria (@raysan5)
*
********************************************************************************************/
@ -14,37 +18,41 @@ using Examples.Shared;
namespace Examples.Shapes;
public class EasingsBallAnim
public partial class EasingsBallAnim : IExample
{
public static int Main()
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
private const int screenWidth = 800;
private const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [shapes] example - easings ball anim");
public string Name => "Shapes / Easings Ball Anim";
public string Title => "raylib [shapes] example - easings ball";
// Ball variable value to be animated with easings
int ballPositionX = -100;
int ballRadius = 20;
float ballAlpha = 0.0f;
private int ballPositionX;
private int ballRadius;
private float ballAlpha;
int state = 0;
int framesCounter = 0;
private int state;
private int framesCounter;
SetTargetFPS(60);
//--------------------------------------------------------------------------------------
public void Init()
{
ballPositionX = -100;
ballRadius = 20;
ballAlpha = 0.0f;
// Main game loop
while (!WindowShouldClose())
state = 0;
framesCounter = 0;
}
public void Update()
{
// Update
//----------------------------------------------------------------------------------
if (state == 0) // Move ball position X with easing
{
framesCounter += 1;
ballPositionX = (int)Easings.EaseElasticOut(framesCounter, -100, screenWidth / 2 + 100, 120);
framesCounter++;
ballPositionX = (int)Easings.EaseElasticOut(framesCounter, -100, screenWidth / 2.0f + 100, 120);
if (framesCounter >= 120)
{
@ -52,10 +60,9 @@ public class EasingsBallAnim
state = 1;
}
}
// Increase ball radius with easing
else if (state == 1)
else if (state == 1) // Increase ball radius with easing
{
framesCounter += 1;
framesCounter++;
ballRadius = (int)Easings.EaseElasticIn(framesCounter, 20, 500, 200);
if (framesCounter >= 200)
@ -64,10 +71,9 @@ public class EasingsBallAnim
state = 2;
}
}
// Change ball alpha with easing (background color blending)
else if (state == 2)
else if (state == 2) // Change ball alpha with easing (background color blending)
{
framesCounter += 1;
framesCounter++;
ballAlpha = Easings.EaseCubicOut(framesCounter, 0.0f, 1.0f, 200);
if (framesCounter >= 200)
@ -76,8 +82,7 @@ public class EasingsBallAnim
state = 3;
}
}
// Reset state to play again
else if (state == 3)
else if (state == 3) // Reset state to play again
{
if (IsKeyPressed(KeyboardKey.Enter))
{
@ -105,7 +110,7 @@ public class EasingsBallAnim
DrawRectangle(0, 0, screenWidth, screenHeight, Color.Green);
}
DrawCircle(ballPositionX, 200, ballRadius, ColorAlpha(Color.Red, 1.0f - ballAlpha));
DrawCircle(ballPositionX, 200, ballRadius, Fade(Color.Red, 1.0f - ballAlpha));
if (state == 3)
{
@ -116,12 +121,35 @@ public class EasingsBallAnim
//----------------------------------------------------------------------------------
}
public void Unload()
{
}
public static int Main()
{
// Initialization
//--------------------------------------------------------------------------------------
InitWindow(screenWidth, screenHeight, "raylib [shapes] example - easings ball");
SetTargetFPS(60); // Set our game to run at 60 frames-per-second
//--------------------------------------------------------------------------------------
var game = new EasingsBallAnim();
game.Init();
// Main game loop
while (!WindowShouldClose()) // Detect window close button or ESC key
{
game.Update();
}
game.Unload();
// De-Initialization
//--------------------------------------------------------------------------------------
CloseWindow();
CloseWindow(); // Close window and OpenGL context
//--------------------------------------------------------------------------------------
return 0;
}
}

View file

@ -1,11 +1,15 @@
/*******************************************************************************************
*
* raylib [shapes] example - easings box anim
* raylib [shapes] example - easings box
*
* This example has been created using raylib 2.5 (www.raylib.com)
* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details)
* Example complexity rating: [] 2/4
*
* Copyright (c) 2014-2019 Ramon Santamaria (@raysan5)
* Example originally created with raylib 2.5, last time updated with raylib 2.5
*
* Example licensed under an unmodified zlib/libpng license, which is an OSI-certified,
* BSD-like license that allows static linking with closed source software
*
* Copyright (c) 2014-2025 Ramon Santamaria (@raysan5)
*
********************************************************************************************/
@ -15,42 +19,45 @@ using Examples.Shared;
namespace Examples.Shapes;
public class EasingsBoxAnim
public partial class EasingsBoxAnim : IExample
{
public static int Main()
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
private const int screenWidth = 800;
private const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [shapes] example - easings box anim");
public string Name => "Shapes / Easings Box Anim";
public string Title => "raylib [shapes] example - easings box";
// Box variables to be animated with easings
Rectangle rec = new(GetScreenWidth() / 2, -100, 100, 100);
float rotation = 0.0f;
float alpha = 1.0f;
private Rectangle rec;
private float rotation;
private float alpha;
int state = 0;
int framesCounter = 0;
private int state;
private int framesCounter;
SetTargetFPS(60);
//--------------------------------------------------------------------------------------
public void Init()
{
rec = new(GetScreenWidth() / 2.0f, -100, 100, 100);
rotation = 0.0f;
alpha = 1.0f;
// Main game loop
while (!WindowShouldClose())
state = 0;
framesCounter = 0;
}
public void Update()
{
// Update
//----------------------------------------------------------------------------------
switch (state)
{
// Move box down to center of screen
case 0:
framesCounter += 1;
case 0: // Move box down to center of screen
framesCounter++;
// NOTE: Remember that 3rd parameter of easing function refers to
// desired value variation, do not confuse it with expected final value!
rec.Y = Easings.EaseElasticOut(framesCounter, -100, GetScreenHeight() / 2 + 100, 120);
rec.Y = Easings.EaseElasticOut(framesCounter, -100, GetScreenHeight() / 2.0f + 100, 120);
if (framesCounter >= 120)
{
@ -58,9 +65,8 @@ public class EasingsBoxAnim
state = 1;
}
break;
// Scale box to an horizontal bar
case 1:
framesCounter += 1;
case 1: // Scale box to an horizontal bar
framesCounter++;
rec.Height = Easings.EaseBounceOut(framesCounter, 100, -90, 120);
rec.Width = Easings.EaseBounceOut(framesCounter, 100, GetScreenWidth(), 120);
@ -70,9 +76,8 @@ public class EasingsBoxAnim
state = 2;
}
break;
// Rotate horizontal bar rectangle
case 2:
framesCounter += 1;
case 2: // Rotate horizontal bar rectangle
framesCounter++;
rotation = Easings.EaseQuadOut(framesCounter, 0.0f, 270.0f, 240);
if (framesCounter >= 240)
@ -81,9 +86,8 @@ public class EasingsBoxAnim
state = 3;
}
break;
// Increase bar size to fill all screen
case 3:
framesCounter += 1;
case 3: // Increase bar size to fill all screen
framesCounter++;
rec.Height = Easings.EaseCircOut(framesCounter, 10, GetScreenWidth(), 120);
if (framesCounter >= 120)
@ -92,8 +96,7 @@ public class EasingsBoxAnim
state = 4;
}
break;
// Fade out animation
case 4:
case 4: // Fade out animation
framesCounter++;
alpha = Easings.EaseSineOut(framesCounter, 1.0f, -1.0f, 160);
@ -110,7 +113,7 @@ public class EasingsBoxAnim
// Reset animation at any moment
if (IsKeyPressed(KeyboardKey.Space))
{
rec = new Rectangle(GetScreenWidth() / 2, -100, 100, 100);
rec = new Rectangle(GetScreenWidth() / 2.0f, -100, 100, 100);
rotation = 0.0f;
alpha = 1.0f;
state = 0;
@ -127,7 +130,7 @@ public class EasingsBoxAnim
rec,
new Vector2(rec.Width / 2, rec.Height / 2),
rotation,
ColorAlpha(Color.Black, alpha)
Fade(Color.Black, alpha)
);
DrawText("PRESS [SPACE] TO RESET BOX ANIMATION!", 10, GetScreenHeight() - 25, 20, Color.LightGray);
@ -135,9 +138,33 @@ public class EasingsBoxAnim
//----------------------------------------------------------------------------------
}
public void Unload()
{
}
public static int Main()
{
// Initialization
//--------------------------------------------------------------------------------------
InitWindow(screenWidth, screenHeight, "raylib [shapes] example - easings box");
SetTargetFPS(60); // Set our game to run at 60 frames-per-second
//--------------------------------------------------------------------------------------
var game = new EasingsBoxAnim();
game.Init();
// Main game loop
while (!WindowShouldClose()) // Detect window close button or ESC key
{
game.Update();
}
game.Unload();
// De-Initialization
//--------------------------------------------------------------------------------------
CloseWindow();
CloseWindow(); // Close window and OpenGL context
//--------------------------------------------------------------------------------------
return 0;

View file

@ -1,14 +1,18 @@
/*******************************************************************************************
*
* raylib [shapes] example - easings rectangle array
* raylib [shapes] example - easings rectangles
*
* Example complexity rating: [] 3/4
*
* 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)
* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details)
* Example originally created with raylib 2.0, last time updated with raylib 2.5
*
* Copyright (c) 2014-2019 Ramon Santamaria (@raysan5)
* Example licensed under an unmodified zlib/libpng license, which is an OSI-certified,
* BSD-like license that allows static linking with closed source software
*
* Copyright (c) 2014-2025 Ramon Santamaria (@raysan5)
*
********************************************************************************************/
@ -18,8 +22,11 @@ using Examples.Shared;
namespace Examples.Shapes;
public class EasingsRectangleArray
public partial class EasingsRectangleArray : IExample
{
private const int screenWidth = 800;
private const int screenHeight = 450;
public const int RecsWidth = 50;
public const int RecsHeight = 50;
public const int MaxRecsX = 800 / RecsWidth;
@ -28,39 +35,36 @@ public class EasingsRectangleArray
// At 60 fps = 4 seconds
public const int PlayTimeInFrames = 240;
public static int Main()
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
public string Name => "Shapes / Easings Rectangle Array";
InitWindow(screenWidth, screenHeight, "raylib [shapes] example - easings rectangle array");
public string Title => "raylib [shapes] example - easings rectangles";
Rectangle[] recs = new Rectangle[MaxRecsX * MaxRecsY];
private Rectangle[] recs;
private float rotation;
private int framesCounter;
private int state; // Rectangles animation state: 0-Playing, 1-Finished
for (int y = 0; y < MaxRecsY; y++)
public void Init()
{
for (int x = 0; x < MaxRecsX; x++)
recs = new Rectangle[MaxRecsX * MaxRecsY];
for (var y = 0; y < MaxRecsY; y++)
{
recs[y * MaxRecsX + x].X = RecsWidth / 2 + RecsWidth * x;
recs[y * MaxRecsX + x].Y = RecsHeight / 2 + RecsHeight * y;
for (var x = 0; x < MaxRecsX; x++)
{
recs[y * MaxRecsX + x].X = RecsWidth / 2.0f + RecsWidth * x;
recs[y * MaxRecsX + x].Y = RecsHeight / 2.0f + RecsHeight * y;
recs[y * MaxRecsX + x].Width = RecsWidth;
recs[y * MaxRecsX + x].Height = RecsHeight;
}
}
float rotation = 0.0f;
int framesCounter = 0;
rotation = 0.0f;
framesCounter = 0;
state = 0;
}
// Rectangles animation state: 0-Playing, 1-Finished
int state = 0;
SetTargetFPS(60);
//--------------------------------------------------------------------------------------
// Main game loop
while (!WindowShouldClose())
public void Update()
{
// Update
//----------------------------------------------------------------------------------
@ -68,7 +72,7 @@ public class EasingsRectangleArray
{
framesCounter++;
for (int i = 0; i < MaxRecsX * MaxRecsY; i++)
for (var i = 0; i < MaxRecsX * MaxRecsY; i++)
{
recs[i].Height = Easings.EaseCircOut(framesCounter, RecsHeight, -RecsHeight, PlayTimeInFrames);
recs[i].Width = Easings.EaseCircOut(framesCounter, RecsWidth, -RecsWidth, PlayTimeInFrames);
@ -95,7 +99,7 @@ public class EasingsRectangleArray
// When animation has finished, press space to restart
framesCounter = 0;
for (int i = 0; i < MaxRecsX * MaxRecsY; i++)
for (var i = 0; i < MaxRecsX * MaxRecsY; i++)
{
recs[i].Height = RecsHeight;
recs[i].Width = RecsWidth;
@ -112,7 +116,7 @@ public class EasingsRectangleArray
if (state == 0)
{
for (int i = 0; i < MaxRecsX * MaxRecsY; i++)
for (var i = 0; i < MaxRecsX * MaxRecsY; i++)
{
DrawRectanglePro(
recs[i],
@ -131,9 +135,33 @@ public class EasingsRectangleArray
//----------------------------------------------------------------------------------
}
public void Unload()
{
}
public static int Main()
{
// Initialization
//--------------------------------------------------------------------------------------
InitWindow(screenWidth, screenHeight, "raylib [shapes] example - easings rectangles");
SetTargetFPS(60); // Set our game to run at 60 frames-per-second
//--------------------------------------------------------------------------------------
var game = new EasingsRectangleArray();
game.Init();
// Main game loop
while (!WindowShouldClose()) // Detect window close button or ESC key
{
game.Update();
}
game.Unload();
// De-Initialization
//--------------------------------------------------------------------------------------
CloseWindow();
CloseWindow(); // Close window and OpenGL context
//--------------------------------------------------------------------------------------
return 0;

View file

@ -2,10 +2,14 @@
*
* raylib [shapes] example - following eyes
*
* This example has been created using raylib 2.5 (www.raylib.com)
* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details)
* Example complexity rating: [] 2/4
*
* Copyright (c) 2013-2019 Ramon Santamaria (@raysan5)
* Example originally created with raylib 2.5, last time updated with raylib 2.5
*
* Example licensed under an unmodified zlib/libpng license, which is an OSI-certified,
* BSD-like license that allows static linking with closed source software
*
* Copyright (c) 2013-2025 Ramon Santamaria (@raysan5)
*
********************************************************************************************/
@ -16,33 +20,44 @@ using static Raylib_cs.Raylib;
namespace Examples.Shapes;
public class FollowingEyes
public partial class FollowingEyes : IExample
{
public static int Main()
private const int screenWidth = 800;
private const int screenHeight = 450;
public string Name => "Shapes / Following Eyes";
public string Title => "raylib [shapes] example - following eyes";
private Vector2 scleraLeftPosition;
private Vector2 scleraRightPosition;
private float scleraRadius;
private Vector2 irisLeftPosition;
private Vector2 irisRightPosition;
private float irisRadius;
private float angle;
private float dx, dy, dxx, dyy;
public void Init()
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
scleraLeftPosition = new(GetScreenWidth() / 2.0f - 100.0f, GetScreenHeight() / 2.0f);
scleraRightPosition = new(GetScreenWidth() / 2.0f + 100.0f, GetScreenHeight() / 2.0f);
scleraRadius = 80;
InitWindow(screenWidth, screenHeight, "raylib [shapes] example - following eyes");
irisLeftPosition = new(GetScreenWidth() / 2.0f - 100.0f, GetScreenHeight() / 2.0f);
irisRightPosition = new(GetScreenWidth() / 2.0f + 100.0f, GetScreenHeight() / 2.0f);
irisRadius = 24;
Vector2 scleraLeftPosition = new(GetScreenWidth() / 2 - 100, GetScreenHeight() / 2);
Vector2 scleraRightPosition = new(GetScreenWidth() / 2 + 100, GetScreenHeight() / 2);
float scleraRadius = 80;
angle = 0.0f;
dx = 0.0f;
dy = 0.0f;
dxx = 0.0f;
dyy = 0.0f;
}
Vector2 irisLeftPosition = new(GetScreenWidth() / 2 - 100, GetScreenHeight() / 2);
Vector2 irisRightPosition = new(GetScreenWidth() / 2 + 100, GetScreenHeight() / 2);
float irisRadius = 24;
float angle = 0.0f;
float dx = 0.0f, dy = 0.0f, dxx = 0.0f, dyy = 0.0f;
SetTargetFPS(60);
//--------------------------------------------------------------------------------------
// Main game loop
while (!WindowShouldClose())
public void Update()
{
// Update
//----------------------------------------------------------------------------------
@ -50,7 +65,7 @@ public class FollowingEyes
irisRightPosition = GetMousePosition();
// Check not inside the left eye sclera
if (!CheckCollisionPointCircle(irisLeftPosition, scleraLeftPosition, scleraRadius - 20))
if (!CheckCollisionPointCircle(irisLeftPosition, scleraLeftPosition, scleraRadius - irisRadius))
{
dx = irisLeftPosition.X - scleraLeftPosition.X;
dy = irisLeftPosition.Y - scleraLeftPosition.Y;
@ -65,7 +80,7 @@ public class FollowingEyes
}
// Check not inside the right eye sclera
if (!CheckCollisionPointCircle(irisRightPosition, scleraRightPosition, scleraRadius - 20))
if (!CheckCollisionPointCircle(irisRightPosition, scleraRightPosition, scleraRadius - irisRadius))
{
dx = irisRightPosition.X - scleraRightPosition.X;
dy = irisRightPosition.Y - scleraRightPosition.Y;
@ -99,9 +114,33 @@ public class FollowingEyes
//----------------------------------------------------------------------------------
}
public void Unload()
{
}
public static int Main()
{
// Initialization
//--------------------------------------------------------------------------------------
InitWindow(screenWidth, screenHeight, "raylib [shapes] example - following eyes");
SetTargetFPS(60); // Set our game to run at 60 frames-per-second
//--------------------------------------------------------------------------------------
var game = new FollowingEyes();
game.Init();
// Main game loop
while (!WindowShouldClose()) // Detect window close button or ESC key
{
game.Update();
}
game.Unload();
// De-Initialization
//--------------------------------------------------------------------------------------
CloseWindow();
CloseWindow(); // Close window and OpenGL context
//--------------------------------------------------------------------------------------
return 0;

View file

@ -1,11 +1,15 @@
/*******************************************************************************************
*
* raylib [shapes] example - Cubic-bezier lines
* raylib [shapes] example - lines bezier
*
* This example has been created using raylib 1.7 (www.raylib.com)
* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details)
* Example complexity rating: [] 1/4
*
* Copyright (c) 2017 Ramon Santamaria (@raysan5)
* Example originally created with raylib 1.7, last time updated with raylib 1.7
*
* Example licensed under an unmodified zlib/libpng license, which is an OSI-certified,
* BSD-like license that allows static linking with closed source software
*
* Copyright (c) 2017-2025 Ramon Santamaria (@raysan5)
*
********************************************************************************************/
@ -14,36 +18,61 @@ using static Raylib_cs.Raylib;
namespace Examples.Shapes;
public class LinesBezier
public partial class LinesBezier : IExample
{
public static int Main()
private const int screenWidth = 800;
private const int screenHeight = 450;
public string Name => "Shapes / Lines Bezier";
public string Title => "raylib [shapes] example - lines bezier";
public ConfigFlags ConfigFlags => ConfigFlags.Msaa4xHint;
private Vector2 startPoint;
private Vector2 endPoint;
private bool moveStartPoint;
private bool moveEndPoint;
public void Init()
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
startPoint = new(30, 30);
endPoint = new(screenWidth - 30, screenHeight - 30);
moveStartPoint = false;
moveEndPoint = false;
}
SetConfigFlags(ConfigFlags.Msaa4xHint);
InitWindow(screenWidth, screenHeight, "raylib [shapes] example - cubic-bezier lines");
Vector2 start = new(0, 0);
Vector2 end = new(screenWidth, screenHeight);
SetTargetFPS(60);
//--------------------------------------------------------------------------------------
// Main game loop
while (!WindowShouldClose())
public void Update()
{
// Update
//----------------------------------------------------------------------------------
if (IsMouseButtonDown(MouseButton.Left))
var mouse = GetMousePosition();
if (CheckCollisionPointCircle(mouse, startPoint, 10.0f) && IsMouseButtonDown(MouseButton.Left))
{
start = GetMousePosition();
moveStartPoint = true;
}
else if (IsMouseButtonDown(MouseButton.Right))
else if (CheckCollisionPointCircle(mouse, endPoint, 10.0f) && IsMouseButtonDown(MouseButton.Left))
{
end = GetMousePosition();
moveEndPoint = true;
}
if (moveStartPoint)
{
startPoint = mouse;
if (IsMouseButtonReleased(MouseButton.Left))
{
moveStartPoint = false;
}
}
if (moveEndPoint)
{
endPoint = mouse;
if (IsMouseButtonReleased(MouseButton.Left))
{
moveEndPoint = false;
}
}
//----------------------------------------------------------------------------------
@ -52,16 +81,47 @@ public class LinesBezier
BeginDrawing();
ClearBackground(Color.RayWhite);
DrawText("USE MOUSE LEFT-RIGHT CLICK to DEFINE LINE START and END POINTS", 15, 20, 20, Color.Gray);
DrawLineBezier(start, end, 2.0f, Color.Red);
DrawText("MOVE START-END POINTS WITH MOUSE", 15, 20, 20, Color.Gray);
// Draw line Cubic Bezier, in-out interpolation (easing), no control points
DrawLineBezier(startPoint, endPoint, 4.0f, Color.Blue);
// Draw start-end spline circles with some details
DrawCircleV(startPoint, CheckCollisionPointCircle(mouse, startPoint, 10.0f) ? 14.0f : 8.0f, moveStartPoint ? Color.Red : Color.Blue);
DrawCircleV(endPoint, CheckCollisionPointCircle(mouse, endPoint, 10.0f) ? 14.0f : 8.0f, moveEndPoint ? Color.Red : Color.Blue);
EndDrawing();
//----------------------------------------------------------------------------------
}
public void Unload()
{
}
public static int Main()
{
// Initialization
//--------------------------------------------------------------------------------------
SetConfigFlags(ConfigFlags.Msaa4xHint);
InitWindow(screenWidth, screenHeight, "raylib [shapes] example - lines bezier");
SetTargetFPS(60); // Set our game to run at 60 frames-per-second
//--------------------------------------------------------------------------------------
var game = new LinesBezier();
game.Init();
// Main game loop
while (!WindowShouldClose()) // Detect window close button or ESC key
{
game.Update();
}
game.Unload();
// De-Initialization
//--------------------------------------------------------------------------------------
CloseWindow();
CloseWindow(); // Close window and OpenGL context
//--------------------------------------------------------------------------------------
return 0;

View file

@ -1,11 +1,15 @@
/*******************************************************************************************
*
* raylib [shapes] example - raylib logo animation
* raylib [shapes] example - logo raylib anim
*
* This example has been created using raylib 1.4 (www.raylib.com)
* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details)
* Example complexity rating: [] 2/4
*
* Copyright (c) 2014 Ramon Santamaria (@raysan5)
* Example originally created with raylib 2.5, last time updated with raylib 4.0
*
* Example licensed under an unmodified zlib/libpng license, which is an OSI-certified,
* BSD-like license that allows static linking with closed source software
*
* Copyright (c) 2014-2025 Ramon Santamaria (@raysan5)
*
********************************************************************************************/
@ -13,59 +17,67 @@ using static Raylib_cs.Raylib;
namespace Examples.Shapes;
public class LogoRaylibAnim
public partial class LogoRaylibAnim : IExample
{
public static int Main()
private const int screenWidth = 800;
private const int screenHeight = 450;
public string Name => "Shapes / Logo Raylib Anim";
public string Title => "raylib [shapes] example - logo raylib anim";
private int logoPositionX;
private int logoPositionY;
private int framesCounter;
private int lettersCount;
private int topSideRecWidth;
private int leftSideRecHeight;
private int bottomSideRecWidth;
private int rightSideRecHeight;
private int state; // Tracking animation states (State Machine)
private float alpha; // Useful for fading
private Color outline;
public void Init()
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
logoPositionX = screenWidth / 2 - 128;
logoPositionY = screenHeight / 2 - 128;
InitWindow(screenWidth, screenHeight, "raylib [shapes] example - raylib logo animation");
framesCounter = 0;
lettersCount = 0;
int logoPositionX = screenWidth / 2 - 128;
int logoPositionY = screenHeight / 2 - 128;
topSideRecWidth = 16;
leftSideRecHeight = 16;
int framesCounter = 0;
int lettersCount = 0;
bottomSideRecWidth = 16;
rightSideRecHeight = 16;
int topSideRecWidth = 16;
int leftSideRecHeight = 16;
state = 0;
alpha = 1.0f;
int bottomSideRecWidth = 16;
int rightSideRecHeight = 16;
outline = new(139, 71, 135, 255);
}
// Tracking animation states (State Machine)
int state = 0;
// Useful for fading
float alpha = 1.0f;
Color outline = new(139, 71, 135, 255);
SetTargetFPS(60);
//--------------------------------------------------------------------------------------
// Main game loop
while (!WindowShouldClose())
public void Update()
{
// Update
//----------------------------------------------------------------------------------
// State 0: Small box blinking
if (state == 0)
if (state == 0) // State 0: Small box blinking
{
framesCounter++;
// Reset counter... will be used later...
if (framesCounter == 120)
{
state = 1;
framesCounter = 0;
framesCounter = 0; // Reset counter... will be used later...
}
}
// State 1: Top and left bars growing
else if (state == 1)
else if (state == 1) // State 1: Top and left bars growing
{
topSideRecWidth += 4;
leftSideRecHeight += 4;
@ -75,8 +87,7 @@ public class LogoRaylibAnim
state = 2;
}
}
// State 2: Bottom and right bars growing
else if (state == 2)
else if (state == 2) // State 2: Bottom and right bars growing
{
bottomSideRecWidth += 4;
rightSideRecHeight += 4;
@ -86,8 +97,7 @@ public class LogoRaylibAnim
state = 3;
}
}
// State 3: Letters appearing (one by one)
else if (state == 3)
else if (state == 3) // State 3: Letters appearing (one by one)
{
framesCounter++;
@ -110,8 +120,7 @@ public class LogoRaylibAnim
}
}
}
// State 4: Reset and Replay
else if (state == 4)
else if (state == 4) // State 4: Reset and Replay
{
if (IsKeyPressed(KeyboardKey.R))
{
@ -124,9 +133,8 @@ public class LogoRaylibAnim
bottomSideRecWidth = 16;
rightSideRecHeight = 16;
// Return to State 0
alpha = 1.0f;
state = 0;
state = 0; // Return to State 0
}
}
//----------------------------------------------------------------------------------
@ -158,18 +166,18 @@ public class LogoRaylibAnim
}
else if (state == 3)
{
Color outlineFade = ColorAlpha(outline, alpha);
var outlineFade = Fade(outline, alpha);
DrawRectangle(logoPositionX, logoPositionY, topSideRecWidth, 16, outlineFade);
DrawRectangle(logoPositionX, logoPositionY + 16, 16, leftSideRecHeight - 32, outlineFade);
DrawRectangle(logoPositionX + 240, logoPositionY + 16, 16, rightSideRecHeight - 32, outlineFade);
DrawRectangle(logoPositionX, logoPositionY + 240, bottomSideRecWidth, 16, outlineFade);
Color whiteFade = ColorAlpha(Color.RayWhite, alpha);
var whiteFade = Fade(Color.RayWhite, alpha);
DrawRectangle(screenWidth / 2 - 112, screenHeight / 2 - 112, 224, 224, whiteFade);
Color label = ColorAlpha(new Color(155, 79, 151, 255), alpha);
string text = "raylib".SubText(0, lettersCount);
var label = Fade(new Color(155, 79, 151, 255), alpha);
var text = "raylib".SubText(0, lettersCount);
DrawText(text, screenWidth / 2 - 44, screenHeight / 2 + 28, 50, label);
DrawText("cs".SubText(0, lettersCount), screenWidth / 2 - 44, screenHeight / 2 + 58, 50, label);
@ -183,9 +191,33 @@ public class LogoRaylibAnim
//----------------------------------------------------------------------------------
}
public void Unload()
{
}
public static int Main()
{
// Initialization
//--------------------------------------------------------------------------------------
InitWindow(screenWidth, screenHeight, "raylib [shapes] example - logo raylib anim");
SetTargetFPS(60); // Set our game to run at 60 frames-per-second
//--------------------------------------------------------------------------------------
var game = new LogoRaylibAnim();
game.Init();
// Main game loop
while (!WindowShouldClose()) // Detect window close button or ESC key
{
game.Update();
}
game.Unload();
// De-Initialization
//--------------------------------------------------------------------------------------
CloseWindow();
CloseWindow(); // Close window and OpenGL context
//--------------------------------------------------------------------------------------
return 0;

View file

@ -1,11 +1,15 @@
/*******************************************************************************************
*
* raylib [shapes] example - Draw raylib logo using basic shapes
* raylib [shapes] example - logo raylib
*
* 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)
* Example complexity rating: [] 1/4
*
* Copyright (c) 2014 Ramon Santamaria (@raysan5)
* Example originally created with raylib 1.0, last time updated with raylib 1.0
*
* Example licensed under an unmodified zlib/libpng license, which is an OSI-certified,
* BSD-like license that allows static linking with closed source software
*
* Copyright (c) 2014-2025 Ramon Santamaria (@raysan5)
*
********************************************************************************************/
@ -13,28 +17,21 @@ using static Raylib_cs.Raylib;
namespace Examples.Shapes;
public class LogoRaylibShape
public partial class LogoRaylibShape : IExample
{
public static int Main()
private const int screenWidth = 800;
private const int screenHeight = 450;
public string Name => "Shapes / Logo Raylib Shape";
public string Title => "raylib [shapes] example - logo raylib";
public void Init()
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
}
InitWindow(screenWidth, screenHeight, "raylib [shapes] example - raylib logo using shapes");
SetTargetFPS(60);
//--------------------------------------------------------------------------------------
// Main game loop
while (!WindowShouldClose())
public void Update()
{
// Update
//----------------------------------------------------------------------------------
// TODO: Update your variables here
//----------------------------------------------------------------------------------
// Draw
//----------------------------------------------------------------------------------
BeginDrawing();
@ -51,9 +48,33 @@ public class LogoRaylibShape
//----------------------------------------------------------------------------------
}
public void Unload()
{
}
public static int Main()
{
// Initialization
//--------------------------------------------------------------------------------------
InitWindow(screenWidth, screenHeight, "raylib [shapes] example - logo raylib");
SetTargetFPS(60); // Set our game to run at 60 frames-per-second
//--------------------------------------------------------------------------------------
var game = new LogoRaylibShape();
game.Init();
// Main game loop
while (!WindowShouldClose()) // Detect window close button or ESC key
{
game.Update();
}
game.Unload();
// De-Initialization
//--------------------------------------------------------------------------------------
CloseWindow();
CloseWindow(); // Close window and OpenGL context
//--------------------------------------------------------------------------------------
return 0;

View file

@ -1,13 +1,17 @@
/*******************************************************************************************
*
* raylib [shapes] example - rectangle scaling by mouse
* raylib [shapes] example - rectangle scaling
*
* This example has been created using raylib 2.5 (www.raylib.com)
* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details)
* Example complexity rating: [] 2/4
*
* Example originally created with raylib 2.5, last time updated with raylib 2.5
*
* Example contributed by Vlad Adrian (@demizdor) and reviewed by Ramon Santamaria (@raysan5)
*
* Copyright (c) 2018 Vlad Adrian (@demizdor) and Ramon Santamaria (@raysan5)
* Example licensed under an unmodified zlib/libpng license, which is an OSI-certified,
* BSD-like license that allows static linking with closed source software
*
* Copyright (c) 2018-2025 Vlad Adrian (@demizdor) and Ramon Santamaria (@raysan5)
*
********************************************************************************************/
@ -16,30 +20,35 @@ using static Raylib_cs.Raylib;
namespace Examples.Shapes;
public class RectangleScaling
public partial class RectangleScaling : IExample
{
private const int screenWidth = 800;
private const int screenHeight = 450;
public const int MOUSE_SCALE_MARK_SIZE = 12;
public static int Main()
public string Name => "Shapes / Rectangle Scaling";
public string Title => "raylib [shapes] example - rectangle scaling";
private Rectangle rec;
private Vector2 mousePosition;
private bool mouseScaleReady;
private bool mouseScaleMode;
public void Init()
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
rec = new(100, 100, 200, 80);
InitWindow(screenWidth, screenHeight, "raylib [shapes] example - rectangle scaling mouse");
mousePosition = new(0, 0);
Rectangle rec = new(100, 100, 200, 80);
Vector2 mousePosition = new(0, 0);
mouseScaleReady = false;
mouseScaleMode = false;
}
bool mouseScaleReady = false;
bool mouseScaleMode = false;
SetTargetFPS(60);
//--------------------------------------------------------------------------------------
// Main game loop
while (!WindowShouldClose())
public void Update()
{
// Update
//----------------------------------------------------------------------------------
@ -52,8 +61,7 @@ public class RectangleScaling
MOUSE_SCALE_MARK_SIZE
);
if (CheckCollisionPointRec(mousePosition, rec) &&
CheckCollisionPointRec(mousePosition, area))
if (CheckCollisionPointRec(mousePosition, area))
{
mouseScaleReady = true;
if (IsMouseButtonPressed(MouseButton.Left))
@ -73,6 +81,7 @@ public class RectangleScaling
rec.Width = (mousePosition.X - rec.X);
rec.Height = (mousePosition.Y - rec.Y);
// Check minimum rec size
if (rec.Width < MOUSE_SCALE_MARK_SIZE)
{
rec.Width = MOUSE_SCALE_MARK_SIZE;
@ -82,6 +91,16 @@ public class RectangleScaling
rec.Height = MOUSE_SCALE_MARK_SIZE;
}
// Check maximum rec size
if (rec.Width > (GetScreenWidth() - rec.X))
{
rec.Width = GetScreenWidth() - rec.X;
}
if (rec.Height > (GetScreenHeight() - rec.Y))
{
rec.Height = GetScreenHeight() - rec.Y;
}
if (IsMouseButtonReleased(MouseButton.Left))
{
mouseScaleMode = false;
@ -95,7 +114,8 @@ public class RectangleScaling
ClearBackground(Color.RayWhite);
DrawText("Scale rectangle dragging from bottom-right corner!", 10, 10, 20, Color.Gray);
DrawRectangleRec(rec, ColorAlpha(Color.Green, 0.5f));
DrawRectangleRec(rec, Fade(Color.Green, 0.5f));
if (mouseScaleReady)
{
@ -112,9 +132,33 @@ public class RectangleScaling
//----------------------------------------------------------------------------------
}
public void Unload()
{
}
public static int Main()
{
// Initialization
//--------------------------------------------------------------------------------------
InitWindow(screenWidth, screenHeight, "raylib [shapes] example - rectangle scaling");
SetTargetFPS(60); // Set our game to run at 60 frames-per-second
//--------------------------------------------------------------------------------------
var game = new RectangleScaling();
game.Init();
// Main game loop
while (!WindowShouldClose()) // Detect window close button or ESC key
{
game.Update();
}
game.Unload();
// De-Initialization
//--------------------------------------------------------------------------------------
CloseWindow();
CloseWindow(); // Close window and OpenGL context
//--------------------------------------------------------------------------------------
return 0;

View file

@ -132,26 +132,26 @@ public static class Easings
// Back Easing functions
public static float EaseBackIn(float t, float b, float c, float d)
{
float s = 1.70158f;
float postFix = t /= d;
var s = 1.70158f;
var postFix = t /= d;
return (c * (postFix) * t * ((s + 1) * t - s) + b);
}
public static float EaseBackOut(float t, float b, float c, float d)
{
float s = 1.70158f;
var s = 1.70158f;
return (c * ((t = t / d - 1) * t * ((s + 1) * t + s) + 1) + b);
}
public static float EaseBackInOut(float t, float b, float c, float d)
{
float s = 1.70158f;
var s = 1.70158f;
if ((t /= d / 2) < 1)
{
return (c / 2 * (t * t * (((s *= (1.525f)) + 1) * t - s)) + b);
}
float postFix = t -= 2;
var postFix = t -= 2;
return (c / 2 * ((postFix) * t * (((s *= (1.525f)) + 1) * t + s) + 2) + b);
}
@ -164,17 +164,17 @@ public static class Easings
}
else if (t < (2 / 2.75f))
{
float postFix = t -= (1.5f / 2.75f);
var postFix = t -= (1.5f / 2.75f);
return (c * (7.5625f * (postFix) * t + 0.75f) + b);
}
else if (t < (2.5 / 2.75))
{
float postFix = t -= (2.25f / 2.75f);
var postFix = t -= (2.25f / 2.75f);
return (c * (7.5625f * (postFix) * t + 0.9375f) + b);
}
else
{
float postFix = t -= (2.625f / 2.75f);
var postFix = t -= (2.625f / 2.75f);
return (c * (7.5625f * (postFix) * t + 0.984375f) + b);
}
}
@ -208,10 +208,10 @@ public static class Easings
return (b + c);
}
float p = d * 0.3f;
float a = c;
float s = p / 4;
float postFix = a * MathF.Pow(2, 10 * (t -= 1));
var p = d * 0.3f;
var a = c;
var s = p / 4;
var postFix = a * MathF.Pow(2, 10 * (t -= 1));
return (-(postFix * MathF.Sin((t * d - s) * (2 * MathF.PI) / p)) + b);
}
@ -227,9 +227,9 @@ public static class Easings
return (b + c);
}
float p = d * 0.3f;
float a = c;
float s = p / 4;
var p = d * 0.3f;
var a = c;
var s = p / 4;
return (a * MathF.Pow(2, -10 * t) * MathF.Sin((t * d - s) * (2 * MathF.PI) / p) + c + b);
}
@ -245,11 +245,11 @@ public static class Easings
return (b + c);
}
float p = d * (0.3f * 1.5f);
float a = c;
float s = p / 4;
var p = d * (0.3f * 1.5f);
var a = c;
var s = p / 4;
float postFix = 0f;
var postFix = 0f;
if (t < 1)
{
postFix = a * MathF.Pow(2, 10 * (t -= 1));

View file

@ -54,12 +54,12 @@ public class PbrLights
);
light.Intensity = intensity;
string enabledName = "lights[" + lightsCount + "].enabled";
string typeName = "lights[" + lightsCount + "].type";
string posName = "lights[" + lightsCount + "].position";
string targetName = "lights[" + lightsCount + "].target";
string colorName = "lights[" + lightsCount + "].color";
string intensityName = "lights[" + lightsCount + "].intensity";
var enabledName = "lights[" + lightsCount + "].enabled";
var typeName = "lights[" + lightsCount + "].type";
var posName = "lights[" + lightsCount + "].position";
var targetName = "lights[" + lightsCount + "].target";
var colorName = "lights[" + lightsCount + "].color";
var intensityName = "lights[" + lightsCount + "].intensity";
light.EnabledLoc = GetShaderLocation(shader, enabledName);
light.TypeLoc = GetShaderLocation(shader, typeName);

View file

@ -43,11 +43,11 @@ public static class Rlights
light.Target = target;
light.Color = color;
string enabledName = "lights[" + lightsCount + "].enabled";
string typeName = "lights[" + lightsCount + "].type";
string posName = "lights[" + lightsCount + "].position";
string targetName = "lights[" + lightsCount + "].target";
string colorName = "lights[" + lightsCount + "].color";
var enabledName = "lights[" + lightsCount + "].enabled";
var typeName = "lights[" + lightsCount + "].type";
var posName = "lights[" + lightsCount + "].position";
var targetName = "lights[" + lightsCount + "].target";
var colorName = "lights[" + lightsCount + "].color";
light.EnabledLoc = GetShaderLocation(shader, enabledName);
light.TypeLoc = GetShaderLocation(shader, typeName);
@ -78,7 +78,7 @@ public static class Rlights
Raylib.SetShaderValue(shader, light.TargetLoc, light.Target, ShaderUniformDataType.Vec3);
// Send to shader light color values
float[] color = new[]
var color = new[]
{
(float)light.Color.R / (float)255,
(float)light.Color.G / (float)255,

View file

@ -1,13 +1,15 @@
/*******************************************************************************************
*
* raylib [text] example - Codepoints loading
* raylib [text] example - codepoints loading
*
* Example originally created with raylib 4.2, last time updated with raylib 2.5
* Example complexity rating: [] 3/4
*
* Example originally created with raylib 4.2, last time updated with raylib 4.2
*
* Example licensed under an unmodified zlib/libpng license, which is an OSI-certified,
* BSD-like license that allows static linking with closed source software
*
* Copyright (c) 2022-2023 Ramon Santamaria (@raysan5)
* Copyright (c) 2022-2025 Ramon Santamaria (@raysan5)
*
********************************************************************************************/
@ -19,32 +21,37 @@ using static Raylib_cs.Raylib;
namespace Examples.Text;
class CodepointsLoading
public partial class CodepointsLoading : IExample
{
public unsafe static int Main()
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [text] example - codepoints loading");
private const int screenWidth = 800;
private const int screenHeight = 450;
// Text to be displayed, must be UTF-8 (save this code file as UTF-8)
// NOTE: It can contain all the required text for the game,
// this text will be scanned to get all the required codepoints
const string text =
private const string text =
"いろはにほへと ちりぬるを\nわかよたれそ つねならむ\nうゐのおくやま けふこえて\nあさきゆめみし ゑひもせす";
public string Name => "Text / Codepoints Loading";
public string Title => "raylib [text] example - codepoints loading";
private List<int> codepoints;
private int[] codepointsNoDuplicates;
private Font font;
private bool showFontAtlas;
public void Init()
{
// Get codepoints from text
List<int> codepoints = GetCodePoints(text);
codepoints = GetCodePoints(text);
// Remove duplicate codepoints to generate smaller font atlas
int[] codepointsNoDuplicates = codepoints.Distinct().ToArray();
codepointsNoDuplicates = codepoints.Distinct().ToArray();
// Load font containing all the provided codepoint glyphs
// A texture font atlas is automatically generated
Font font = LoadFontEx(
font = LoadFontEx(
"resources/fonts/DotGothic16-Regular.ttf",
36,
codepointsNoDuplicates,
@ -54,13 +61,12 @@ class CodepointsLoading
// Set bilinear scale filter for better font scaling
SetTextureFilter(font.Texture, TextureFilter.Bilinear);
bool showFontAtlas = false;
SetTextLineSpacing(20); // Set line spacing for multiline text (when line breaks are included '\n')
SetTargetFPS(60);
//--------------------------------------------------------------------------------------
showFontAtlas = false;
}
// Main game loop
while (!WindowShouldClose())
public void Update()
{
// Update
//----------------------------------------------------------------------------------
@ -94,7 +100,7 @@ class CodepointsLoading
}
else
{
// Draw provided text with laoded font, containing all required codepoint glyphs
// Draw provided text with loaded font, containing all required codepoint glyphs
DrawTextEx(font, text, new Vector2(160, 110), 48, 5, Color.Black);
}
@ -104,14 +110,9 @@ class CodepointsLoading
//----------------------------------------------------------------------------------
}
// De-Initialization
//--------------------------------------------------------------------------------------
UnloadFont(font);
CloseWindow();
//--------------------------------------------------------------------------------------
return 0;
public void Unload()
{
UnloadFont(font); // Unload font
}
private static List<int> GetCodePoints(string text)
@ -119,14 +120,42 @@ class CodepointsLoading
List<int> codePoints = new();
StringInfo stringInfo = new(text);
TextElementEnumerator enumerator = StringInfo.GetTextElementEnumerator(text);
var enumerator = StringInfo.GetTextElementEnumerator(text);
while (enumerator.MoveNext())
{
int codePoint = char.ConvertToUtf32(enumerator.Current.ToString(), 0);
var codePoint = char.ConvertToUtf32(enumerator.Current.ToString(), 0);
codePoints.Add(codePoint);
}
return codePoints;
}
public static int Main()
{
// Initialization
//--------------------------------------------------------------------------------------
InitWindow(screenWidth, screenHeight, "raylib [text] example - codepoints loading");
SetTargetFPS(60); // Set our game to run at 60 frames-per-second
//--------------------------------------------------------------------------------------
var game = new CodepointsLoading();
game.Init();
// Main game loop
while (!WindowShouldClose()) // Detect window close button or ESC key
{
game.Update();
}
game.Unload();
// De-Initialization
//--------------------------------------------------------------------------------------
CloseWindow(); // Close window and OpenGL context
//--------------------------------------------------------------------------------------
return 0;
}
}

View file

@ -1,15 +1,19 @@
/*******************************************************************************************
*
* raylib [text] example - Font filters
* raylib [text] example - font filters
*
* After font loading, font texture atlas filter could be configured for a softer
* Example complexity rating: [] 2/4
*
* NOTE: After font loading, font texture atlas filter could be configured for a softer
* display of the font when scaling it to different sizes, that way, it's not required
* to generate multiple fonts at multiple sizes (as long as the scaling is not very different)
*
* This example has been created using raylib 1.3.0 (www.raylib.com)
* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details)
* Example originally created with raylib 1.3, last time updated with raylib 4.2
*
* Copyright (c) 2015 Ramon Santamaria (@raysan5)
* Example licensed under an unmodified zlib/libpng license, which is an OSI-certified,
* BSD-like license that allows static linking with closed source software
*
* Copyright (c) 2015-2025 Ramon Santamaria (@raysan5)
*
********************************************************************************************/
@ -18,41 +22,45 @@ using static Raylib_cs.Raylib;
namespace Examples.Text;
public class FontFilters
public partial class FontFilters : IExample
{
public static int Main()
private const int screenWidth = 800;
private const int screenHeight = 450;
public string Name => "Text / Font Filters";
public string Title => "raylib [text] example - font filters";
private string msg;
private Font font;
private float fontSize;
private Vector2 fontPosition;
private Vector2 textSize;
private TextureFilter currentFontFilter;
public void Init()
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [text] example - font filters");
string msg = "Loaded Font";
msg = "Loaded Font";
// NOTE: Textures/Fonts MUST be loaded after Window initialization (OpenGL context is required)
// TTF Font loading with custom generation parameters
Font font = LoadFontEx("resources/fonts/KAISG.ttf", 96, null, 0);
font = LoadFontEx("resources/fonts/KAISG.ttf", 96, null, 0);
// Generate mipmap levels to use trilinear filtering
// NOTE: On 2D drawing it won't be noticeable, it looks like TEXTURE_FILTER_BILINEAR
// NOTE: On 2D drawing it won't be noticeable, it looks like FILTER_BILINEAR
GenTextureMipmaps(ref font.Texture);
float fontSize = font.BaseSize;
Vector2 fontPosition = new(40, screenHeight / 2 - 80);
Vector2 textSize = new(0.0f, 0.0f);
fontSize = font.BaseSize;
fontPosition = new(40, screenHeight / 2 - 80);
textSize = new(0.0f, 0.0f);
// Setup texture scaling filter
SetTextureFilter(font.Texture, TextureFilter.Point);
TextureFilter currentFontFilter = TextureFilter.Point;
currentFontFilter = TextureFilter.Point; // TEXTURE_FILTER_POINT
}
SetTargetFPS(60);
//--------------------------------------------------------------------------------------
// Main game loop
while (!WindowShouldClose())
public void Update()
{
// Update
//----------------------------------------------------------------------------------
@ -87,10 +95,13 @@ public class FontFilters
fontPosition.X += 10;
}
#if BROWSER
// NOTE: drag-and-drop font loading is not supported in the browser host; default loaded font is kept.
#else
// Load a dropped TTF file dynamically (at current fontSize)
if (IsFileDropped())
{
string[] files = Raylib.GetDroppedFiles();
var files = Raylib.GetDroppedFiles();
// NOTE: We only support first ttf file dropped
if (IsFileExtension(files[0], ".ttf"))
@ -99,6 +110,7 @@ public class FontFilters
font = LoadFontEx(files[0], (int)fontSize, null, 0);
}
}
#endif
//----------------------------------------------------------------------------------
// Draw
@ -113,14 +125,19 @@ public class FontFilters
DrawTextEx(font, msg, fontPosition, fontSize, 0, Color.Black);
// TODO: It seems texSize measurement is not accurate due to chars offsets...
//DrawRectangleLines((int)fontPosition.X, (int)fontPosition.Y, (int)textSize.X, (int)textSize.Y, Color.Red);
DrawRectangle(0, screenHeight - 80, screenWidth, 80, Color.LightGray);
DrawText($"Font size: {fontSize:00.00}", 20, screenHeight - 50, 10, Color.DarkGray);
DrawText($"Text size: [{textSize.X:00.00}, {textSize.Y:00.00}]", 20, screenHeight - 30, 10, Color.DarkGray);
DrawText("CURRENT TEXTURE FILTER:", 250, 400, 20, Color.Gray);
if (currentFontFilter == TextureFilter.Point)
{
DrawText("POINT", 570, 400, 20, Color.Black);
}
else if (currentFontFilter == TextureFilter.Point)
else if (currentFontFilter == TextureFilter.Bilinear)
{
DrawText("BILINEAR", 570, 400, 20, Color.Black);
}
@ -133,14 +150,36 @@ public class FontFilters
//----------------------------------------------------------------------------------
}
public void Unload()
{
UnloadFont(font); // Font unloading
}
public static int Main()
{
// Initialization
//--------------------------------------------------------------------------------------
InitWindow(screenWidth, screenHeight, "raylib [text] example - font filters");
SetTargetFPS(60); // Set our game to run at 60 frames-per-second
//--------------------------------------------------------------------------------------
var game = new FontFilters();
game.Init();
// Main game loop
while (!WindowShouldClose()) // Detect window close button or ESC key
{
game.Update();
}
game.Unload();
// De-Initialization
//--------------------------------------------------------------------------------------
UnloadFont(font);
CloseWindow();
CloseWindow(); // Close window and OpenGL context
//--------------------------------------------------------------------------------------
return 0;
}
}

View file

@ -1,20 +1,24 @@
/*******************************************************************************************
*
* raylib [text] example - Font loading
* raylib [text] example - font loading
*
* raylib can load fonts from multiple file formats:
* Example complexity rating: [] 1/4
*
* NOTE: raylib can load fonts from multiple input file formats:
*
* - TTF/OTF > Sprite font atlas is generated on loading, user can configure
* some of the generation parameters (size, characters to include)
* - BMFonts > Angel code font fileformat, sprite font image must be provided
* together with the .fnt file, font generation cna not be configured
* together with the .fnt file, font generation can not be configured
* - XNA Spritefont > Sprite font image, following XNA Spritefont conventions,
* Characters in image must follow some spacing and order rules
*
* This example has been created using raylib 2.6 (www.raylib.com)
* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details)
* Example originally created with raylib 1.4, last time updated with raylib 3.0
*
* Copyright (c) 2016-2019 Ramon Santamaria (@raysan5)
* Example licensed under an unmodified zlib/libpng license, which is an OSI-certified,
* BSD-like license that allows static linking with closed source software
*
* Copyright (c) 2016-2025 Ramon Santamaria (@raysan5)
*
********************************************************************************************/
@ -23,37 +27,41 @@ using static Raylib_cs.Raylib;
namespace Examples.Text;
public class FontLoading
public partial class FontLoading : IExample
{
public static int Main()
private const int screenWidth = 800;
private const int screenHeight = 450;
public string Name => "Text / Font Loading";
public string Title => "raylib [text] example - font loading";
private string msg;
private Font fontBm;
private Font fontTtf;
private bool useTtf;
public void Init()
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [text] example - font loading");
// Define characters to draw
// NOTE: raylib supports UTF-8 encoding, following list is actually codified as UTF8 internally
string msg = "!\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHI\nJKLMNOPQRSTUVWXYZ[]^_`abcdefghijklmn\nopqrstuvwxyz{|}~¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓ\nÔÕÖרÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷\nøùúûüýþÿ";
msg = "!#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHI\nJKLMNOPQRSTUVWXYZ[]^_`abcdefghijklmn\nopqrstuvwxyz{|}~¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓ\nÔÕÖרÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷\nøùúûüýþÿ";
// 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
Font fontBm = LoadFont("resources/fonts/pixantiqua.fnt");
fontBm = LoadFont("resources/fonts/pixantiqua.fnt"); // Requires "resources/fonts/pixantiqua.png"
// 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
Font fontTtf = LoadFontEx("resources/fonts/pixantiqua.ttf", 32, null, 250);
fontTtf = LoadFontEx("resources/fonts/pixantiqua.ttf", 32, null, 250);
bool useTtf = false;
SetTextLineSpacing(16); // Set line spacing for multiline text (when line breaks are included '\n')
SetTargetFPS(60);
//--------------------------------------------------------------------------------------
useTtf = false;
}
// Main game loop
while (!WindowShouldClose())
public void Update()
{
// Update
//----------------------------------------------------------------------------------
@ -89,12 +97,35 @@ public class FontLoading
//----------------------------------------------------------------------------------
}
public void Unload()
{
UnloadFont(fontBm); // AngelCode Font unloading
UnloadFont(fontTtf); // TTF Font unloading
}
public static int Main()
{
// Initialization
//--------------------------------------------------------------------------------------
InitWindow(screenWidth, screenHeight, "raylib [text] example - font loading");
SetTargetFPS(60); // Set our game to run at 60 frames-per-second
//--------------------------------------------------------------------------------------
var game = new FontLoading();
game.Init();
// Main game loop
while (!WindowShouldClose()) // Detect window close button or ESC key
{
game.Update();
}
game.Unload();
// De-Initialization
//--------------------------------------------------------------------------------------
UnloadFont(fontBm);
UnloadFont(fontTtf);
CloseWindow();
CloseWindow(); // Close window and OpenGL context
//--------------------------------------------------------------------------------------
return 0;

View file

@ -1,11 +1,15 @@
/*******************************************************************************************
*
* raylib [text] example - TTF loading and usage
* raylib [text] example - font sdf
*
* This example has been created using raylib 1.3.0 (www.raylib.com)
* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details)
* Example complexity rating: [] 3/4
*
* Copyright (c) 2015 Ramon Santamaria (@raysan5)
* Example originally created with raylib 1.3, last time updated with raylib 4.0
*
* Example licensed under an unmodified zlib/libpng license, which is an OSI-certified,
* BSD-like license that allows static linking with closed source software
*
* Copyright (c) 2015-2025 Ramon Santamaria (@raysan5)
*
********************************************************************************************/
@ -16,23 +20,44 @@ using static Raylib_cs.Raylib;
namespace Examples.Text;
public class FontSdf
public partial class FontSdf : IExample
{
public unsafe static int Main()
private const int screenWidth = 800;
private const int screenHeight = 450;
#if BROWSER
const int GlslVersion = 100; // WebGL1 needs GLSL ES 100
#else
private const int GlslVersion = 330;
#endif
public string Name => "Text / Font SDF";
public string Title => "raylib [text] example - font sdf";
private string msg;
private Font fontDefault;
private Font fontSDF;
private Shader shader;
private Vector2 fontPosition;
private Vector2 textSize;
private float fontSize;
private int currentFont;
public unsafe void Init()
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [text] example - SDF fonts");
// NOTE: Textures/Fonts MUST be loaded after Window initialization (OpenGL context is required)
string msg = "Signed Distance Fields";
msg = "Signed Distance Fields";
// Loading file to memory
int fileSize = 0;
byte* fileData = LoadFileData("resources/fonts/anonymous_pro_bold.ttf", ref fileSize);
var fileSize = 0;
var fileData = LoadFileData("resources/fonts/anonymous_pro_bold.ttf", ref fileSize);
// Build the fonts in locals first: taking the address of a struct's field (&font.GlyphCount,
// &font.Recs) is only allowed for a stack local, not a heap field. Assign to the fields after.
// Default font generation from TTF font
Font fontDefault = new();
@ -40,43 +65,39 @@ public class FontSdf
fontDefault.GlyphCount = 95;
// Loading font data from memory data
// Parameters > font size: 16, no chars array provided (0), chars count: 95 (autogenerate chars array)
// Parameters > font size: 16, no glyphs array provided (0), glyphs count: 95 (autogenerate chars array)
fontDefault.Glyphs = LoadFontData(fileData, (int)fileSize, 16, null, 95, FontType.Default, &fontDefault.GlyphCount);
// Parameters > chars count: 95, font size: 16, chars padding in image: 4 px, pack method: 0 (default)
Image atlas = GenImageFontAtlas(fontDefault.Glyphs, &fontDefault.Recs, 95, 16, 4, 0);
// Parameters > glyphs count: 95, font size: 16, glyphs padding in image: 4 px, pack method: 0 (default)
var atlas = GenImageFontAtlas(fontDefault.Glyphs, &fontDefault.Recs, 95, 16, 4, 0);
fontDefault.Texture = LoadTextureFromImage(atlas);
UnloadImage(atlas);
this.fontDefault = fontDefault;
// SDF font generation from TTF font
Font fontSDF = new();
fontSDF.BaseSize = 16;
fontSDF.GlyphCount = 95;
// Parameters > font size: 16, no chars array provided (0), chars count: 0 (defaults to 95)
fontSDF.Glyphs = LoadFontData(fileData, (int)fileSize, 16, null, 0, FontType.Sdf, &fontDefault.GlyphCount);
// Parameters > chars count: 95, font size: 16, chars padding in image: 0 px, pack method: 1 (Skyline algorythm)
// Parameters > font size: 16, no glyphs array provided (0), glyphs count: 0 (defaults to 95)
fontSDF.Glyphs = LoadFontData(fileData, (int)fileSize, 16, null, 0, FontType.Sdf, &fontSDF.GlyphCount);
// Parameters > glyphs count: 95, font size: 16, glyphs padding in image: 0 px, pack method: 1 (Skyline algorythm)
atlas = GenImageFontAtlas(fontSDF.Glyphs, &fontSDF.Recs, 95, 16, 0, 1);
fontSDF.Texture = LoadTextureFromImage(atlas);
UnloadImage(atlas);
this.fontSDF = fontSDF;
// Free memory from loaded file
UnloadFileData(fileData);
UnloadFileData(fileData); // Free memory from loaded file
// Load SDF required shader (we use default vertex shader)
Shader shader = LoadShader(null, "resources/shaders/glsl330/sdf.fs");
// Required for SDF font
SetTextureFilter(fontSDF.Texture, TextureFilter.Bilinear);
shader = LoadShader(null, $"resources/shaders/glsl{GlslVersion}/sdf.fs");
SetTextureFilter(fontSDF.Texture, TextureFilter.Bilinear); // Required for SDF font
Vector2 fontPosition = new(40, screenHeight / 2 - 50);
Vector2 textSize = new(0.0f);
float fontSize = 16.0f;
// 0 - fontDefault, 1 - fontSDF
int currentFont = 0;
fontPosition = new(40, screenHeight / 2.0f - 50);
textSize = new(0.0f);
fontSize = 16.0f;
currentFont = 0; // 0 - fontDefault, 1 - fontSDF
}
SetTargetFPS(60);
//--------------------------------------------------------------------------------------
// Main game loop
while (!WindowShouldClose())
public void Update()
{
// Update
//----------------------------------------------------------------------------------
@ -117,9 +138,9 @@ public class FontSdf
if (currentFont == 1)
{
// NOTE: SDF fonts require a custom SDf shader to compute fragment color
BeginShaderMode(shader);
BeginShaderMode(shader); // Activate SDF font shader
DrawTextEx(fontSDF, msg, fontPosition, fontSize, 0, Color.Black);
EndShaderMode();
EndShaderMode(); // Activate our default shader for next drawings
DrawTexture(fontSDF.Texture, 10, 10, Color.Black);
}
@ -139,22 +160,46 @@ public class FontSdf
}
DrawText("FONT SIZE: 16.0", GetScreenWidth() - 240, 20, 20, Color.DarkGray);
DrawText($"RENDER SIZE: {fontSize:2F}", GetScreenWidth() - 240, 50, 20, Color.DarkGray);
DrawText($"RENDER SIZE: {fontSize:00.00}", GetScreenWidth() - 240, 50, 20, Color.DarkGray);
DrawText("Use MOUSE WHEEL to SCALE TEXT!", GetScreenWidth() - 240, 90, 10, Color.DarkGray);
DrawText("PRESS SPACE to USE SDF FONT VERSION!", 340, GetScreenHeight() - 30, 20, Color.Maroon);
DrawText("HOLD SPACE to USE SDF FONT VERSION!", 340, GetScreenHeight() - 30, 20, Color.Maroon);
EndDrawing();
//----------------------------------------------------------------------------------
}
public void Unload()
{
UnloadFont(fontDefault); // Default font unloading
UnloadFont(fontSDF); // SDF font unloading
UnloadShader(shader); // Unload SDF shader
}
public static int Main()
{
// Initialization
//--------------------------------------------------------------------------------------
InitWindow(screenWidth, screenHeight, "raylib [text] example - font sdf");
SetTargetFPS(60); // Set our game to run at 60 frames-per-second
//--------------------------------------------------------------------------------------
var game = new FontSdf();
game.Init();
// Main game loop
while (!WindowShouldClose()) // Detect window close button or ESC key
{
game.Update();
}
game.Unload();
// De-Initialization
//--------------------------------------------------------------------------------------
UnloadFont(fontDefault);
UnloadFont(fontSDF);
UnloadShader(shader);
CloseWindow();
CloseWindow(); // Close window and OpenGL context
//--------------------------------------------------------------------------------------
return 0;

View file

@ -1,20 +1,25 @@
/*******************************************************************************************
*
* raylib [text] example - Sprite font loading
* raylib [text] example - font spritefont
*
* Example complexity rating: [] 1/4
*
* NOTE: Sprite fonts should be generated following this conventions:
*
* Loaded sprite fonts have been generated following XNA SpriteFont conventions:
* - Characters must be ordered starting with character 32 (Space)
* - Every character must be contained within the same Rectangle height
* - Every character and every line must be separated the same distance
* - Rectangles must be defined by a magenta color background
* - Every character and every line must be separated by the same distance (margin/padding)
* - Rectangles must be defined by a MAGENTA color background
*
* If following this constraints, a font can be provided just by an image,
* this is quite handy to avoid additional information files (like BMFonts use).
* Following those constraints, a font can be provided just by an image,
* this is quite handy to avoid additional font descriptor files (like BMFonts use)
*
* 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)
* Example originally created with raylib 1.0, last time updated with raylib 1.0
*
* Copyright (c) 2014 Ramon Santamaria (@raysan5)
* Example licensed under an unmodified zlib/libpng license, which is an OSI-certified,
* BSD-like license that allows static linking with closed source software
*
* Copyright (c) 2014-2025 Ramon Santamaria (@raysan5)
*
********************************************************************************************/
@ -23,46 +28,55 @@ using static Raylib_cs.Raylib;
namespace Examples.Text;
public class FontSpritefont
public partial class FontSpritefont : IExample
{
public static int Main()
private const int screenWidth = 800;
private const int screenHeight = 450;
public string Name => "Text / Font Spritefont";
public string Title => "raylib [text] example - font spritefont";
private string msg1;
private string msg2;
private string msg3;
private Font font1;
private Font font2;
private Font font3;
private Vector2 fontPosition1;
private Vector2 fontPosition2;
private Vector2 fontPosition3;
public void Init()
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [text] example - sprite font loading");
string msg1 = "THIS IS A custom SPRITE FONT...";
string msg2 = "...and this is ANOTHER CUSTOM font...";
string msg3 = "...and a THIRD one! GREAT! :D";
msg1 = "THIS IS A custom SPRITE FONT...";
msg2 = "...and this is ANOTHER CUSTOM font...";
msg3 = "...and a THIRD one! GREAT! :D";
// NOTE: Textures/Fonts MUST be loaded after Window initialization (OpenGL context is required)
Font font1 = LoadFont("resources/fonts/custom_mecha.png");
Font font2 = LoadFont("resources/fonts/custom_alagard.png");
Font font3 = LoadFont("resources/fonts/custom_jupiter_crash.png");
font1 = LoadFont("resources/custom_mecha.png"); // Font loading
font2 = LoadFont("resources/custom_alagard.png"); // Font loading
font3 = LoadFont("resources/custom_jupiter_crash.png"); // Font loading
Vector2 fontPosition1 = new(
fontPosition1 = new(
screenWidth / 2 - MeasureTextEx(font1, msg1, font1.BaseSize, -3).X / 2,
screenHeight / 2 - font1.BaseSize / 2 - 80
);
Vector2 fontPosition2 = new(
fontPosition2 = new(
screenWidth / 2 - MeasureTextEx(font2, msg2, font2.BaseSize, -2).X / 2,
screenHeight / 2 - font2.BaseSize / 2 - 10
);
Vector2 fontPosition3 = new(
fontPosition3 = new(
screenWidth / 2 - MeasureTextEx(font3, msg3, font3.BaseSize, 2).X / 2,
screenHeight / 2 - font3.BaseSize / 2 + 50
);
}
SetTargetFPS(60);
//--------------------------------------------------------------------------------------
// Main game loop
while (!WindowShouldClose())
public void Update()
{
// Update
//----------------------------------------------------------------------------------
@ -82,13 +96,36 @@ public class FontSpritefont
//----------------------------------------------------------------------------------
}
public void Unload()
{
UnloadFont(font1); // Font unloading
UnloadFont(font2); // Font unloading
UnloadFont(font3); // Font unloading
}
public static int Main()
{
// Initialization
//--------------------------------------------------------------------------------------
InitWindow(screenWidth, screenHeight, "raylib [text] example - font spritefont");
SetTargetFPS(60); // Set our game to run at 60 frames-per-second
//--------------------------------------------------------------------------------------
var game = new FontSpritefont();
game.Init();
// Main game loop
while (!WindowShouldClose()) // Detect window close button or ESC key
{
game.Update();
}
game.Unload();
// De-Initialization
//--------------------------------------------------------------------------------------
UnloadFont(font1);
UnloadFont(font2);
UnloadFont(font3);
CloseWindow();
CloseWindow(); // Close window and OpenGL context
//--------------------------------------------------------------------------------------
return 0;

Some files were not shown because too many files have changed in this diff Show more