Warning: Undefined variable $post_id in /var/www/godotshaders.com/public_html/wp-content/plugins/code-snippets/php/snippet-ops.php(663) : eval()'d code on line 7

Stencil-based silhouette

This only works in Godot 4.5 or newer, since that adds support for stencil buffers. This creates a silhouette that appears when a character is behind a wall. There were ways of achieving this in earlier versions of Godot but it’s more elegant with stencil buffers.

This contains two spatial shaders, put the silhouette shader material in the Next Pass for the first shader material.

The first writes a value to the stencil shader, and otherwise draws what your character looks like normally. So the only crucial part is: `stencil_mode write, compare_always, 1;` and you can change the rest for what you want your character to look like.

1 is arbitrary, you can pick any number except 0 as long as it matches in both shaders.

Second shader draws the actual silhouette, the crucial parts are: `render_mode depth_test_inverted, depth_draw_never;` and `stencil_mode read, write, compare_not_equal, 1;`

So the first shader writes 1 to the stencil, the second reads the stencil and won’t appear anywhere the stencil is 1. It also uses inverted depth test to only appear where something is closer to the camera. Without the stencil, you could still see the shadow where a character’s arm overlaps their torso for example, but the stencil ensures that doesn’t happen.

Shader code
// first shader, draws your character and writes to the stencil

shader_type spatial;
stencil_mode write, compare_always, 1;

uniform sampler2D main_texture:source_color;

void fragment() {
	vec4 sample = texture(main_texture, UV);
	ALBEDO.rgb = sample.rgb;
}


// second shader draws the character's silhouette if behind a wall

shader_type spatial;
render_mode unshaded, blend_mul, depth_test_inverted, depth_draw_never;
stencil_mode read, write, compare_not_equal, 1;

uniform vec3 shadow_colour:source_color = vec3(0.7,0.7,0.9);

void fragment() {
	ALBEDO = shadow_colour;
}

Warning: Undefined variable $post in /var/www/godotshaders.com/public_html/wp-content/plugins/code-snippets/php/snippet-ops.php(663) : eval()'d code on line 26

Warning: Attempt to read property "ID" on null in /var/www/godotshaders.com/public_html/wp-content/plugins/code-snippets/php/snippet-ops.php(663) : eval()'d code on line 26
Tags
silhouette, Stencil
The shader code and all code snippets in this post are under CC0 license and can be used freely without the author's permission. Images and videos, and assets depicted in those, do not fall under this license. For more info, see our License terms.

More from rrh

Related shaders

guest

1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
LoneInitiate
LoneInitiate
3 months ago

Whats your discord?