Merge pull request #4861 from luis605/view-depth-texture

[examples] Added new shader example: `shader_depth_texture`
This commit is contained in:
Ray 2025-04-09 17:57:20 +02:00 committed by GitHub
commit a5639bb186
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
10 changed files with 784 additions and 30 deletions

View file

@ -90,13 +90,14 @@ if (${PLATFORM} MATCHES "Android")
list(REMOVE_ITEM example_sources ${CMAKE_CURRENT_SOURCE_DIR}/shaders/shaders_custom_uniform.c)
list(REMOVE_ITEM example_sources ${CMAKE_CURRENT_SOURCE_DIR}/shaders/shaders_model_shader.c)
list(REMOVE_ITEM example_sources ${CMAKE_CURRENT_SOURCE_DIR}/shaders/shaders_view_depth.c)
list(REMOVE_ITEM example_sources ${CMAKE_CURRENT_SOURCE_DIR}/shaders/shaders_postprocessing.c)
list(REMOVE_ITEM example_sources ${CMAKE_CURRENT_SOURCE_DIR}/shaders/shaders_raymarching.c)
list(REMOVE_ITEM example_sources ${CMAKE_CURRENT_SOURCE_DIR}/shaders/shaders_palette_switch.c)
list(REMOVE_ITEM example_sources ${CMAKE_CURRENT_SOURCE_DIR}/shaders/shaders_basic_lighting.c)
elseif (${PLATFORM} MATCHES "Web")
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Os")
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Os")
# Since WASM is used, ALLOW_MEMORY_GROWTH has no extra overheads
set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -s WASM=1 -s ASYNCIFY -s ALLOW_MEMORY_GROWTH=1 --shell-file ${CMAKE_SOURCE_DIR}/src/shell.html")
set(CMAKE_EXECUTABLE_SUFFIX ".html")

View file

