Simple Shader to Color Swap Pixels

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Diet Estus

I am trying to learn shaders in Godot 3.0 using the shading language documentation.

I am a complete novice when it comes to shaders and am trying to create a simple canvas_item shader which changes the color of certain pixels of my sprite. I’m just trying to do this simple task to learn how things work.

Basically, if the pixel color is above a certain threshold of red, I want to change it to green, otherwise I’ll change it to blue.

I attached the following shader script to a sprite’s ShaderMaterial, but it doesn’t work as expected. If I set the threshold below 1, the entire sprite is green. If I set the threshold above 1, the entire sprite is blue. It’s not changing things on a pixel-by-pixel basis.

Here is my code:

shader_type canvas_item;
render_mode blend_mix;   // not sure if this matters in this example

void fragment(){
	// if the pixel has enough red
	if (COLOR.r  > 100.0){
		// set its color to green
		COLOR = vec4(0.0, 255.0, 0.0, 255.0);
		}
	// otherwise
	else{
		// set its color to blue
		COLOR = vec4(0.0, 0.0, 255.0, 255.0)
		}
}

What am I doing wrong?

:bust_in_silhouette: Reply From: volzhs

I think this is what you want.

shader_type canvas_item;
render_mode blend_mix;

void fragment(){
	vec4 color = texture(TEXTURE, UV);
	// if the pixel has enough red
	if (color.r  > 100.0){
		// set its color to green
		color.g = 255.0;  // or color = vec4(0,255.0,0,color.a)
	}
	// otherwise
	else {
		// set its color to blue
		color.b = 255.0;  // or color = vec4(0,0,255.0,color.a)
	}
	COLOR = color;
}

Brilliant! Thanks. Can you say a word about the texture() method and its arguments. From the documentation, I know it creates a reading of a 2D texture, and that UV is some kind of vec2. But I would really like to understand what UV means… It has to do with the u and v vectors in some kind of mapping from 3D to 2D? Any why must you “read” the texture like this if fragment() is called for every pixel anyway? Just trying to understand the code.

Diet Estus | 2018-04-12 19:16

It’s hard to explain what the UV is, cause I’m not a native english speaker.
I suggest you to google it :slight_smile:

volzhs | 2018-04-12 19:34