Creating a simple outline shader

small dragon sprite with purple outline

Learn how to create a simple outline around an image in a fragment shader using the GLSL programming language. Easily portable to other shader languages.

Uniforms

We will pass 2 uniforms into the shader. The outline colour and the size of the texture.

uniform vec3 colour = vec3(1.0f, 1.0f, 1.0f);
uniform vec2 size = vec2(1.0f, 1.0f);

Pixel colour

First get the pixel colour inside the main shader function.

vec4 pixel = texture(textureUnit, texCoord);

Outline

Compare the pixel alpha against a small number to see if the current pixel is transparent. If the current pixel is transparent, then we need to check if any of the adjacent pixel alphas are opaque by adding them together. If they are opaque, we can set the current transparent pixel to the outline colour. Note the alpha also needs to be set for the outline to be visible.

The adjacent pixel alpha values are calculated using the offset vector. The uniform size value is used to calculate the distance to the closest adjacent pixels. The step function will return 1 if an adjacent pixel is opaque. This is used in the mix function to decide whether the current pixel is an outline colour or not.

const float SMALL_NUMBER = 0.0001f;	
if(pixel.a < SMALL_NUMBER)
{
	vec2 offset = vec2(1.0 / size.x, 0.0);
	float left = texture(textureUnit, texCoord - offset).a;
	float right = texture(textureUnit, texCoord + offset).a;

	offset.x = 0.0;
	offset.y = 1.0 / size.y;
	float up = texture(textureUnit, texCoord - offset).a;
	float down = texture(textureUnit, texCoord + offset).a;

	float a = step(SMALL_NUMBER, left + right + up + down);
	pixel = mix(pixel, vec4(vec3(colour), 1.0), a);
}

Output

Assign pixel colour to the output fragment colour.

fragColour = pixel;
small dragon with yellow and purple outline
Small dragon with yellow and purple outline

Conclusion

Thank you for reading this tutorial. Let me know in the comments section if you enjoyed it, or have any questions!

5 responses to “Creating a simple outline shader”

Leave a comment

Blog at WordPress.com.