@ -232,7 +232,7 @@ CFLAGS = -Wall -std=c99 -D_DEFAULT_SOURCE -Wno-missing-braces -Wunused-result
ifeq ($(BUILD_MODE),DEBUG)
CFLAGS += -g -D_DEBUG
else
else
ifeq ($(TARGET_PLATFORM),$(filter $(TARGET_PLATFORM),PLATFORM_WEB PLATFORM_WEB_RGFW))
ifeq ($(BUILD_WEB_ASYNCIFY),TRUE)
CFLAGS += -O3
@ -341,12 +341,12 @@ ifeq ($(TARGET_PLATFORM),$(filter $(TARGET_PLATFORM),PLATFORM_WEB PLATFORM_WEB_R
# --source-map-base # allow debugging in browser with source map
# --shell-file shell.html # define a custom shell .html and output extension
LDFLAGS += -sTOTAL_MEMORY=$(BUILD_WEB_HEAP_SIZE) -sFORCE_FILESYSTEM=1 -sMINIFY_HTML=0
# Using GLFW3 library (instead of RGFW)
ifeq ($(TARGET_PLATFORM),PLATFORM_WEB)
LDFLAGS += -sUSE_GLFW=3
endif
# Build using asyncify
ifeq ($(BUILD_WEB_ASYNCIFY),TRUE)
LDFLAGS += -sASYNCIFY
@ -642,6 +642,7 @@ SHADERS = \
shaders/shaders_texture_outline \
shaders/shaders_texture_tiling \
shaders/shaders_texture_waves \
shaders/shaders_view_depth \
shaders/shaders_write_depth \
shaders/shaders_vertex_displacement

View file

@ -278,7 +278,7 @@ ifeq ($(PLATFORM),$(filter $(PLATFORM),PLATFORM_WEB PLATFORM_WEB_RGFW))
# --source-map-base # allow debugging in browser with source map
# --shell-file shell.html # define a custom shell .html and output extension
LDFLAGS += -sTOTAL_MEMORY=$(BUILD_WEB_HEAP_SIZE) -sFORCE_FILESYSTEM=1 -sEXPORTED_RUNTIME_METHODS=ccall -sMINIFY_HTML=0
# Using GLFW3 library (instead of RGFW)
ifeq ($(PLATFORM),PLATFORM_WEB)
LDFLAGS += -sUSE_GLFW=3
@ -525,6 +525,7 @@ SHADERS = \
shaders/shaders_texture_tiling \
shaders/shaders_texture_waves \
shaders/shaders_vertex_displacement \
shaders/shaders_view_depth \
shaders/shaders_write_depth
AUDIO = \
@ -1150,6 +1151,10 @@ shaders/shaders_texture_waves: shaders/shaders_texture_waves.c
--preload-file shaders/resources/space.png@resources/space.png \
--preload-file shaders/resources/shaders/glsl100/wave.fs@resources/shaders/glsl100/wave.fs
shaders/shaders_view_depth: shaders/shaders_view_depth.c
$(CC) -o $@$(EXT) $< $(CFLAGS) $(INCLUDE_PATHS) $(LDFLAGS) $(LDLIBS) -D$(PLATFORM) \
--preload-file shaders/resources/shaders/glsl100/write_depth.fs@resources/shaders/glsl100/write_depth.fs
shaders/shaders_write_depth: shaders/shaders_write_depth.c
$(CC) -o $@$(EXT) $< $(CFLAGS) $(INCLUDE_PATHS) $(LDFLAGS) $(LDLIBS) -D$(PLATFORM) \
--preload-file shaders/resources/shaders/glsl100/write_depth.fs@resources/shaders/glsl100/write_depth.fs
@ -1235,4 +1240,3 @@ ifeq ($(PLATFORM),$(filter $(PLATFORM),PLATFORM_WEB PLATFORM_WEB_RGFW))
del *.o *.html *.js
endif
@echo Cleaning done

View file

@ -201,6 +201,7 @@ Examples using raylib shaders functionality, including shaders loading, paramete
| 139 | [shaders_basic_pbr](shaders/shaders_basic_pbr.c) | <img src="shaders/shaders_basic_pbr.png" alt="shaders_basic_pbr" width="80"> | ⭐️⭐️⭐️⭐️ | 5.0 | 5.1-dev | [Afan OLOVCIC](https://github.com/_DevDad) |
| 140 | [shaders_lightmap](shaders/shaders_lightmap.c) | <img src="shaders/shaders_lightmap.png" alt="shaders_lightmap" width="80"> | ⭐️⭐️⭐️☆ | 4.5 | 4.5 | [Jussi Viitala](https://github.com/nullstare) |
| 141 | [shaders_rounded_rectangle](shaders/shaders_rounded_rectangle.c) | <img src="shaders/shaders_rounded_rectangle.png" alt="shaders_rounded_rectangle" width=80> | ⭐️⭐️⭐️☆ | 5.5 | 5.5 | [Anstro Pleuton](https://github.com/anstropleuton) |
| 142 | [shaders_view_depth](shaders/shaders_view_depth.c) | <img src="shaders/shaders_view_depth.png" alt="shaders_view_depth" width="80"> | ⭐️⭐️⭐️☆ | 5.6-dev | 5.6-dev | [Luís Almeida](https://github.com/luis605) |
### category: audio
@ -230,4 +231,3 @@ Examples showing raylib misc functionality that does not fit in other categories
| 154 | [raymath_vector_angle](others/raymath_vector_angle.c) | <img src="others/raymath_vector_angle.png" alt="raymath_vector_angle" width="80"> | ⭐️⭐️☆☆ | 1.0 | 4.6 | [Ray](https://github.com/raysan5) |
As always contributions are welcome, feel free to send new examples! Here is an [examples template](examples_template.c) to start with!

View file

@ -1,26 +1,34 @@
#version 100
precision mediump float;
// Input vertex attributes (from vertex shader)
varying vec2 fragTexCoord;
varying vec4 fragColor;
// Input uniform values
uniform sampler2D texture0; // Depth texture
uniform vec4 colDiffuse;
uniform sampler2D depthTexture;
uniform bool flipY;
// NOTE: Add your custom variables here
float nearPlane = 0.1;
float farPlane = 100.0;
// Function to linearize depth from non-linear depth buffer
float linearizeDepth(float depth)
{
return (2.0 * nearPlane) / (farPlane + nearPlane - depth * (farPlane - nearPlane));
}
void main()
{
float zNear = 0.01; // camera z near
float zFar = 10.0; // camera z far
float z = texture2D(texture0, fragTexCoord).x;
// Handle potential Y-flipping
vec2 texCoord = fragTexCoord;
if (flipY)
texCoord.y = 1.0 - texCoord.y;
// Linearize depth value
float depth = (2.0*zNear)/(zFar + zNear - z*(zFar - zNear));
// Sample depth texture
float depth = texture2D(depthTexture, texCoord).r;
// Calculate final fragment color
gl_FragColor = vec4(depth, depth, depth, 1.0);
// Linearize depth
float linearDepth = linearizeDepth(depth);
// Output final color
gl_FragColor = vec4(vec3(linearDepth), 1.0);
}

View file

@ -2,26 +2,36 @@
// Input vertex attributes (from vertex shader)
in vec2 fragTexCoord;
in vec4 fragColor;
// Input uniform values
uniform sampler2D texture0; // Depth texture
uniform vec4 colDiffuse;
uniform sampler2D depthTexture;
uniform bool flipY;
const float nearPlane = 0.1;
const float farPlane = 100.0;
// Output fragment color
out vec4 finalColor;
// NOTE: Add your custom variables here
// Linearizes the depth buffer value
float linearizeDepth(float depth)
{
return (2.0 * nearPlane) / (farPlane + nearPlane - depth * (farPlane - nearPlane));
}
void main()
{
float zNear = 0.01; // camera z near
float zFar = 10.0; // camera z far
float z = texture(texture0, fragTexCoord).x;
// Handle potential Y-flipping
vec2 texCoord = fragTexCoord;
if (flipY)
texCoord.y = 1.0 - texCoord.y;
// Sample depth
float depth = texture(depthTexture, texCoord).r;
// Linearize depth value
float depth = (2.0*zNear)/(zFar + zNear - z*(zFar - zNear));
float linearDepth = linearizeDepth(depth);
// Calculate final fragment color
finalColor = vec4(depth, depth, depth, 1.0);
// Output final color
finalColor = vec4(vec3(linearDepth), 1.0);
}

View file

@ -0,0 +1,159 @@
/*******************************************************************************************
*
* raylib [shader] example - render depth texture
*
* Example complexity rating: [] 3/4
*
* Example originally created with raylib 5.6-dev, last time updated with raylib 5.6-dev
*
* Example contributed by Luís Almeida (@luis605)
*
* 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) 2025 Luís Almeida (@luis605)
*
********************************************************************************************/
#include "raylib.h"
#include "rlgl.h"
#if defined(PLATFORM_DESKTOP)
#define GLSL_VERSION 330
#else // PLATFORM_ANDROID, PLATFORM_WEB
#define GLSL_VERSION 100
#endif
RenderTexture2D LoadRenderTextureWithDepth(int width, int height);
//------------------------------------------------------------------------------------
// Program main entry point
//------------------------------------------------------------------------------------
int main(void)
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 600;
InitWindow(screenWidth, screenHeight, "raylib [shader] example - render depth texture");
// Load camera
Camera camera = { 0 };
camera.position = (Vector3){ 4.0f, 1.0f, 5.0f };
camera.target = (Vector3){ 0.0f, 0.0f, 0.0f };
camera.up = (Vector3){ 0.0f, 1.0f, 0.0f };
camera.fovy = 45.0f;
camera.projection = CAMERA_PERSPECTIVE;
// Load an empty render texture with a depth texture
RenderTexture2D target = LoadRenderTextureWithDepth(screenWidth, screenHeight);
// Load depth shader and get depth texture shader location
Shader depthShader = LoadShader(0, TextFormat("resources/shaders/glsl%i/depth.fs", GLSL_VERSION));
int depthLoc = GetShaderLocation(depthShader, "depthTexture");
int flipTextureLoc = GetShaderLocation(depthShader, "flipY");
SetShaderValue(depthShader, flipTextureLoc, (int[]){ 1 }, SHADER_UNIFORM_INT); // Flip Y texture
// Load models
Model cube = LoadModelFromMesh(GenMeshCube(1.0f, 1.0f, 1.0f));
Model floor = LoadModelFromMesh(GenMeshPlane(20.0f, 20.0f, 1, 1));
DisableCursor(); // Limit cursor to relative movement inside the window
SetTargetFPS(60); // Set our game to run at 60 frames-per-second
//--------------------------------------------------------------------------------------
// Main game loop
while (!WindowShouldClose()) // Detect window close button or ESC key
{
// Update
//----------------------------------------------------------------------------------
UpdateCamera(&camera, CAMERA_FREE);
//----------------------------------------------------------------------------------
// Draw
//----------------------------------------------------------------------------------
BeginTextureMode(target);
ClearBackground(WHITE);
BeginMode3D(camera);
DrawModel(cube, (Vector3){ 0.0f, 0.0f, 0.0f }, 3.0f, YELLOW);
DrawModel(floor, (Vector3){ 10.0f, 0.0f, 2.0f }, 2.0f, RED);
EndMode3D();
EndTextureMode();
BeginDrawing();
BeginShaderMode(depthShader);
SetShaderValueTexture(depthShader, depthLoc, target.depth);
DrawTexture(target.depth, 0, 0, WHITE);
EndShaderMode();
DrawRectangle( 10, 10, 320, 93, Fade(SKYBLUE, 0.5f));
DrawRectangleLines( 10, 10, 320, 93, BLUE);
DrawText("Camera Controls:", 20, 20, 10, BLACK);
DrawText("- WASD to move", 40, 40, 10, DARKGRAY);
DrawText("- Mouse Wheel Pressed to Pan", 40, 60, 10, DARKGRAY);
DrawText("- Z to zoom to (0, 0, 0)", 40, 80, 10, DARKGRAY);
EndDrawing();
//----------------------------------------------------------------------------------
}
// De-Initialization
//--------------------------------------------------------------------------------------
UnloadModel(cube); // Unload model
UnloadModel(floor); // Unload model
UnloadRenderTexture(target); // Unload render texture
UnloadShader(depthShader); // Unload shader
CloseWindow(); // Close window and OpenGL context
//--------------------------------------------------------------------------------------
return 0;
}
RenderTexture2D LoadRenderTextureWithDepth(int width, int height)
{
RenderTexture2D target = {0};
target.id = rlLoadFramebuffer(); // Load an empty framebuffer
if (target.id > 0)
{
rlEnableFramebuffer(target.id);
// Create color texture (default to RGBA)
target.texture.id = rlLoadTexture(0, width, height, PIXELFORMAT_UNCOMPRESSED_R8G8B8A8, 1);
target.texture.width = width;
target.texture.height = height;
target.texture.format = PIXELFORMAT_UNCOMPRESSED_R8G8B8A8;
target.texture.mipmaps = 1;
// Create depth texture
target.depth.id = rlLoadTextureDepth(width, height, false);
target.depth.width = width;
target.depth.height = height;
target.depth.format = 19; //DEPTH_COMPONENT_24BIT? THIS DOESN'T EXIST IN RAYLIB
target.depth.mipmaps = 1;
// Attach color texture and depth texture to FBO
rlFramebufferAttach(target.id, target.texture.id, RL_ATTACHMENT_COLOR_CHANNEL0, RL_ATTACHMENT_TEXTURE2D, 0);
rlFramebufferAttach(target.id, target.depth.id, RL_ATTACHMENT_DEPTH, RL_ATTACHMENT_TEXTURE2D, 0);
// Check if fbo is complete with attachments (valid)
if (rlFramebufferComplete(target.id)) TRACELOG(LOG_INFO, "FBO: [ID %i] Framebuffer object created successfully", target.id);
rlDisableFramebuffer();
}
else TRACELOG(LOG_WARNING, "FBO: Framebuffer object can not be created");
return target;
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB