...

/

Custom Postprocessing Shaders

Custom Postprocessing Shaders

Learn how to create custom shaders for postprocessing in Three.js.

Creating custom postprocessing shaders

In this lesson, we’ll learn how to create a custom shader that we can use in postprocessing. We’ll create two different shaders. The first one will convert the current image to a grayscale image, and the second one will convert the image to an 8-bit image by reducing the number of colors that are available.

Note: Creating vertex and fragment shaders is a very broad subject. In this lesson, we will only touch the surface of what can be done by these shaders and how they work. For more in-depth information, we can find the WebGL specification. Another resource, full of examples, is Shadertoy, or The Book of Shaders.

Custom grayscale shader

To create a custom shader for Three.js (and also for other WebGL libraries), we have to create two components: a vertex shader and a fragment shader. The vertex shader can be used to change the position of individual vertices, and the fragment shader can be used to determine the colors of individual pixels. For a postprocessing shader, we only need to implement a fragment shader, and we can keep the default vertex shader provided by Three.js.

An important point to make before looking at the code is that GPUs support multiple shader pipelines. This means that the vertex shaders run in parallel on multiple vertices at the same time, and the same goes for the fragment shaders.

Example: Custom shader

Let’s start by looking at the complete source code ...