Six Channel Colour Shader
A simple shader for colouring static objects dynamically. Contains 6 channels, Red, Magenta, Green, Yellow, Blue, Cyan. Example:
x = any_number>0
- Red = Color(X,0.0,0.0,1.0)
- Magenta = Color(X, 0.0,X,1.0)
- Non shaded colour = Color(X,X,X,1.0)
Can be shaded, so
- Bright = Color(1.0,0.0,0.0,1.0)
- Medium = Color(0.5,0.0,0.0,1.0)
- Dark = Color(0.1,0.0,0.0,1.0)
Interacts poorly with non-pixel perfect moving objects.
Edit: Just to clarify on the non shaded colour. If you wanted pure green that wouldn’t get shaded you’d put Color(0.01,1.0,0.01,1.0).
Shader code
shader_type canvas_item;
uniform vec4 Red: hint_color;
uniform vec4 Magenta: hint_color;
uniform vec4 Green: hint_color;
uniform vec4 Yellow: hint_color;
uniform vec4 Blue: hint_color;
uniform vec4 Cyan: hint_color;
void fragment(){
vec4 col = texture(TEXTURE, UV);
vec4 chosen_col = col;
if (col.r == 0.0){
if (col.b == 0.0){
if (col.g > 0.0){
chosen_col.rgb = Green.rgb*col.g;
}
}else{
if(col.g == 0.0){
chosen_col.rgb = Blue.rgb*col.b;
}else{
chosen_col.rgb = Cyan.rgb*((col.g+col.b)/2.0);
}
}
}else{
if (col.b == 0.0){
if (col.g == 0.0){
chosen_col.rgb = Red.rgb*col.r;
}else{
chosen_col.rgb = Yellow.rgb*((col.r+col.g)/2.0);
}
}else{
if (col.g == 0.0){
chosen_col.rgb = Magenta.rgb*((col.r+col.b)/2.0);
}
}
}
COLOR = chosen_col;
}
Looks very cool, I’m just feared about the performance, because using lots of if statements is highly unrecommended in shaders.
It branches up to three times. Using several sqrt is worse than that in most cases.
I’ve never had a problem with hundreds of instances on screen. You’d have to stress test it (as you should do with any shader code) but my question would be why aren’t you using a texture substitution if you want more than a few hundred instances?
If you want a version without if statements. There is no noticeable difference between the two operations except on GPUs that can process branching. If a GPU can process branching then the branch version is more efficient.
Too many branching operators. It is much more efficient to use a constant array of vectors.
How would you go about using a constant array of vectors to switch between six colour channels?
I rewrote it to use no branching, but the difference is entirely negligible as this merely computes every possible outcome and adds them – doing exactly the same thing as the if/else does on GPUs that don’t deal with branching.