2
0
mirror of https://github.com/raylib-cs/raylib-cs synced 2025-06-30 19:03:42 -04:00

Update/merge examples back into main repo (#192)

This commit is contained in:
2023-08-25 08:08:32 +01:00
committed by GitHub
parent fa682b00ac
commit bcdf8cec5b
320 changed files with 57965 additions and 1 deletions

View File

@ -0,0 +1,224 @@
/*******************************************************************************************
*
* raylib [shaders] example - basic lighting
*
* NOTE: This example requires raylib OpenGL 3.3 or ES2 versions for shaders support,
* OpenGL 1.1 does not support shaders, recompile raylib to OpenGL 3.3 version.
*
* NOTE: Shaders used in this example are #version 330 (OpenGL 3.3).
*
* This example has been created using raylib 2.5 (www.raylib.com)
* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details)
*
* Example contributed by Chris Camacho (@codifies) and reviewed by Ramon Santamaria (@raysan5)
*
* Chris Camacho (@codifies - http://bedroomcoders.co.uk/) notes:
*
* This is based on the PBR lighting example, but greatly simplified to aid learning...
* actually there is very little of the PBR example left!
* When I first looked at the bewildering complexity of the PBR example I feared
* I would never understand how I could do simple lighting with raylib however its
* a testement to the authors of raylib (including rlights.h) that the example
* came together fairly quickly.
*
* Copyright (c) 2019 Chris Camacho (@codifies) and Ramon Santamaria (@raysan5)
*
********************************************************************************************/
using System.Numerics;
using static Raylib_cs.Raylib;
using static Examples.Rlights;
namespace Examples.Shaders;
public class BasicLighting
{
const int GLSL_VERSION = 330;
public unsafe static int Main()
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
// Enable Multi Sampling Anti Aliasing 4x (if available)
SetConfigFlags(ConfigFlags.FLAG_MSAA_4X_HINT);
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.CAMERA_PERSPECTIVE;
// 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"
);
// Get some required shader loactions
shader.Locs[(int)ShaderLocationIndex.SHADER_LOC_VECTOR_VIEW] = GetShaderLocation(shader, "viewPos");
// ambient light level
int ambientLoc = GetShaderLocation(shader, "ambient");
float[] ambient = new[] { 0.1f, 0.1f, 0.1f, 1.0f };
Raylib.SetShaderValue(shader, ambientLoc, ambient, ShaderUniformDataType.SHADER_UNIFORM_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];
lights[0] = CreateLight(
0,
LightType.Point,
new Vector3(-2, 1, -2),
Vector3.Zero,
Color.YELLOW,
shader
);
lights[1] = CreateLight(
1,
LightType.Point,
new Vector3(2, 1, 2),
Vector3.Zero,
Color.RED,
shader
);
lights[2] = CreateLight(
2,
LightType.Point,
new Vector3(-2, 1, 2),
Vector3.Zero,
Color.GREEN,
shader
);
lights[3] = CreateLight(
3,
LightType.Point,
new Vector3(2, 1, -2),
Vector3.Zero,
Color.BLUE,
shader
);
SetTargetFPS(60);
//--------------------------------------------------------------------------------------
// Main game loop
while (!WindowShouldClose())
{
// Update
//----------------------------------------------------------------------------------
UpdateCamera(ref camera, CameraMode.CAMERA_ORBITAL);
if (IsKeyPressed(KeyboardKey.KEY_Y))
{
lights[0].Enabled = !lights[0].Enabled;
}
if (IsKeyPressed(KeyboardKey.KEY_R))
{
lights[1].Enabled = !lights[1].Enabled;
}
if (IsKeyPressed(KeyboardKey.KEY_G))
{
lights[2].Enabled = !lights[2].Enabled;
}
if (IsKeyPressed(KeyboardKey.KEY_B))
{
lights[3].Enabled = !lights[3].Enabled;
}
// Update light values (actually, only enable/disable them)
UpdateLightValues(shader, lights[0]);
UpdateLightValues(shader, lights[1]);
UpdateLightValues(shader, lights[2]);
UpdateLightValues(shader, lights[3]);
// Update the light shader with the camera view position
Raylib.SetShaderValue(
shader,
shader.Locs[(int)ShaderLocationIndex.SHADER_LOC_VECTOR_VIEW],
camera.Position,
ShaderUniformDataType.SHADER_UNIFORM_VEC3
);
//----------------------------------------------------------------------------------
// Draw
//----------------------------------------------------------------------------------
BeginDrawing();
ClearBackground(Color.RAYWHITE);
BeginMode3D(camera);
DrawModel(model, Vector3.Zero, 1.0f, Color.WHITE);
DrawModel(cube, Vector3.Zero, 1.0f, Color.WHITE);
// Draw markers to show where the lights are
if (lights[0].Enabled)
{
DrawSphereEx(lights[0].Position, 0.2f, 8, 8, Color.YELLOW);
}
else
{
DrawSphereWires(lights[0].Position, 0.2f, 8, 8, ColorAlpha(Color.YELLOW, 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);
EndMode3D();
DrawFPS(10, 10);
DrawText("Use keys [Y][R][G][B] to toggle lights", 10, 40, 20, Color.DARKGRAY);
EndDrawing();
//----------------------------------------------------------------------------------
}
// De-Initialization
//--------------------------------------------------------------------------------------
UnloadModel(model);
UnloadModel(cube);
UnloadShader(shader);
CloseWindow();
//--------------------------------------------------------------------------------------
return 0;
}
}

View File

@ -0,0 +1,145 @@
/*******************************************************************************************
*
* raylib [shaders] example - Apply a postprocessing shader and connect a custom uniform variable
*
* NOTE: This example requires raylib OpenGL 3.3 or ES2 versions for shaders support,
* OpenGL 1.1 does not support shaders, recompile raylib to OpenGL 3.3 version.
*
* NOTE: Shaders used in this example are #version 330 (OpenGL 3.3), 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)
*
* Copyright (c) 2015 Ramon Santamaria (@raysan5)
*
********************************************************************************************/
using System.Numerics;
using static Raylib_cs.Raylib;
namespace Examples.Shaders;
public class CustomUniform
{
public static int Main()
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
// Enable Multi Sampling Anti Aliasing 4x (if available)
SetConfigFlags(ConfigFlags.FLAG_MSAA_4X_HINT);
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.CAMERA_PERSPECTIVE;
Model model = LoadModel("resources/models/barracks.obj");
Texture2D texture = LoadTexture("resources/models/barracks_diffuse.png");
// Set model diffuse texture
Raylib.SetMaterialTexture(ref model, 0, MaterialMapIndex.MATERIAL_MAP_ALBEDO, ref texture);
Vector3 position = new(0.0f, 0.0f, 0.0f);
// Load postpro shader
Shader shader = LoadShader("resources/shaders/glsl330/base.vs",
"resources/shaders/glsl330/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");
float[] 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);
SetTargetFPS(60);
//--------------------------------------------------------------------------------------
// Main game loop
while (!WindowShouldClose())
{
// Update
//----------------------------------------------------------------------------------
Vector2 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.SHADER_UNIFORM_VEC2);
UpdateCamera(ref camera, CameraMode.CAMERA_ORBITAL);
//----------------------------------------------------------------------------------
// Draw
//----------------------------------------------------------------------------------
BeginDrawing();
ClearBackground(Color.RAYWHITE);
// Enable drawing to texture
BeginTextureMode(target);
ClearBackground(Color.RAYWHITE);
BeginMode3D(camera);
DrawModel(model, position, 0.5f, Color.WHITE);
DrawGrid(10, 1.0f);
EndMode3D();
DrawText("TEXT DRAWN IN RENDER TEXTURE", 200, 10, 30, Color.RED);
// End drawing to texture (now we have a texture available for next passes)
EndTextureMode();
BeginShaderMode(shader);
// NOTE: Render texture must be y-flipped due to default OpenGL coordinates (left-bottom)
DrawTextureRec(
target.Texture,
new Rectangle(0, 0, target.Texture.Width, -target.Texture.Height),
new Vector2(0, 0),
Color.WHITE
);
EndShaderMode();
DrawText(
"(c) Barracks 3D model by Alberto Cano",
screenWidth - 220,
screenHeight - 20,
10,
Color.GRAY
);
DrawFPS(10, 10);
EndDrawing();
//----------------------------------------------------------------------------------
}
// De-Initialization
//--------------------------------------------------------------------------------------
UnloadShader(shader);
UnloadTexture(texture);
UnloadModel(model);
UnloadRenderTexture(target);
CloseWindow();
//--------------------------------------------------------------------------------------
return 0;
}
}

View File

@ -0,0 +1,103 @@
/*******************************************************************************************
*
* raylib [shaders] example - Sieve of Eratosthenes
*
* Sieve of Eratosthenes, the earliest known (ancient Greek) prime number sieve.
*
* "Sift the twos and sift the threes,
* The Sieve of Eratosthenes.
* When the multiples sublime,
* 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.
*
* NOTE: Shaders used in this example are #version 330 (OpenGL 3.3).
*
* This example has been created using raylib 2.5 (www.raylib.com)
* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details)
*
* Example contributed by ProfJski and reviewed by Ramon Santamaria (@raysan5)
*
* Copyright (c) 2019 ProfJski and Ramon Santamaria (@raysan5)
*
********************************************************************************************/
using System.Numerics;
using static Raylib_cs.Raylib;
namespace Examples.Shaders;
public class Eratosthenes
{
const int GlslVersion = 330;
public static int Main()
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [shaders] example - Sieve of Eratosthenes");
RenderTexture2D 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");
SetTargetFPS(60);
//--------------------------------------------------------------------------------------
// Main game loop
while (!WindowShouldClose())
{
// Update
//----------------------------------------------------------------------------------
// Nothing to do here, everything is happening in the shader
//----------------------------------------------------------------------------------
// Draw
//----------------------------------------------------------------------------------
BeginDrawing();
ClearBackground(Color.RAYWHITE);
// 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 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);
// End drawing to texture (now we have a blank texture available for the shader)
EndTextureMode();
BeginShaderMode(shader);
// NOTE: Render texture must be y-flipped due to default OpenGL coordinates (left-bottom)
DrawTextureRec(
target.Texture,
new Rectangle(0, 0, target.Texture.Width, -target.Texture.Height),
new Vector2(0.0f, 0.0f),
Color.WHITE
);
EndShaderMode();
EndDrawing();
//----------------------------------------------------------------------------------
}
// De-Initialization
//--------------------------------------------------------------------------------------
UnloadShader(shader);
UnloadRenderTexture(target);
CloseWindow();
//--------------------------------------------------------------------------------------
return 0;
}
}

181
Examples/Shaders/Fog.cs Normal file
View File

@ -0,0 +1,181 @@
/*******************************************************************************************
*
* raylib [shaders] example - fog
*
* NOTE: This example requires raylib OpenGL 3.3 or ES2 versions for shaders support,
* OpenGL 1.1 does not support shaders, recompile raylib to OpenGL 3.3 version.
*
* NOTE: Shaders used in this example are #version 330 (OpenGL 3.3).
*
* This example has been created using raylib 2.5 (www.raylib.com)
* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details)
*
* Example contributed by Chris Camacho (@codifies) and reviewed by Ramon Santamaria (@raysan5)
*
* Chris Camacho (@codifies - http://bedroomcoders.co.uk/) notes:
*
* This is based on the PBR lighting example, but greatly simplified to aid learning...
* actually there is very little of the PBR example left!
* When I first looked at the bewildering complexity of the PBR example I feared
* I would never understand how I could do simple lighting with raylib however its
* a testement to the authors of raylib (including rlights.h) that the example
* came together fairly quickly.
*
* Copyright (c) 2019 Chris Camacho (@codifies) and Ramon Santamaria (@raysan5)
*
********************************************************************************************/
using System.Numerics;
using static Raylib_cs.Raylib;
using static Raylib_cs.Raymath;
using static Examples.Rlights;
namespace Examples.Shaders;
public class Fog
{
public unsafe static int Main()
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
// Enable Multi Sampling Anti Aliasing 4x (if available)
SetConfigFlags(ConfigFlags.FLAG_MSAA_4X_HINT);
InitWindow(screenWidth, screenHeight, "raylib [shaders] example - fog");
// Define the camera to look into our 3d world
Camera3D 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.CAMERA_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");
// Assign texture to default model material
Raylib.SetMaterialTexture(ref modelA, 0, MaterialMapIndex.MATERIAL_MAP_ALBEDO, ref texture);
Raylib.SetMaterialTexture(ref modelB, 0, MaterialMapIndex.MATERIAL_MAP_ALBEDO, ref texture);
Raylib.SetMaterialTexture(ref modelC, 0, MaterialMapIndex.MATERIAL_MAP_ALBEDO, ref texture);
// Load shader and set up some uniforms
Shader shader = LoadShader("resources/shaders/glsl330/lighting.vs", "resources/shaders/glsl330/fog.fs");
shader.Locs[(int)ShaderLocationIndex.SHADER_LOC_MATRIX_MODEL] = GetShaderLocation(shader, "matModel");
shader.Locs[(int)ShaderLocationIndex.SHADER_LOC_VECTOR_VIEW] = GetShaderLocation(shader, "viewPos");
// Ambient light level
int ambientLoc = GetShaderLocation(shader, "ambient");
Raylib.SetShaderValue(
shader,
ambientLoc,
new float[] { 0.2f, 0.2f, 0.2f, 1.0f },
ShaderUniformDataType.SHADER_UNIFORM_VEC4
);
float fogDensity = 0.15f;
int fogDensityLoc = GetShaderLocation(shader, "fogDensity");
Raylib.SetShaderValue(shader, fogDensityLoc, fogDensity, ShaderUniformDataType.SHADER_UNIFORM_FLOAT);
// NOTE: All models share the same shader
Raylib.SetMaterialShader(ref modelA, 0, ref shader);
Raylib.SetMaterialShader(ref modelB, 0, ref shader);
Raylib.SetMaterialShader(ref modelC, 0, ref shader);
// Using just 1 point lights
CreateLight(0, LightType.Point, new Vector3(0, 2, 6), Vector3.Zero, Color.WHITE, shader);
SetTargetFPS(60);
//--------------------------------------------------------------------------------------
// Main game loop
while (!WindowShouldClose())
{
// Update
//----------------------------------------------------------------------------------
UpdateCamera(ref camera, CameraMode.CAMERA_ORBITAL);
if (IsKeyDown(KeyboardKey.KEY_UP))
{
fogDensity += 0.001f;
if (fogDensity > 1.0f)
{
fogDensity = 1.0f;
}
}
if (IsKeyDown(KeyboardKey.KEY_DOWN))
{
fogDensity -= 0.001f;
if (fogDensity < 0.0f)
{
fogDensity = 0.0f;
}
}
Raylib.SetShaderValue(shader, fogDensityLoc, fogDensity, ShaderUniformDataType.SHADER_UNIFORM_FLOAT);
// Rotate the torus
modelA.Transform = MatrixMultiply(modelA.Transform, MatrixRotateX(-0.025f));
modelA.Transform = MatrixMultiply(modelA.Transform, MatrixRotateZ(0.012f));
// Update the light shader with the camera view position
Raylib.SetShaderValue(
shader,
shader.Locs[(int)ShaderLocationIndex.SHADER_LOC_VECTOR_VIEW],
camera.Position,
ShaderUniformDataType.SHADER_UNIFORM_VEC3
);
//----------------------------------------------------------------------------------
// Draw
//----------------------------------------------------------------------------------
BeginDrawing();
ClearBackground(Color.GRAY);
BeginMode3D(camera);
// Draw the three models
DrawModel(modelA, Vector3.Zero, 1.0f, Color.WHITE);
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)
{
DrawModel(modelA, new Vector3(i, 0, 2), 1.0f, Color.WHITE);
}
EndMode3D();
DrawText(
$"Use up/down to change fog density [{fogDensity:F2}]",
10,
10,
20,
Color.RAYWHITE
);
EndDrawing();
//----------------------------------------------------------------------------------
}
// De-Initialization
//--------------------------------------------------------------------------------------
UnloadModel(modelA);
UnloadModel(modelB);
UnloadModel(modelC);
UnloadTexture(texture);
UnloadShader(shader);
CloseWindow();
//--------------------------------------------------------------------------------------
return 0;
}
}

View File

@ -0,0 +1,138 @@
/*******************************************************************************************
*
* raylib [shaders] example - Hot reloading
*
* 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 3.0 (www.raylib.com)
* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details)
*
* Copyright (c) 2020 Ramon Santamaria (@raysan5)
*
********************************************************************************************/
using System.Numerics;
using static Raylib_cs.Raylib;
namespace Examples.Shaders;
public class HotReloading
{
public static int Main()
{
// 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);
// Load raymarching shader
// NOTE: Defining 0 (NULL) for vertex shader forces usage of internal default vertex shader
Shader 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");
float[] resolution = new[] { (float)screenWidth, (float)screenHeight };
Raylib.SetShaderValue(shader, resolutionLoc, resolution, ShaderUniformDataType.SHADER_UNIFORM_VEC2);
float totalTime = 0.0f;
bool shaderAutoReloading = false;
SetTargetFPS(60);
//--------------------------------------------------------------------------------------
// Main game loop
while (!WindowShouldClose())
{
// Update
//----------------------------------------------------------------------------------
totalTime += GetFrameTime();
Vector2 mouse = GetMousePosition();
float[] mousePos = new[] { mouse.X, mouse.Y };
// Set shader required uniform values
Raylib.SetShaderValue(shader, timeLoc, totalTime, ShaderUniformDataType.SHADER_UNIFORM_FLOAT);
Raylib.SetShaderValue(shader, mouseLoc, mousePos, ShaderUniformDataType.SHADER_UNIFORM_VEC2);
// Hot shader reloading
if (shaderAutoReloading || (IsMouseButtonPressed(MouseButton.MOUSE_LEFT_BUTTON)))
{
long currentFragShaderModTime = GetFileModTime(fragShaderFileName);
// Check if shader file has been modified
if (currentFragShaderModTime != fragShaderFileModTime)
{
// Try reloading updated shader
Shader updatedShader = LoadShader(null, fragShaderFileName);
// It was correctly loaded
if (updatedShader.Id != 0) //rlGetShaderIdDefault())
{
UnloadShader(shader);
shader = updatedShader;
// Get shader locations for required uniforms
resolutionLoc = GetShaderLocation(shader, "resolution");
mouseLoc = GetShaderLocation(shader, "mouse");
timeLoc = GetShaderLocation(shader, "time");
// Reset required uniforms
Raylib.SetShaderValue(
shader,
resolutionLoc,
resolution,
ShaderUniformDataType.SHADER_UNIFORM_VEC2
);
}
fragShaderFileModTime = currentFragShaderModTime;
}
}
if (IsKeyPressed(KeyboardKey.KEY_A))
{
shaderAutoReloading = !shaderAutoReloading;
}
//----------------------------------------------------------------------------------
// Draw
//----------------------------------------------------------------------------------
BeginDrawing();
ClearBackground(Color.RAYWHITE);
// We only draw a white full-screen rectangle, frame is generated in shader
BeginShaderMode(shader);
DrawRectangle(0, 0, screenWidth, screenHeight, Color.WHITE);
EndShaderMode();
string 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);
EndDrawing();
//----------------------------------------------------------------------------------
}
// De-Initialization
//--------------------------------------------------------------------------------------
UnloadShader(shader);
CloseWindow();
//--------------------------------------------------------------------------------------
return 0;
}
}

View File

