0 votes

I am trying to create a simple Vignette Shader in Godot 3, adapting this tutorial.

For testing, I want to apply the Vignette to a sprite whose texture is Godot's default icon.png.

So far I have:

shader_type canvas_item;
render_mode unshaded; // will output the shader opaquely


// BASIC VIGNETTE

// resolution of the texture
uniform vec2 resolution = vec2(64, 64);


// fragment() runs on every pixel
void fragment (){

    // sample the texture
    vec4 tex_color = texture(TEXTURE, UV);

    // determine center of texture
    vec2 position = (FRAGCOORD.xy / resolution.xy) - vec2(0.5, 0.5);

    // determine length of current pixel to center of texture
    float len = length(position);

    // visualize length for debugging purposes
    COLOR = vec4(vec3(len), 1.0);

}

The output is:

enter image description here

The problem is that the effect is not limited to the Sprite, but is always local to the bottom left corner of the editor. I guess this is because GLSL uses the bottom left corner as origin and I've specified a resolution of 64x64. So, the center that's being used in the shader is at (32, 32), assuming a bottom left origin.

My question is:

How do I adapt this so that the shader applies only to my Sprite, and not the whole screen?

I imagine I need to find the center of the sprite, then the distance of the current pixel/fragment from that center. But I don't know how to do this.

in Engine by (1,549 points)

1 Answer

+2 votes
Best answer

Your making this harder than it really is. Since your doing this relative to the sprite, use UV instead of FRAGCOORD and subtract vec2(0.5) to it. Its length shall give you the

void fragment() {
    float len = length(UV - vec2(0.5));

    COLOR = vec4(vec3(len, 1.0));
}
by (3,875 points)
selected by

Thanks! I only just realized that UV is the coordinate within the texture. I thought it was something more complicated than that. Very new to shaders.

Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to webmaster@godotengine.org with your username.