Outline shader behind objects. WIP

Godot Version

4.3

Question

Basically I need input where my shader goes wrong and why it does show behind other objects. There are little to none information or tutorial but I found one that should be able to render behind objects, even though it is version 3 of Godot. So I translated the code to 4.3.

Here is the video https://www.youtube.com/watch?v=NsSgNkQKUnY and here is the code Bitbucket.

Here are the updated silhoutte stencil:

shader_type spatial;
render_mode depth_draw_always, unshaded;

uniform float bias = -1.0;
uniform sampler2D DEPTH_TEXTURE : hint_depth_texture, filter_linear_mipmap;

varying mat4 camera_matrix;

void vertex() {
    camera_matrix = VIEW_MATRIX;
}

void fragment() {
    vec4 screen_pixel_vertex = vec4(vec3(SCREEN_UV, textureLod(DEPTH_TEXTURE, SCREEN_UV, 0.0).x)* 2.0 - 1.0, 1.0 );
    vec4 screen_pixel_coord = INV_PROJECTION_MATRIX * screen_pixel_vertex;
    screen_pixel_coord.xyz /= screen_pixel_coord.w;
    float depth = -screen_pixel_coord.z;

    float z = -VERTEX.z;

    ALPHA = 0.0;
    DEPTH = 1.0 - float(depth < z + bias);
}

and the outline:

shader_type spatial;
render_mode unshaded, cull_disabled;

uniform sampler2D DEPTH_TEXTURE : hint_depth_texture, filter_linear_mipmap;
uniform vec4 color : source_color;
uniform float bias = -1.0;
uniform float thickness = 0.02;

varying mat4 camera_matrix;

void vertex() {
    VERTEX += NORMAL * thickness;
    camera_matrix = VIEW_MATRIX;
}

void fragment() {
    vec4 screen_pixel_vertex = vec4(vec3(SCREEN_UV, textureLod(DEPTH_TEXTURE, SCREEN_UV, 0.0).x)* 2.0 - 1.0, 1.0 );
    vec4 screen_pixel_coord = INV_PROJECTION_MATRIX * screen_pixel_vertex;
    screen_pixel_coord.xyz /= screen_pixel_coord.w;
    float depth = -screen_pixel_coord.z;

    float z = -VERTEX.z;

    ALBEDO = color.rgb;
    ALPHA = color.a * float(depth < z + bias);
    DEPTH = 0.00001;
}

An image of how I apply the shader and their priority.

I have tried so many things with render priority, mixture with depth, cull_/front/back/disabled and so on and on. I can make a silhoutte of the object behind but I rather have the outline visiblie through other objects. Picture below is the closest I have got, but the outline and color is inverted, so cull_back and depth_test_disabled isn’t the trick. What is not visible should be green and what’s green should not be visible.

So this is what I get:

This is what I want:

I’m realtive new at Godot and gaming engines and have studied .Net before this so it is diffirent. Any pointers to lead me in the right direction is mostly welcome. Thanks!

1 Like

Great Job!