@ -0,0 +1,235 @@
/*******************************************************************************************
*
* raylib [shaders] example - Hybrid Rendering
*
* Example originally created with raylib 4.2, last time updated with raylib 4.2
*
* Example contributed by Buğra Alptekin Sarı (@BugraAlptekinSari) 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) 2022-2023 Buğra Alptekin Sarı (@BugraAlptekinSari)
*
********************************************************************************************/
using System;
using System.Numerics;
using static Raylib_cs.Raylib;
namespace Examples.Shaders;
public class HybridRender
{
struct RayLocs
{
public int CamPos;
public int CamDir;
public int ScreenCenter;
}
const int GLSL_VERSION = 330;
public static int Main()
{
// 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 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");
// Declare struct used to store camera locs
RayLocs marchLocs = new();
// 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);
SetShaderValue(
shdrRaymarch,
marchLocs.ScreenCenter,
screenCenter,
ShaderUniformDataType.SHADER_UNIFORM_VEC2
);
// 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(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.CAMERA_PERSPECTIVE;
// Camera FOV is pre-calculated in the camera Distance.
float camDist = 1.0f / (MathF.Tan(camera.FovY * 0.5f * Raylib.DEG2RAD));
SetTargetFPS(60);
//--------------------------------------------------------------------------------------
// Main game loop
while (!WindowShouldClose())
{
// Update
//----------------------------------------------------------------------------------
UpdateCamera(ref camera, CameraMode.CAMERA_ORBITAL);
// Update Camera Postion in the ray march shader.
SetShaderValue(
shdrRaymarch,
marchLocs.CamPos,
camera.Position,
ShaderUniformDataType.SHADER_UNIFORM_VEC3
);
// Update Camera Looking Vector. Vector length determines FOV.
Vector3 camDir = Vector3.Normalize(camera.Target - camera.Position) * camDist;
SetShaderValue(shdrRaymarch, marchLocs.CamDir, camDir, ShaderUniformDataType.SHADER_UNIFORM_VEC3);
//----------------------------------------------------------------------------------
// Draw
//----------------------------------------------------------------------------------
// Draw into our custom render texture (framebuffer)
BeginTextureMode(target);
ClearBackground(Color.WHITE);
// Raymarch Scene
// Manually enable Depth Test to handle multiple rendering methods.
Rlgl.EnableDepthTest();
BeginShaderMode(shdrRaymarch);
DrawRectangleRec(new Rectangle(0, 0, screenWidth, screenHeight), Color.WHITE);
EndShaderMode();
// Rasterize Scene
BeginMode3D(camera);
BeginShaderMode(shdrRaster);
DrawCubeWiresV(new Vector3(0.0f, 0.5f, 1.0f), new Vector3(1.0f, 1.0f, 1.0f), Color.RED);
DrawCubeV(new Vector3(0.0f, 0.5f, 1.0f), new Vector3(1.0f, 1.0f, 1.0f), Color.PURPLE);
DrawCubeWiresV(new Vector3(0.0f, 0.5f, -1.0f), new Vector3(1.0f, 1.0f, 1.0f), Color.DARKGREEN);
DrawCubeV(new Vector3(0.0f, 0.5f, -1.0f), new Vector3(1.0f, 1.0f, 1.0f), Color.YELLOW);
DrawGrid(10, 1.0f);
EndShaderMode();
EndMode3D();
EndTextureMode();
// Draw custom render texture
BeginDrawing();
ClearBackground(Color.RAYWHITE);
DrawTextureRec(
target.Texture,
new Rectangle(0, 0, screenWidth, -screenHeight),
Vector2.Zero,
Color.WHITE
);
DrawFPS(10, 10);
EndDrawing();
//----------------------------------------------------------------------------------
}
// De-Initialization
//--------------------------------------------------------------------------------------
UnloadRenderTextureDepthTex(target);
UnloadShader(shdrRaymarch);
UnloadShader(shdrRaster);
CloseWindow();
//--------------------------------------------------------------------------------------
return 0;
}
// Load custom render texture, create a writable depth texture buffer
private static unsafe RenderTexture2D LoadRenderTextureDepthTex(int width, int height)
{
RenderTexture2D target = new();
// Load an empty framebuffer
target.Id = Rlgl.LoadFramebuffer(width, height);
if (target.Id > 0)
{
Rlgl.EnableFramebuffer(target.Id);
// Create color texture (default to RGBA)
target.Texture.Id = Rlgl.LoadTexture(
null,
width,
height,
PixelFormat.PIXELFORMAT_UNCOMPRESSED_R8G8B8A8,
1
);
target.Texture.Width = width;
target.Texture.Height = height;
target.Texture.Format = PixelFormat.PIXELFORMAT_UNCOMPRESSED_R8G8B8A8;
target.Texture.Mipmaps = 1;
// Create depth texture buffer (instead of raylib default renderbuffer)
target.Depth.Id = Rlgl.LoadTextureDepth(width, height, false);
target.Depth.Width = width;
target.Depth.Height = height;
target.Depth.Format = PixelFormat.PIXELFORMAT_COMPRESSED_PVRT_RGBA;
target.Depth.Mipmaps = 1;
// Attach color texture and depth texture to FBO
Rlgl.FramebufferAttach(
target.Id,
target.Texture.Id,
FramebufferAttachType.RL_ATTACHMENT_COLOR_CHANNEL0,
FramebufferAttachTextureType.RL_ATTACHMENT_TEXTURE2D,
0
);
Rlgl.FramebufferAttach(
target.Id,
target.Depth.Id,
FramebufferAttachType.RL_ATTACHMENT_DEPTH,
FramebufferAttachTextureType.RL_ATTACHMENT_TEXTURE2D,
0
);
// Check if fbo is complete with attachments (valid)
if (Rlgl.FramebufferComplete(target.Id))
{
TraceLog(TraceLogLevel.LOG_INFO, $"FBO: [ID {target.Id}] Framebuffer object created successfully");
}
Rlgl.DisableFramebuffer();
}
else
{
TraceLog(TraceLogLevel.LOG_WARNING, "FBO: Framebuffer object can not be created");
}
return target;
}
// Unload render texture from GPU memory (VRAM)
private static void UnloadRenderTextureDepthTex(RenderTexture2D target)
{
if (target.Id > 0)
{
// Color texture attached to FBO is deleted
Rlgl.UnloadTexture(target.Texture.Id);
Rlgl.UnloadTexture(target.Depth.Id);
// NOTE: Depth texture is automatically
// queried and deleted before deleting framebuffer
Rlgl.UnloadFramebuffer(target.Id);
}
}
}

View File

@ -0,0 +1,248 @@
/*******************************************************************************************
*
* raylib [shaders] example - julia sets
*
* NOTE: This example requires raylib OpenGL 3.3 or ES2 versions for shaders support,
* OpenGL 1.1 does not support shaders, recompile raylib to OpenGL 3.3 version.
*
* NOTE: Shaders used in this example are #version 330 (OpenGL 3.3).
*
* This example has been created using raylib 2.5 (www.raylib.com)
* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details)
*
* Example contributed by eggmund (@eggmund) and reviewed by Ramon Santamaria (@raysan5)
*
* Copyright (c) 2019 eggmund (@eggmund) and Ramon Santamaria (@raysan5)
*
********************************************************************************************/
using System.Numerics;
using static Raylib_cs.Raylib;
namespace Examples.Shaders;
public class JuliaSet
{
const int GlslVersion = 330;
// A few good julia sets
static float[][] PointsOfInterest = new float[][] {
new float[] { -0.348827f, 0.607167f },
new float[] { -0.786268f, 0.169728f },
new float[] { -0.8f, 0.156f },
new float[] { 0.285f, 0.0f },
new float[] { -0.835f, -0.2321f },
new float[] { -0.70176f, -0.3842f },
};
public static int Main()
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
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");
// c constant to use in z^2 + c
float[] c = { PointsOfInterest[0][0], PointsOfInterest[0][1] };
// Offset and zoom to draw the julia set at. (centered on screen and default size)
float[] offset = { -(float)screenWidth / 2, -(float)screenHeight / 2 };
float zoom = 1.0f;
Vector2 offsetSpeed = new(0.0f, 0.0f);
// 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");
// Tell the shader what the screen dimensions, zoom, offset and c are
float[] screenDims = { (float)screenWidth, (float)screenHeight };
Raylib.SetShaderValue(
shader,
GetShaderLocation(shader, "screenDims"),
screenDims,
ShaderUniformDataType.SHADER_UNIFORM_VEC2
);
Raylib.SetShaderValue(shader, cLoc, c, ShaderUniformDataType.SHADER_UNIFORM_VEC2);
Raylib.SetShaderValue(shader, zoomLoc, zoomLoc, ShaderUniformDataType.SHADER_UNIFORM_FLOAT);
Raylib.SetShaderValue(shader, offsetLoc, offset, ShaderUniformDataType.SHADER_UNIFORM_VEC2);
// Create a RenderTexture2D to be used for render to texture
RenderTexture2D target = LoadRenderTexture(screenWidth, screenHeight);
// Multiplier of speed to change c value
int incrementSpeed = 0;
// Show controls
bool showControls = true;
// Pause animation
bool pause = false;
SetTargetFPS(60);
//--------------------------------------------------------------------------------------
// Main game loop
while (!WindowShouldClose())
{
// Update
//----------------------------------------------------------------------------------
// Press [1 - 6] to reset c to a point of interest
if (IsKeyPressed(KeyboardKey.KEY_ONE) ||
IsKeyPressed(KeyboardKey.KEY_TWO) ||
IsKeyPressed(KeyboardKey.KEY_THREE) ||
IsKeyPressed(KeyboardKey.KEY_FOUR) ||
IsKeyPressed(KeyboardKey.KEY_FIVE) ||
IsKeyPressed(KeyboardKey.KEY_SIX))
{
if (IsKeyPressed(KeyboardKey.KEY_ONE))
{
c[0] = PointsOfInterest[0][0];
c[1] = PointsOfInterest[0][1];
}
else if (IsKeyPressed(KeyboardKey.KEY_TWO))
{
c[0] = PointsOfInterest[1][0];
c[1] = PointsOfInterest[1][1];
}
else if (IsKeyPressed(KeyboardKey.KEY_THREE))
{
c[0] = PointsOfInterest[2][0];
c[1] = PointsOfInterest[2][1];
}
else if (IsKeyPressed(KeyboardKey.KEY_FOUR))
{
c[0] = PointsOfInterest[3][0];
c[1] = PointsOfInterest[3][1];
}
else if (IsKeyPressed(KeyboardKey.KEY_FIVE))
{
c[0] = PointsOfInterest[4][0];
c[1] = PointsOfInterest[4][1];
}
else if (IsKeyPressed(KeyboardKey.KEY_SIX))
{
c[0] = PointsOfInterest[5][0];
c[1] = PointsOfInterest[5][1];
}
Raylib.SetShaderValue(shader, cLoc, c, ShaderUniformDataType.SHADER_UNIFORM_VEC2);
}
// Pause animation (c change)
if (IsKeyPressed(KeyboardKey.KEY_SPACE))
{
pause = !pause;
}
// Toggle whether or not to show controls
if (IsKeyPressed(KeyboardKey.KEY_F1))
{
showControls = !showControls;
}
if (!pause)
{
if (IsKeyPressed(KeyboardKey.KEY_RIGHT))
{
incrementSpeed++;
}
else if (IsKeyPressed(KeyboardKey.KEY_LEFT))
{
incrementSpeed--;
}
// TODO: The idea is to zoom and move around with mouse
// Probably offset movement should be proportional to zoom level
if (IsMouseButtonDown(MouseButton.MOUSE_LEFT_BUTTON) || IsMouseButtonDown(MouseButton.MOUSE_RIGHT_BUTTON))
{
if (IsMouseButtonDown(MouseButton.MOUSE_LEFT_BUTTON))
{
zoom += zoom * 0.003f;
}
if (IsMouseButtonDown(MouseButton.MOUSE_RIGHT_BUTTON))
{
zoom -= zoom * 0.003f;
}
Vector2 mousePos = GetMousePosition();
offsetSpeed.X = mousePos.X - (float)screenWidth / 2;
offsetSpeed.Y = mousePos.Y - (float)screenHeight / 2;
// Slowly move camera to targetOffset
offset[0] += GetFrameTime() * offsetSpeed.X * 0.8f;
offset[1] += GetFrameTime() * offsetSpeed.Y * 0.8f;
}
else
{
offsetSpeed = new Vector2(0.0f, 0.0f);
}
Raylib.SetShaderValue(shader, zoomLoc, zoom, ShaderUniformDataType.SHADER_UNIFORM_FLOAT);
Raylib.SetShaderValue(shader, offsetLoc, offset, ShaderUniformDataType.SHADER_UNIFORM_VEC2);
// Increment c value with time
float amount = GetFrameTime() * incrementSpeed * 0.0005f;
c[0] += amount;
c[1] += amount;
Raylib.SetShaderValue(shader, cLoc, c, ShaderUniformDataType.SHADER_UNIFORM_VEC2);
}
//----------------------------------------------------------------------------------
// Draw
//----------------------------------------------------------------------------------
BeginDrawing();
ClearBackground(Color.BLACK);
// 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,
// 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 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);
EndShaderMode();
if (showControls)
{
DrawText("Press Mouse buttons right/left to zoom in/out and move", 10, 15, 10, Color.RAYWHITE);
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);
}
EndDrawing();
//----------------------------------------------------------------------------------
}
// De-Initialization
//--------------------------------------------------------------------------------------
UnloadShader(shader);
UnloadRenderTexture(target);
CloseWindow();
//--------------------------------------------------------------------------------------
return 0;
}
}

