How to apply a shader pixel-by-pixel on a 2D sprite? (3.0 beta)

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By P
:warning: Old Version Published before Godot 3 was released.

Hi everyone,

I’ve been trying to use the new shading language in the 3.0 beta, and can’t quite figure it out. I am working with 2D sprites, so I have been using the “canvas_item” shading type. In 2.1, I could halve the RED value of each pixel’s color with the following fragment shader:

COLOR.r /= 2.0;

How would I go about this using the new shading language? Is there another way (without using shaders) to achieve the same effect?

:bust_in_silhouette: Reply From: Zylann

The shader to halve the red value in Godot 3.0 would be:

shader_type canvas_item;

// Executed for every pixel covered by the sprite on screen
void fragment() {

	// Fetch the texture's pixel
	vec4 col = texture(TEXTURE, UV);

	// Halve R
	col.r /= 2.0;

	// Assign the color to the output
	COLOR = col;
}

You can also do this by halving the color in the modulate property, because that color is multiplied with the sprite’s pixels to tint it, so halving R will halve the final result.

Thank you! Followup question - I had tried doingCOLOR.r /= 2, but that didn’t work. I thought it was because it read-only and couldn’t be set, which is what the docs claim. Am I interpreting the docs wrong, or are they incorrect?

P | 2017-12-27 12:36

COLOR is an output variable, so even if you could do this, it would still give you nothing. In 3.0 you have to fetch the pixel color from the texture first, like I did in my example.

Zylann | 2017-12-27 12:44

Ah, that explains a lot. How can I find out if a variable is input or output?

P | 2017-12-27 12:54

The doc says it http://docs.godotengine.org/en/latest/learning/features/shading/shading_language.html#id4
Note that COLOR here is NOT the texture color, it’s the vertex color. So for example, if you render a polygon, each point of that polygon can have a color, and that’s the one you get…
Damn I wonder why COLOR is even writable in fragment shader then… you can check yourself, my shader works xD I have to check something

Edit: I checked the latest 2D shader demos, COLOR seems to be the way… the doc says in but it’s also an output

Zylann | 2017-12-27 12:56

After some testing it looks like COLORis only an output. I’ll update the docs and see if anyone knows about any other incorrect variables. Thanks for your answers!

P | 2017-12-29 02:33