Extensible Color Palette

This shader allows you to turn greyscale colors (based on highest value of red, green, or blue) into defined colors in the shader parameters.

By default, it uses 9 colors, and can be programmed for more or fewer designated colors.

When adding more colors in the variables, (ie color0, color1, etc.) each variable’s name must be “color#”, where the # denotes its number. the variables must be numbered from 0 to “#-1” where “#” is the number of colors you have.

The second part of adding colors is by editing the vec4 array named “colors”. Each “color#” variable needs to be present in this list for that color to appear in the shader.
(All of the multiplication and division is based on the array’s length).

The order in which the “color#” variables are listed in the array is the same order in which they will appear on their respective greyscale value.

If you want to define 12 colors that you want to use, make sure you have variables “color0” to “color11”, and list them in the array named “colors[]”

I’m sure that I can make this shader even more efficient by reducing all of the unnecessary “vec3″s to floats, and process single values rather than carrying around 3 for each pixel. I’ll get around to it soon.


Shader code
shader_type canvas_item; 
render_mode blend_mix, unshaded;

uniform vec4 color0: hint_color;
uniform vec4 color1: hint_color;
uniform vec4 color2: hint_color;
uniform vec4 color3: hint_color;
uniform vec4 color4: hint_color;
uniform vec4 color5: hint_color;
uniform vec4 color6: hint_color;
uniform vec4 color7: hint_color;
uniform vec4 color8: hint_color;

void fragment() {
// Input:3
	vec4 colors[] = {color0,color1,color2,color3,color4,color5,color6,color7,color8};

	vec3 scrn_uv = vec3(UV, 0.0);

// Texture:4
	vec3 n_out4p0;
	float n_out4p1;
		vec4 _tex_read = textureLod(TEXTURE, scrn_uv.xy, 0.0);
		n_out4p0 = _tex_read.rgb;
		n_out4p1 = _tex_read.a;

// ColorFunc:6
	vec3 n_out6p0;
		vec3 c = n_out4p0;
		float max1 = max(c.r, c.g);
		float max2 = max(max1, c.b);
		float max3 = max(max1, max2);
		n_out6p0 = vec3(max3, max3, max3);

// VectorOp:8
	vec3 n_in8p1 = vec3(float(colors.length()-1));
	vec3 n_out8p0 = n_out6p0 * n_in8p1;

// VectorFunc:7
	vec3 n_out7p0 = round(n_out8p0);

// VectorOp:9
	vec3 n_in9p1 = vec3(float(colors.length()-1));
	vec3 n_out9p0 = n_out7p0 / n_in9p1;
	vec4 out_color = colors[int(round(n_out8p0.x))];

// Output:0
	COLOR = out_color;
	COLOR.a = n_out4p1;
	//COLOR.rgb = n_out9p0;


void light() {
// Output:0

Color, color palette, palette
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.

Related shaders

color splash (show only one color)

Palette Filter For 3D and 2D

Palette Swap (no recolor / recolor)

Inline Feedbacks
View all comments