View File

@ -0,0 +1,326 @@
/*******************************************************************************************
*
* raylib [shaders] example - rlgl module usage for instanced meshes
*
* This example uses [rlgl] module funtionality (pseudo-OpenGL 1.1 style coding)
*
* 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 contributed by @seanpringle and reviewed by Ramon Santamaria (@raysan5)
*
* Copyright (c) 2020 @seanpringle
*
********************************************************************************************/
using System;
using System.Numerics;
using static Raylib_cs.Raylib;
namespace Examples.Shaders;
public class MeshInstancing
{
public static int Main()
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
const int fps = 60;
// Enable Multi Sampling Anti Aliasing 4x (if available)
SetConfigFlags(ConfigFlags.FLAG_MSAA_4X_HINT);
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.CAMERA_PERSPECTIVE;
// Number of instances to display
const int instances = 10000;
Mesh 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];
// Scatter random cubes around
for (int i = 0; i < instances; i++)
{
x = GetRandomValue(-50, 50);
y = GetRandomValue(-50, 50);
z = GetRandomValue(-50, 50);
translations[i] = Matrix4x4.CreateTranslation(x, y, z);
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;
}
// 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"
);
// Get some shader loactions
unsafe
{
int* locs = (int*)shader.Locs;
locs[(int)ShaderLocationIndex.SHADER_LOC_MATRIX_MVP] = GetShaderLocation(shader, "mvp");
locs[(int)ShaderLocationIndex.SHADER_LOC_VECTOR_VIEW] = GetShaderLocation(shader, "viewPos");
locs[(int)ShaderLocationIndex.SHADER_LOC_MATRIX_MODEL] = GetShaderLocationAttrib(
shader,
"instanceTransform"
);
}
// Ambient light level
int ambientLoc = GetShaderLocation(shader, "ambient");
Raylib.SetShaderValue(
shader,
ambientLoc,
new float[] { 0.2f, 0.2f, 0.2f, 1.0f },
ShaderUniformDataType.SHADER_UNIFORM_VEC4
);
Rlights.CreateLight(
0,
LightType.Directorional,
new Vector3(50, 50, 0),
Vector3.Zero,
Color.WHITE,
shader
);
Material material = LoadMaterialDefault();
material.Shader = shader;
unsafe
{
material.Maps[(int)MaterialMapIndex.MATERIAL_MAP_DIFFUSE].Color = Color.RED;
}
int textPositionY = 300;
// Simple frames counter to manage animation
int framesCounter = 0;
SetTargetFPS(fps);
//--------------------------------------------------------------------------------------
// Main game loop
while (!WindowShouldClose())
{
// Update
//----------------------------------------------------------------------------------
UpdateCamera(ref camera, CameraMode.CAMERA_FREE);
textPositionY = 300;
framesCounter += 1;
if (IsKeyDown(KeyboardKey.KEY_UP))
{
amp += 0.5f;
}
if (IsKeyDown(KeyboardKey.KEY_DOWN))
{
amp = (amp <= 1) ? 1.0f : (amp - 1.0f);
}
if (IsKeyDown(KeyboardKey.KEY_LEFT))
{
variance = (variance <= 0.0f) ? 0.0f : (variance - 0.01f);
}
if (IsKeyDown(KeyboardKey.KEY_RIGHT))
{
variance = (variance >= 1.0f) ? 1.0f : (variance + 0.01f);
}
if (IsKeyDown(KeyboardKey.KEY_ONE))
{
groups = 1;
}
if (IsKeyDown(KeyboardKey.KEY_TWO))
{
groups = 2;
}
if (IsKeyDown(KeyboardKey.KEY_THREE))
{
groups = 3;
}
if (IsKeyDown(KeyboardKey.KEY_FOUR))
{
groups = 4;
}
if (IsKeyDown(KeyboardKey.KEY_FIVE))
{
groups = 5;
}
if (IsKeyDown(KeyboardKey.KEY_SIX))
{
groups = 6;
}
if (IsKeyDown(KeyboardKey.KEY_SEVEN))
{
groups = 7;
}
if (IsKeyDown(KeyboardKey.KEY_EIGHT))
{
groups = 8;
}
if (IsKeyDown(KeyboardKey.KEY_NINE))
{
groups = 9;
}
if (IsKeyDown(KeyboardKey.KEY_W))
{
groups = 7;
amp = 25;
speed = 18;
variance = 0.70f;
}
if (IsKeyDown(KeyboardKey.KEY_EQUAL))
{
speed = (speed <= (int)(fps * 0.25f)) ? (int)(fps * 0.25f) : (int)(speed * 0.95f);
}
if (IsKeyDown(KeyboardKey.KEY_KP_ADD))
{
speed = (speed <= (int)(fps * 0.25f)) ? (int)(fps * 0.25f) : (int)(speed * 0.95f);
}
if (IsKeyDown(KeyboardKey.KEY_MINUS))
{
speed = (int)MathF.Max(speed * 1.02f, speed + 1);
}
if (IsKeyDown(KeyboardKey.KEY_KP_SUBTRACT))
{
speed = (int)MathF.Max(speed * 1.02f, speed + 1);
}
// 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.SHADER_LOC_VECTOR_VIEW,
cameraPos,
ShaderUniformDataType.SHADER_UNIFORM_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);
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();
//----------------------------------------------------------------------------------
}
// De-Initialization
//--------------------------------------------------------------------------------------
CloseWindow();
//--------------------------------------------------------------------------------------
return 0;
}
}

View File

@ -0,0 +1,108 @@
/*******************************************************************************************
*
* raylib [shaders] example - Apply a shader to a 3d model
*
* NOTE: This example requires raylib OpenGL 3.3 or ES2 versions for shaders support,
* OpenGL 1.1 does not support shaders, recompile raylib to OpenGL 3.3 version.
*
* NOTE: Shaders used in this example are #version 330 (OpenGL 3.3), 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)
*
* Copyright (c) 2014 Ramon Santamaria (@raysan5)
*
********************************************************************************************/
using System.Numerics;
using static Raylib_cs.Raylib;
namespace Examples.Shaders;
public class ModelShader
{
public static int Main()
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
// Enable Multi Sampling Anti Aliasing 4x (if available)
SetConfigFlags(ConfigFlags.FLAG_MSAA_4X_HINT);
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.CAMERA_PERSPECTIVE;
Model model = LoadModel("resources/models/watermill.obj");
Texture2D texture = LoadTexture("resources/models/watermill_diffuse.png");
Shader shader = LoadShader("resources/shaders/glsl330/base.vs",
"resources/shaders/glsl330/grayscale.fs");
Raylib.SetMaterialShader(ref model, 0, ref shader);
Raylib.SetMaterialTexture(ref model, 0, MaterialMapIndex.MATERIAL_MAP_ALBEDO, ref texture);
Vector3 position = new(0.0f, 0.0f, 0.0f);
SetTargetFPS(60);
//--------------------------------------------------------------------------------------
// Main game loop
while (!WindowShouldClose())
{
// Update
//----------------------------------------------------------------------------------
UpdateCamera(ref camera, CameraMode.CAMERA_FREE);
//----------------------------------------------------------------------------------
// Draw
//----------------------------------------------------------------------------------
BeginDrawing();
ClearBackground(Color.RAYWHITE);
BeginMode3D(camera);
DrawModel(model, position, 0.2f, Color.WHITE);
DrawGrid(10, 1.0f);
EndMode3D();
DrawText(
"(c) Watermill 3D model by Alberto Cano",
screenWidth - 210,
screenHeight - 20,
10,
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();
//----------------------------------------------------------------------------------
}
// De-Initialization
//--------------------------------------------------------------------------------------
UnloadShader(shader);
UnloadTexture(texture);
UnloadModel(model);
CloseWindow();
//--------------------------------------------------------------------------------------
return 0;
}
}

View File

@ -0,0 +1,116 @@
/*******************************************************************************************
*
* raylib [shaders] example - Multiple sample2D with default batch system
*
* NOTE: This example requires raylib OpenGL 3.3 or ES2 versions for shaders support,
* OpenGL 1.1 does not support shaders, recompile raylib to OpenGL 3.3 version.
*
* NOTE: Shaders used in this example are #version 330 (OpenGL 3.3), 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)
*
* Copyright (c) 2020 Ramon Santamaria (@raysan5)
*
********************************************************************************************/
using static Raylib_cs.Raylib;
namespace Examples.Shaders;
public class MultiSample2d
{
public static int Main()
{
// 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);
UnloadImage(imRed);
Image imBlue = GenImageColor(800, 450, new Color(0, 0, 255, 255));
Texture2D texBlue = LoadTextureFromImage(imBlue);
UnloadImage(imBlue);
Shader shader = LoadShader(null, "resources/shaders/glsl330/color_mix.fs");
// Get an additional sampler2D location to be enabled on drawing
int texBlueLoc = GetShaderLocation(shader, "texture1");
// Get shader uniform for divider
int dividerLoc = GetShaderLocation(shader, "divider");
float dividerValue = 0.5f;
SetTargetFPS(60);
//--------------------------------------------------------------------------------------
// Main game loop
while (!WindowShouldClose())
{
// Update
//----------------------------------------------------------------------------------
if (IsKeyDown(KeyboardKey.KEY_RIGHT))
{
dividerValue += 0.01f;
}
else if (IsKeyDown(KeyboardKey.KEY_LEFT))
{
dividerValue -= 0.01f;
}
if (dividerValue < 0.0f)
{
dividerValue = 0.0f;
}
else if (dividerValue > 1.0f)
{
dividerValue = 1.0f;
}
Raylib.SetShaderValue(shader, dividerLoc, dividerValue, ShaderUniformDataType.SHADER_UNIFORM_FLOAT);
//----------------------------------------------------------------------------------
// Draw
//----------------------------------------------------------------------------------
BeginDrawing();
ClearBackground(Color.RAYWHITE);
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)
SetShaderValueTexture(shader, texBlueLoc, texBlue);
// 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();
int y = GetScreenHeight() - 40;
DrawText("Use KEY_LEFT/KEY_RIGHT to move texture mixing in shader!", 80, y, 20, Color.RAYWHITE);
EndDrawing();
//----------------------------------------------------------------------------------
}
// De-Initialization
//--------------------------------------------------------------------------------------
UnloadShader(shader);
UnloadTexture(texRed);
UnloadTexture(texBlue);
CloseWindow();
//--------------------------------------------------------------------------------------
return 0;
}
}

View File

@ -0,0 +1,166 @@
/*******************************************************************************************
*
* raylib [shaders] example - Color palette switch
*
* NOTE: This example requires raylib OpenGL 3.3 or ES2 versions for shaders support,
* OpenGL 1.1 does not support shaders, recompile raylib to OpenGL 3.3 version.
*
* NOTE: Shaders used in this example are #version 330 (OpenGL 3.3), 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 contributed by Marco Lizza (@MarcoLizza) and reviewed by Ramon Santamaria (@raysan5)
*
* Copyright (c) 2019 Marco Lizza (@MarcoLizza) and Ramon Santamaria (@raysan5)
*
********************************************************************************************/
using static Raylib_cs.Raylib;
namespace Examples.Shaders;
public class PaletteSwitch
{
const int GlslVersion = 330;
const int ColorsPerPalette = 8;
const int VALUES_PER_COLOR = 3;
static int[][] Palettes = new int[][] {
// 3-BIT RGB
new int[] {
0, 0, 0,
255, 0, 0,
0, 255, 0,
0, 0, 255,
0, 255, 255,
255, 0, 255,
255, 255, 0,
255, 255, 255,
},
// AMMO-8 (GameBoy-like)
new int[] {
4, 12, 6,
17, 35, 24,
30, 58, 41,
48, 93, 66,
77, 128, 97,
137, 162, 87,
190, 220, 127,
238, 255, 204,
},
// RKBV (2-strip film)
new int[] {
21, 25, 26,
138, 76, 88,
217, 98, 117,
230, 184, 193,
69, 107, 115,
75, 151, 166,
165, 189, 194,
255, 245, 247,
}
};
static string[] PaletteText = new string[] {
"3-BIT RGB",
"AMMO-8 (GameBoy-like)",
"RKBV (2-strip film)"
};
public static int Main()
{
// 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");
// 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");
int currentPalette = 0;
int lineHeight = screenHeight / ColorsPerPalette;
SetTargetFPS(60);
//--------------------------------------------------------------------------------------
// Main game loop
while (!WindowShouldClose())
{
// Update
//----------------------------------------------------------------------------------
if (IsKeyPressed(KeyboardKey.KEY_RIGHT))
{
currentPalette++;
}
else if (IsKeyPressed(KeyboardKey.KEY_LEFT))
{
currentPalette--;
}
if (currentPalette >= Palettes.Length)
{
currentPalette = 0;
}
else if (currentPalette < 0)
{
currentPalette = Palettes.Length - 1;
}
// Send new value to the shader to be used on drawing.
// NOTE: We are sending RGB triplets w/o the alpha channel
Raylib.SetShaderValueV(
shader,
paletteLoc,
Palettes[currentPalette],
ShaderUniformDataType.SHADER_UNIFORM_IVEC3,
ColorsPerPalette
);
//----------------------------------------------------------------------------------
// Draw
//----------------------------------------------------------------------------------
BeginDrawing();
ClearBackground(Color.RAYWHITE);
BeginShaderMode(shader);
for (int 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
DrawRectangle(0, lineHeight * i, GetScreenWidth(), lineHeight, new Color(i, i, i, 255));
}
EndShaderMode();
DrawText("< >", 10, 10, 30, Color.DARKBLUE);
DrawText("CURRENT PALETTE:", 60, 15, 20, Color.RAYWHITE);
DrawText(PaletteText[currentPalette], 300, 15, 20, Color.RED);
DrawFPS(700, 15);
EndDrawing();
//----------------------------------------------------------------------------------
}
// De-Initialization
//--------------------------------------------------------------------------------------
UnloadShader(shader);
CloseWindow();
//--------------------------------------------------------------------------------------
return 0;
}
}

View File

@ -0,0 +1,206 @@
/*******************************************************************************************
*
* raylib [shaders] example - Apply a postprocessing shader to a scene
*
* NOTE: This example requires raylib OpenGL 3.3 or ES2 versions for shaders support,
* OpenGL 1.1 does not support shaders, recompile raylib to OpenGL 3.3 version.
*
* NOTE: Shaders used in this example are #version 330 (OpenGL 3.3), 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)
*
* Copyright (c) 2015 Ramon Santamaria (@raysan5)
*
********************************************************************************************/
using System.Numerics;
using static Raylib_cs.Raylib;
namespace Examples.Shaders;
public class PostProcessing
{
public const int GLSL_VERSION = 330;
enum PostproShader
{
FxGrayScale = 0,
FxPosterization,
FxDreamVision,
FxPixelizer,
FxCrossHatching,
FxCrossStiching,
FxPredatorView,
FxScanLines,
FxFishEye,
FxSobel,
FxBloom,
FxBlur,
//FX_FXAA
Max
}
static string[] postproShaderText = new string[] {
"GRAYSCALE",
"POSTERIZATION",
"DREAM_VISION",
"PIXELIZER",
"CROSS_HATCHING",
"CROSS_STITCHING",
"PREDATOR_VIEW",
"SCANLINES",
"FISHEYE",
"SOBEL",
"BLOOM",
"BLUR",
//"FXAA"
};
public static int Main()
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
// Enable Multi Sampling Anti Aliasing 4x (if available)
SetConfigFlags(ConfigFlags.FLAG_MSAA_4X_HINT);
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.CAMERA_PERSPECTIVE;
Model model = LoadModel("resources/models/church.obj");
Texture2D texture = LoadTexture("resources/models/church_diffuse.png");
// Set model diffuse texture
Raylib.SetMaterialTexture(ref model, 0, MaterialMapIndex.MATERIAL_MAP_ALBEDO, ref texture);
Vector3 position = new(0.0f, 0.0f, 0.0f);
// 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];
// NOTE: Defining null (NULL) for vertex shader forces usage of internal default vertex shader
string shaderPath = "resources/shaders/glsl330";
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");
shaders[(int)PostproShader.FxPixelizer] = LoadShader(null, $"{shaderPath}/pixelizer.fs");
shaders[(int)PostproShader.FxCrossHatching] = LoadShader(null, $"{shaderPath}/cross_hatching.fs");
shaders[(int)PostproShader.FxCrossStiching] = LoadShader(null, $"{shaderPath}/cross_stitching.fs");
shaders[(int)PostproShader.FxPredatorView] = LoadShader(null, $"{shaderPath}/predator.fs");
shaders[(int)PostproShader.FxScanLines] = LoadShader(null, $"{shaderPath}/scanlines.fs");
shaders[(int)PostproShader.FxFishEye] = LoadShader(null, $"{shaderPath}/fisheye.fs");
shaders[(int)PostproShader.FxSobel] = LoadShader(null, $"{shaderPath}/sobel.fs");
shaders[(int)PostproShader.FxBloom] = LoadShader(null, $"{shaderPath}/bloom.fs");
shaders[(int)PostproShader.FxBlur] = LoadShader(null, $"{shaderPath}/blur.fs");
int currentShader = (int)PostproShader.FxGrayScale;
// Create a RenderTexture2D to be used for render to texture
RenderTexture2D target = LoadRenderTexture(screenWidth, screenHeight);
SetTargetFPS(60);
//--------------------------------------------------------------------------------------
// Main game loop
while (!WindowShouldClose())
{
// Update
//----------------------------------------------------------------------------------
UpdateCamera(ref camera, CameraMode.CAMERA_ORBITAL);
if (IsKeyPressed(KeyboardKey.KEY_RIGHT))
{
currentShader++;
}
else if (IsKeyPressed(KeyboardKey.KEY_LEFT))
{
currentShader--;
}
if (currentShader >= (int)PostproShader.Max)
{
currentShader = 0;
}
else if (currentShader < 0)
{
currentShader = (int)PostproShader.Max - 1;
}
//----------------------------------------------------------------------------------
// Draw
//----------------------------------------------------------------------------------
BeginDrawing();
ClearBackground(Color.RAYWHITE);
// Enable drawing to texture
BeginTextureMode(target);
ClearBackground(Color.RAYWHITE);
BeginMode3D(camera);
DrawModel(model, position, 0.1f, Color.WHITE);
DrawGrid(10, 1.0f);
EndMode3D();
// End drawing to texture (now we have a texture available for next passes)
EndTextureMode();
// Render previously generated texture using selected postpro shader
BeginShaderMode(shaders[currentShader]);
// NOTE: Render texture must be y-flipped due to default OpenGL coordinates (left-bottom)
DrawTextureRec(
target.Texture,
new Rectangle(0, 0, target.Texture.Width, -target.Texture.Height),
new Vector2(0, 0),
Color.WHITE
);
EndShaderMode();
DrawRectangle(0, 9, 580, 30, ColorAlpha(Color.LIGHTGRAY, 0.7f));
DrawText("(c) Church 3D model by Alberto Cano", screenWidth - 200, screenHeight - 20, 10, Color.GRAY);
DrawText("CURRENT POSTPRO SHADER:", 10, 15, 20, Color.BLACK);
DrawText(postproShaderText[currentShader], 330, 15, 20, Color.RED);
DrawText("< >", 540, 10, 30, Color.DARKBLUE);
DrawFPS(700, 15);
EndDrawing();
//----------------------------------------------------------------------------------
}
// De-Initialization
//--------------------------------------------------------------------------------------
for (int i = 0; i < (int)PostproShader.Max; i++)
{
UnloadShader(shaders[i]);
}
UnloadTexture(texture);
UnloadModel(model);
UnloadRenderTexture(target);
CloseWindow();
//--------------------------------------------------------------------------------------
return 0;
}
}

View File

@ -0,0 +1,121 @@
/*******************************************************************************************
*
* raylib [shaders] example - Raymarching shapes generation
*
* NOTE: This example requires raylib OpenGL 3.3 or ES2 versions for shaders support,
* OpenGL 1.1 does not support shaders, recompile raylib to OpenGL 3.3 version.
*
* NOTE: Shaders used in this example are #version 330 (OpenGL 3.3), 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.0 (www.raylib.com)
* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details)
*
* Copyright (c) 2018 Ramon Santamaria (@raysan5)
*
********************************************************************************************/
using System.Numerics;
using static Raylib_cs.Raylib;
using static Raylib_cs.ConfigFlags;
namespace Examples.Shaders;
public class Raymarching
{
public const int GlslVersion = 330;
public static int Main()
{
// Initialization
//--------------------------------------------------------------------------------------
int screenWidth = 800;
int screenHeight = 450;
SetConfigFlags(FLAG_WINDOW_RESIZABLE);
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;
// 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");
// 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");
float[] resolution = { (float)screenWidth, (float)screenHeight };
Raylib.SetShaderValue(shader, resolutionLoc, resolution, ShaderUniformDataType.SHADER_UNIFORM_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.SHADER_UNIFORM_VEC2);
}
// Update
//----------------------------------------------------------------------------------
UpdateCamera(ref camera, CameraMode.CAMERA_FREE);
float deltaTime = GetFrameTime();
runTime += deltaTime;
// Set shader required uniform values
Raylib.SetShaderValue(shader, viewEyeLoc, camera.Position, ShaderUniformDataType.SHADER_UNIFORM_VEC3);
Raylib.SetShaderValue(shader, viewCenterLoc, camera.Target, ShaderUniformDataType.SHADER_UNIFORM_VEC3);
Raylib.SetShaderValue(shader, runTimeLoc, runTime, ShaderUniformDataType.SHADER_UNIFORM_FLOAT);
//----------------------------------------------------------------------------------
// Draw
//----------------------------------------------------------------------------------
BeginDrawing();
ClearBackground(Color.RAYWHITE);
// We only draw a white full-screen rectangle,
// frame is generated in shader using raymarching
BeginShaderMode(shader);
DrawRectangle(0, 0, screenWidth, screenHeight, Color.WHITE);
EndShaderMode();
DrawText(
"(c) Raymarching shader by Iñigo Quilez. MIT License.",
screenWidth - 280,
screenHeight - 20,
10,
Color.BLACK
);
EndDrawing();
//----------------------------------------------------------------------------------
}
// De-Initialization
//--------------------------------------------------------------------------------------
UnloadShader(shader);
CloseWindow();
//--------------------------------------------------------------------------------------
return 0;
}
}

View File

@ -0,0 +1,121 @@
/*******************************************************************************************
*
* raylib [shaders] example - Apply a shader to some shape or texture
*
* NOTE: This example requires raylib OpenGL 3.3 or ES2 versions for shaders support,
* OpenGL 1.1 does not support shaders, recompile raylib to OpenGL 3.3 version.
*
* NOTE: Shaders used in this example are #version 330 (OpenGL 3.3), 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)
*
* Copyright (c) 2015 Ramon Santamaria (@raysan5)
*
********************************************************************************************/
using System.Numerics;
using static Raylib_cs.Raylib;
namespace Examples.Shaders;
public class ShapesTextures
{
public static int Main()
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [shaders] example - shapes and texture shaders");
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())
{
// Update
//----------------------------------------------------------------------------------
// TODO: Update your variables here
//----------------------------------------------------------------------------------
// Draw
//----------------------------------------------------------------------------------
BeginDrawing();
ClearBackground(Color.RAYWHITE);
// Start drawing with default shader
DrawText("USING DEFAULT SHADER", 20, 40, 10, Color.RED);
DrawCircle(80, 120, 35, Color.DARKBLUE);
DrawCircleGradient(80, 220, 60, Color.GREEN, Color.SKYBLUE);
DrawCircleLines(80, 340, 80, Color.DARKBLUE);
// Activate our custom shader to be applied on next shapes/textures drawings
BeginShaderMode(shader);
DrawText("USING CUSTOM SHADER", 190, 40, 10, Color.RED);
DrawRectangle(250 - 60, 90, 120, 60, Color.RED);
DrawRectangleGradientH(250 - 90, 170, 180, 130, Color.MAROON, Color.GOLD);
DrawRectangleLines(250 - 40, 320, 80, 60, Color.ORANGE);
// Activate our default shader for next drawings
EndShaderMode();
DrawText("USING DEFAULT SHADER", 370, 40, 10, Color.RED);
DrawTriangle(
new Vector2(430, 80),
new Vector2(430 - 60, 150),
new Vector2(430 + 60, 150), Color.VIOLET
);
DrawTriangleLines(
new Vector2(430, 160),
new Vector2(430 - 20, 230),
new Vector2(430 + 20, 230), Color.DARKBLUE
);
DrawPoly(new Vector2(430, 320), 6, 80, 0, Color.BROWN);
// Activate our custom shader to be applied on next shapes/textures drawings
BeginShaderMode(shader);
// Using custom shader
DrawTexture(fudesumi, 500, -30, Color.WHITE);
// Activate our default shader for next drawings
EndShaderMode();
DrawText("(c) Fudesumi sprite by Eiden Marsal", 380, screenHeight - 20, 10, Color.GRAY);
EndDrawing();
//----------------------------------------------------------------------------------
}
// De-Initialization
//--------------------------------------------------------------------------------------
UnloadShader(shader);
UnloadTexture(fudesumi);
CloseWindow();
//--------------------------------------------------------------------------------------
return 0;
}
}

View File

@ -0,0 +1,164 @@
/*******************************************************************************************
*
* raylib [shaders] example - Simple shader mask
*
* This example has been created using raylib 2.5 (www.raylib.com)
* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details)
*
* Example contributed by Chris Camacho (@codifies) and reviewed by Ramon Santamaria (@raysan5)
*
* Copyright (c) 2019 Chris Camacho (@codifies) and Ramon Santamaria (@raysan5)
*
********************************************************************************************
*
* After a model is loaded it has a default material, this material can be
* modified in place rather than creating one from scratch...
* While all of the maps have particular names, they can be used for any purpose
* except for three maps that are applied as cubic maps (see below)
*
********************************************************************************************/
using System.Numerics;
using static Raylib_cs.Raylib;
using static Raylib_cs.Raymath;
namespace Examples.Shaders;
public class SimpleMask
{
public unsafe static int Main()
{
// 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.CAMERA_PERSPECTIVE;
// Define our three models to show the shader on
Mesh torus = GenMeshTorus(.3f, 1, 16, 32);
Model model1 = LoadModelFromMesh(torus);
Mesh cube = GenMeshCube(.8f, .8f, .8f);
Model model2 = LoadModelFromMesh(cube);
// Generate model to be shaded just to see the gaps in the other two
Mesh sphere = GenMeshSphere(1, 16, 16);
Model model3 = LoadModelFromMesh(sphere);
// Load the shader
Shader shader = LoadShader("resources/shaders/glsl330/mask.vs", "resources/shaders/glsl330/mask.fs");
// Load and apply the diffuse texture (colour map)
Texture2D texDiffuse = LoadTexture("resources/plasma.png");
Material* materials = model1.Materials;
MaterialMap* maps = materials[0].Maps;
model1.Materials[0].Maps[(int)MaterialMapIndex.MATERIAL_MAP_ALBEDO].Texture = texDiffuse;
materials = model2.Materials;
maps = materials[0].Maps;
maps[(int)MaterialMapIndex.MATERIAL_MAP_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");
materials = model1.Materials;
maps = (MaterialMap*)materials[0].Maps;
maps[(int)MaterialMapIndex.MATERIAL_MAP_EMISSION].Texture = texMask;
materials = model2.Materials;
maps = (MaterialMap*)materials[0].Maps;
maps[(int)MaterialMapIndex.MATERIAL_MAP_EMISSION].Texture = texMask;
int* locs = shader.Locs;
locs[(int)ShaderLocationIndex.SHADER_LOC_MAP_EMISSION] = GetShaderLocation(shader, "mask");
// Frame is incremented each frame to animate the shader
int shaderFrame = GetShaderLocation(shader, "framesCounter");
// Apply the shader to the two models
materials = model1.Materials;
materials[0].Shader = shader;
materials = (Material*)model2.Materials;
materials[0].Shader = shader;
int framesCounter = 0;
// Model rotation angles
Vector3 rotation = new(0, 0, 0);
SetTargetFPS(60);
//--------------------------------------------------------------------------------------
// Main game loop
while (!WindowShouldClose())
{
// Update
//----------------------------------------------------------------------------------
framesCounter++;
rotation.X += 0.01f;
rotation.Y += 0.005f;
rotation.Z -= 0.0025f;
// Send frames counter to shader for animation
Raylib.SetShaderValue(shader, shaderFrame, framesCounter, ShaderUniformDataType.SHADER_UNIFORM_INT);
// Rotate one of the models
model1.Transform = MatrixRotateXYZ(rotation);
UpdateCamera(ref camera, CameraMode.CAMERA_CUSTOM);
//----------------------------------------------------------------------------------
// Draw
//----------------------------------------------------------------------------------
BeginDrawing();
ClearBackground(Color.DARKBLUE);
BeginMode3D(camera);
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);
EndMode3D();
string frameText = $"Frame: {framesCounter}";
DrawRectangle(16, 698, MeasureText(frameText, 20) + 8, 42, Color.BLUE);
DrawText(frameText, 20, 700, 20, Color.WHITE);
DrawFPS(10, 10);
EndDrawing();
//----------------------------------------------------------------------------------
}
// De-Initialization
//--------------------------------------------------------------------------------------
UnloadModel(model1);
UnloadModel(model2);
UnloadModel(model3);
UnloadTexture(texDiffuse);
UnloadTexture(texMask);
UnloadShader(shader);
CloseWindow();
//--------------------------------------------------------------------------------------
return 0;
}
}

View File

@ -0,0 +1,286 @@
/*******************************************************************************************
*
* raylib [shaders] example - Simple shader mask
*
* This example has been created using raylib 2.5 (www.raylib.com)
* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details)
*
* Example contributed by Chris Camacho (@chriscamacho - http://bedroomcoders.co.uk/)
* and reviewed by Ramon Santamaria (@raysan5)
*
* Copyright (c) 2019 Chris Camacho (@chriscamacho) and Ramon Santamaria (@raysan5)
*
********************************************************************************************
*
* The shader makes alpha holes in the forground to give the apearance 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.
*
* 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.
*
********************************************************************************************/
using System;
using System.Numerics;
using static Raylib_cs.Raylib;
namespace Examples.Shaders;
public class Spotlight
{
// NOTE: It must be the same as define in shader
const int MaxSpots = 3;
const int MaxStars = 400;
// Spot data
struct Spot
{
public Vector2 pos;
public Vector2 vel;
public float inner;
public float radius;
// Shader locations
public int posLoc;
public int innerLoc;
public int radiusLoc;
}
// Stars in the star field have a position and velocity
struct Star
{
public Vector2 pos;
public Vector2 vel;
}
public static int Main()
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib - shader spotlight");
HideCursor();
Texture2D texRay = LoadTexture("resources/raysan.png");
Star[] stars = new Star[MaxStars];
for (int 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 (int n = 0; n < MaxStars; n++)
{
UpdateStar(ref stars[n]);
}
}
int frameCounter = 0;
// Use default vert shader
Shader shdrSpot = LoadShader(null, "resources/shaders/glsl330/spotlight.fs");
// Get the locations of spots in the shader
Spot[] spots = new Spot[MaxSpots];
for (int i = 0; i < MaxSpots; i++)
{
string posName = $"spots[{i}].pos";
string innerName = $"spots[{i}].inner";
string radiusName = $"spots[{i}].radius";
spots[i].posLoc = GetShaderLocation(shdrSpot, posName);
spots[i].innerLoc = GetShaderLocation(shdrSpot, innerName);
spots[i].radiusLoc = GetShaderLocation(shdrSpot, radiusName);
}
// 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();
Raylib.SetShaderValue(shdrSpot, wLoc, sw, ShaderUniformDataType.SHADER_UNIFORM_FLOAT);
// Randomise the locations and velocities of the spotlights
// and initialise the shader locations
for (int i = 0; i < MaxSpots; i++)
{
spots[i].pos.X = GetRandomValue(64, screenWidth - 64);
spots[i].pos.Y = GetRandomValue(64, screenHeight - 64);
spots[i].vel = new Vector2(0, 0);
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].inner = 28.0f * (i + 1);
spots[i].radius = 48.0f * (i + 1);
Raylib.SetShaderValue(
shdrSpot,
spots[i].posLoc,
spots[i].pos,
ShaderUniformDataType.SHADER_UNIFORM_VEC2
);
Raylib.SetShaderValue(
shdrSpot,
spots[i].innerLoc,
spots[i].inner,
ShaderUniformDataType.SHADER_UNIFORM_FLOAT
);
Raylib.SetShaderValue(
shdrSpot,
spots[i].radiusLoc,
spots[i].radius,
ShaderUniformDataType.SHADER_UNIFORM_FLOAT
);
}
SetTargetFPS(60);
//--------------------------------------------------------------------------------------
// Main game loop
while (!WindowShouldClose())
{
// Update
//----------------------------------------------------------------------------------
frameCounter++;
// Move the stars, resetting them if the go offscreen
for (int n = 0; n < MaxStars; n++)
{
UpdateStar(ref stars[n]);
}
// Update the spots, send them to the shader
for (int i = 0; i < MaxSpots; i++)
{
if (i == 0)
{
Vector2 mp = GetMousePosition();
spots[i].pos.X = mp.X;
spots[i].pos.Y = screenHeight - mp.Y;
}
else
{
spots[i].pos.X += spots[i].vel.X;
spots[i].pos.Y += spots[i].vel.Y;
if (spots[i].pos.X < 64)
{
spots[i].vel.X = -spots[i].vel.X;
}
if (spots[i].pos.X > (screenWidth - 64))
{
spots[i].vel.X = -spots[i].vel.X;
}
if (spots[i].pos.Y < 64)
{
spots[i].vel.Y = -spots[i].vel.Y;
}
if (spots[i].pos.Y > (screenHeight - 64))
{
spots[i].vel.Y = -spots[i].vel.Y;
}
}
Raylib.SetShaderValue(
shdrSpot,
spots[i].posLoc,
spots[i].pos,
ShaderUniformDataType.SHADER_UNIFORM_VEC2
);
}
// Draw
//----------------------------------------------------------------------------------
BeginDrawing();
ClearBackground(Color.DARKBLUE);
// Draw stars and bobs
for (int n = 0; n < MaxStars; n++)
{
// MathF.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++)
{
DrawTexture(
texRay,
(int)((screenWidth / 2.0) + MathF.Cos((frameCounter + i * 8) / 51.45f) * (screenWidth / 2.2) - 32),
(int)((screenHeight / 2.0) + MathF.Sin((frameCounter + i * 8) / 17.87f) * (screenHeight / 4.2)),
Color.WHITE
);
}
// Draw spot lights
BeginShaderMode(shdrSpot);
// Instead of a blank rectangle you could render a render texture of the full screen used to do screen
// scaling (slight adjustment to shader would be required to actually pay attention to the colour!)
DrawRectangle(0, 0, screenWidth, screenHeight, Color.WHITE);
EndShaderMode();
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("Dark", (int)(screenWidth * 0.66f), screenHeight / 2, 20, Color.GREEN);
EndDrawing();
//----------------------------------------------------------------------------------
}
// De-Initialization
//--------------------------------------------------------------------------------------
UnloadTexture(texRay);
UnloadShader(shdrSpot);
CloseWindow();
//--------------------------------------------------------------------------------------
return 0;
}
static void ResetStar(ref Star s)
{
s.pos = new Vector2(GetScreenWidth() / 2.0f, GetScreenHeight() / 2.0f);
do
{
s.vel.X = (float)GetRandomValue(-1000, 1000) / 100.0f;
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));
}
static void UpdateStar(ref Star s)
{
s.pos += s.vel;
if ((s.pos.X < 0) || (s.pos.X > GetScreenWidth()) ||
(s.pos.Y < 0) || (s.pos.Y > GetScreenHeight()))
{
ResetStar(ref s);
}
}
}

View File

@ -0,0 +1,86 @@
/*******************************************************************************************
*
* raylib [textures] example - Texture drawing
*
* This example illustrates how to draw on a blank texture using a shader
*
* 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 contributed by Michał Ciesielski and reviewed by Ramon Santamaria (@raysan5)
*
* Copyright (c) 2019 Michał Ciesielski and Ramon Santamaria (@raysan5)
*
********************************************************************************************/
using static Raylib_cs.Raylib;
namespace Examples.Shaders;
public class TextureDrawing
{
const int GlslVersion = 330;
public static int Main()
{
// 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);
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");
float time = 0.0f;
int timeLoc = GetShaderLocation(shader, "uTime");
Raylib.SetShaderValue(shader, timeLoc, time, ShaderUniformDataType.SHADER_UNIFORM_FLOAT);
SetTargetFPS(60);
//--------------------------------------------------------------------------------------
// Main game loop
while (!WindowShouldClose())
{
// Update
//----------------------------------------------------------------------------------
time = (float)GetTime();
Raylib.SetShaderValue(shader, timeLoc, time, ShaderUniformDataType.SHADER_UNIFORM_FLOAT);
//----------------------------------------------------------------------------------
// Draw
//----------------------------------------------------------------------------------
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();
DrawText("BACKGROUND is PAINTED and ANIMATED on SHADER!", 10, 10, 20, Color.MAROON);
EndDrawing();
//----------------------------------------------------------------------------------
}
// De-Initialization
//--------------------------------------------------------------------------------------
UnloadShader(shader);
CloseWindow();
//--------------------------------------------------------------------------------------
return 0;
}
}

View File

@ -0,0 +1,119 @@
/*******************************************************************************************
*
* raylib [textures] example - Texture drawing
*
* This example illustrates how to draw on a blank texture using a shader
*
* 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 contributed by Michał Ciesielski and reviewed by Ramon Santamaria (@raysan5)
*
* Copyright (c) 2019 Michał Ciesielski and Ramon Santamaria (@raysan5)
*
********************************************************************************************/
using static Raylib_cs.Raylib;
namespace Examples.Shaders;
public class TextureOutline
{
const int GLSL_VERSION = 330;
public static int Main()
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [shaders] example - Apply an outline to a texture");
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 };
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");
// Set shader values (they can be changed later)
Raylib.SetShaderValue(
shdrOutline,
outlineSizeLoc,
outlineSize,
ShaderUniformDataType.SHADER_UNIFORM_FLOAT
);
Raylib.SetShaderValue(
shdrOutline,
outlineColorLoc,
outlineColor,
ShaderUniformDataType.SHADER_UNIFORM_VEC4
);
Raylib.SetShaderValue(
shdrOutline,
textureSizeLoc,
textureSize,
ShaderUniformDataType.SHADER_UNIFORM_VEC2
);
SetTargetFPS(60);
//--------------------------------------------------------------------------------------
// Main game loop
while (!WindowShouldClose())
{
// Update
//----------------------------------------------------------------------------------
outlineSize += GetMouseWheelMove();
if (outlineSize < 1.0f)
{
outlineSize = 1.0f;
}
Raylib.SetShaderValue(
shdrOutline,
outlineSizeLoc,
outlineSize,
ShaderUniformDataType.SHADER_UNIFORM_FLOAT
);
//----------------------------------------------------------------------------------
// Draw
//----------------------------------------------------------------------------------
BeginDrawing();
ClearBackground(Color.RAYWHITE);
BeginShaderMode(shdrOutline);
DrawTexture(texture, GetScreenWidth() / 2 - texture.Width / 2, -30, Color.WHITE);
EndShaderMode();
DrawText("Shader-based\ntexture\noutline", 10, 10, 20, Color.GRAY);
DrawText($"Outline size: {outlineSize} px", 10, 120, 20, Color.MAROON);
DrawFPS(710, 10);
EndDrawing();
//----------------------------------------------------------------------------------
}
// De-Initialization
//--------------------------------------------------------------------------------------
UnloadTexture(texture);
UnloadShader(shdrOutline);
CloseWindow();
//--------------------------------------------------------------------------------------
return 0;
}
}

View File

@ -0,0 +1,115 @@
/*******************************************************************************************
*
* raylib [shaders] example - Texture Waves
*
* NOTE: This example requires raylib OpenGL 3.3 or ES2 versions for shaders support,
* OpenGL 1.1 does not support shaders, recompile raylib to OpenGL 3.3 version.
*
* NOTE: Shaders used in this example are #version 330 (OpenGL 3.3), 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 contributed by Anata (@anatagawa) and reviewed by Ramon Santamaria (@raysan5)
*
* Copyright (c) 2019 Anata (@anatagawa) and Ramon Santamaria (@raysan5)
*
********************************************************************************************/
using static Raylib_cs.Raylib;
namespace Examples.Shaders;
public class TextureWaves
{
const int GlslVersion = 330;
public static int Main()
{
// 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");
// Load shader and setup location points and values
Shader 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");
// 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;
float[] screenSize = { (float)GetScreenWidth(), (float)GetScreenHeight() };
Raylib.SetShaderValue(
shader,
GetShaderLocation(shader, "size"),
screenSize,
ShaderUniformDataType.SHADER_UNIFORM_VEC2
);
Raylib.SetShaderValue(shader, freqXLoc, freqX, ShaderUniformDataType.SHADER_UNIFORM_FLOAT);
Raylib.SetShaderValue(shader, freqYLoc, freqY, ShaderUniformDataType.SHADER_UNIFORM_FLOAT);
Raylib.SetShaderValue(shader, ampXLoc, ampX, ShaderUniformDataType.SHADER_UNIFORM_FLOAT);
Raylib.SetShaderValue(shader, ampYLoc, ampY, ShaderUniformDataType.SHADER_UNIFORM_FLOAT);
Raylib.SetShaderValue(shader, speedXLoc, speedX, ShaderUniformDataType.SHADER_UNIFORM_FLOAT);
Raylib.SetShaderValue(shader, speedYLoc, speedY, ShaderUniformDataType.SHADER_UNIFORM_FLOAT);
float seconds = 0.0f;
SetTargetFPS(60);
//--------------------------------------------------------------------------------------
// Main game loop
while (!WindowShouldClose())
{
// Update
//----------------------------------------------------------------------------------
seconds += GetFrameTime();
Raylib.SetShaderValue(shader, secondsLoc, seconds, ShaderUniformDataType.SHADER_UNIFORM_FLOAT);
//----------------------------------------------------------------------------------
// Draw
//----------------------------------------------------------------------------------
BeginDrawing();
ClearBackground(Color.RAYWHITE);
BeginShaderMode(shader);
DrawTexture(texture, 0, 0, Color.WHITE);
DrawTexture(texture, texture.Width, 0, Color.WHITE);
EndShaderMode();
EndDrawing();
//----------------------------------------------------------------------------------
}
// De-Initialization
//--------------------------------------------------------------------------------------
UnloadShader(shader);
UnloadTexture(texture);
CloseWindow();
//--------------------------------------------------------------------------------------
return 0;
}
}

View File

@ -0,0 +1,177 @@
/*******************************************************************************************
*
* raylib [shaders] example - Depth buffer writing
*
* Example originally created with raylib 4.2, last time updated with raylib 4.2
*
* Example contributed by Buğra Alptekin Sarı (@BugraAlptekinSari) 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) 2022-2023 Buğra Alptekin Sarı (@BugraAlptekinSari)
*
********************************************************************************************/
using System.Numerics;
using static Raylib_cs.Raylib;
namespace Examples.Shaders;
public class WriteDepth
{
const int GLSL_VERSION = 330;
public static int Main()
{
// 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.CAMERA_PERSPECTIVE;
SetTargetFPS(60);
//--------------------------------------------------------------------------------------
UpdateCamera(ref camera, CameraMode.CAMERA_ORBITAL);
//----------------------------------------------------------------------------------
// Draw
//----------------------------------------------------------------------------------
// Draw into our custom render texture (framebuffer)
BeginTextureMode(target);
ClearBackground(Color.WHITE);
BeginMode3D(camera);
BeginShaderMode(shader);
DrawCubeWiresV(new Vector3(0.0f, 0.5f, 1.0f), new Vector3(1.0f, 1.0f, 1.0f), Color.RED);
DrawCubeV(new Vector3(0.0f, 0.5f, 1.0f), new Vector3(1.0f, 1.0f, 1.0f), Color.PURPLE);
DrawCubeWiresV(new Vector3(0.0f, 0.5f, -1.0f), new Vector3(1.0f, 1.0f, 1.0f), Color.DARKGREEN);
DrawCubeV(new Vector3(0.0f, 0.5f, -1.0f), new Vector3(1.0f, 1.0f, 1.0f), Color.YELLOW);
DrawGrid(10, 1.0f);
EndShaderMode();
EndMode3D();
EndTextureMode();
// Draw custom render texture
BeginDrawing();
ClearBackground(Color.RAYWHITE);
DrawTextureRec(
target.Texture,
new Rectangle(0, 0, screenWidth, -screenHeight),
Vector2.Zero,
Color.WHITE
);
DrawFPS(10, 10);
EndDrawing();
//----------------------------------------------------------------------------------
// De-Initialization
//--------------------------------------------------------------------------------------
UnloadRenderTextureDepthTex(target);
UnloadShader(shader);
CloseWindow();
//--------------------------------------------------------------------------------------
return 0;
}
// Load custom render texture, create a writable depth texture buffer
private static unsafe RenderTexture2D LoadRenderTextureDepthTex(int width, int height)
{
RenderTexture2D target = new();
// Load an empty framebuffer
target.Id = Rlgl.LoadFramebuffer(width, height);
if (target.Id > 0)
{
Rlgl.EnableFramebuffer(target.Id);
// Create color texture (default to RGBA)
target.Texture.Id = Rlgl.LoadTexture(
null,
width,
height,
PixelFormat.PIXELFORMAT_UNCOMPRESSED_R8G8B8A8,
1
);
target.Texture.Width = width;
target.Texture.Height = height;
target.Texture.Format = PixelFormat.PIXELFORMAT_UNCOMPRESSED_R8G8B8A8;
target.Texture.Mipmaps = 1;
// Create depth texture buffer (instead of raylib default renderbuffer)
target.Depth.Id = Rlgl.LoadTextureDepth(width, height, false);
target.Depth.Width = width;
target.Depth.Height = height;
target.Depth.Format = PixelFormat.PIXELFORMAT_COMPRESSED_PVRT_RGBA;
target.Depth.Mipmaps = 1;
// Attach color texture and depth texture to FBO
Rlgl.FramebufferAttach(
target.Id,
target.Texture.Id,
FramebufferAttachType.RL_ATTACHMENT_COLOR_CHANNEL0,
FramebufferAttachTextureType.RL_ATTACHMENT_TEXTURE2D,
0
);
Rlgl.FramebufferAttach(
target.Id,
target.Depth.Id,
FramebufferAttachType.RL_ATTACHMENT_DEPTH,
FramebufferAttachTextureType.RL_ATTACHMENT_TEXTURE2D,
0
);
// Check if fbo is complete with attachments (valid)
if (Rlgl.FramebufferComplete(target.Id))
{
TraceLog(TraceLogLevel.LOG_INFO, $"FBO: [ID {target.Id}] Framebuffer object created successfully");
}
Rlgl.DisableFramebuffer();
}
else
{
TraceLog(TraceLogLevel.LOG_WARNING, "FBO: Framebuffer object can not be created");
}
return target;
}
// Unload render texture from GPU memory (VRAM)
private static void UnloadRenderTextureDepthTex(RenderTexture2D target)
{
if (target.Id > 0)
{
// Color texture attached to FBO is deleted
Rlgl.UnloadTexture(target.Texture.Id);
Rlgl.UnloadTexture(target.Depth.Id);
// NOTE: Depth texture is automatically
// queried and deleted before deleting framebuffer
Rlgl.UnloadFramebuffer(target.Id);
}
}
}