TExcelTAD
Home › Godot 4 with GDScript › The Godot Shading Language

The Godot Shading Language

Godot shaders are written in the Godot shading language, a simplified dialect of GLSL ES 3.0. You write only the interesting parts (vertex(), fragment(), light()); Godot adds the boilerplate, binds textures, and translates the shader for each renderer (Forward+, Mobile, Compatibility). Shaders are saved as .gdshader files and used through a ShaderMaterial. If GLSL is new to you, the Shaders & Graphics Programming course teaches it with live examples.

Shader types

The first line picks what the shader draws:

shader_type Used for Main outputs
canvas_item 2D: sprites, UI, Polygon2D, the 2D screen COLOR
spatial 3D meshes ALBEDO, ROUGHNESS, METALLIC, EMISSION, NORMAL_MAP, ALPHA
particles GPU particle behaviour (GPUParticles2D/3D) particle TRANSFORM, VELOCITY, COLOR
sky the Sky of a WorldEnvironment COLOR
fog volumetric fog volumes (FogVolume) DENSITY, ALBEDO

A 2D hit flash

The most common 2D shader in games: flash a sprite white when it takes damage.

gdshader
shader_type canvas_item;

uniform vec4 flash_color : source_color = vec4(1.0);
uniform float flash_amount : hint_range(0.0, 1.0) = 0.0;

void fragment() {
	vec4 tex = texture(TEXTURE, UV);
	COLOR = vec4(mix(tex.rgb, flash_color.rgb, flash_amount), tex.a);
}
  • Uniforms are parameters you set from the inspector or from code. Hints after the colon tell the editor how to show them: source_color (a colour picker, and the value is treated as sRGB), hint_range(min, max) (a slider). Default values follow =.
  • Built-ins are in capitals. In a canvas_item fragment: UV (0..1 across the texture), TEXTURE (the node's texture), COLOR (input: the vertex colour times modulate; output: the final colour), TIME, SCREEN_UV, FRAGCOORD.
  • Precision qualifiers, #version, main() and the texture bindings are written for you.

Using it:

  1. Select the Sprite2D. In the inspector under CanvasItem > Material, choose New ShaderMaterial.
  2. Click the material, then Shader > New Shader, and save it as hit_flash.gdshader.
  3. Paste the code. The uniforms appear under Shader Parameters, where you can drag flash_amount.

From GDScript, set or animate the parameters through the material. Godot really compiled this shader in the run below: it parses the code headless, lists the uniforms, and a tween fades the flash out over 0.05 s (three frames):

gdscript · try it yourself
extends Sprite2D

# frames: 4
const HIT_FLASH := """
shader_type canvas_item;

uniform vec4 flash_color : source_color = vec4(1.0);
uniform float flash_amount : hint_range(0.0, 1.0) = 0.0;

void fragment() {
	vec4 tex = texture(TEXTURE, UV);
	COLOR = vec4(mix(tex.rgb, flash_color.rgb, flash_amount), tex.a);
}
"""

func _ready():
	var shader := Shader.new()
	shader.code = HIT_FLASH
	for u in shader.get_shader_uniform_list():
		print("uniform ", u.name, " hint_string='", u.hint_string, "'")
	material = ShaderMaterial.new()
	material.shader = shader
	hit()

func hit():
	material.set_shader_parameter("flash_amount", 1.0)
	var tween := create_tween()
	tween.tween_property(material, "shader_parameter/flash_amount", 0.0, 0.05)

func _process(_delta):
	print("flash_amount = ", snappedf(material.get_shader_parameter("flash_amount"), 0.001))
uniform flash_color hint_string=''
uniform flash_amount hint_string='0.0,1.0,0.0010000000475'
flash_amount = 1.0
flash_amount = 0.667
flash_amount = 0.333
flash_amount = 0.0

Note the property path for tweens and AnimationPlayer tracks: shader_parameter/<name>.

A 3D dissolve

A spatial shader writes material properties; Godot's lighting does the rest. This one burns a mesh away using a noise texture, with a glowing edge, and makes it wobble in the vertex shader:

gdshader
shader_type spatial;
render_mode cull_disabled;

uniform vec3 base_color : source_color = vec3(0.2, 0.6, 1.0);
uniform sampler2D noise : filter_linear, repeat_enable;
uniform float dissolve : hint_range(0.0, 1.0) = 0.0;
uniform vec3 edge_color : source_color = vec3(1.0, 0.5, 0.1);
instance uniform float wobble = 0.0;

void vertex() {
	VERTEX.y += sin(TIME * 3.0 + VERTEX.x * 4.0) * wobble;
}

void fragment() {
	float n = texture(noise, UV).r;
	if (n < dissolve) {
		discard;
	}
	float edge = 1.0 - smoothstep(0.0, 0.05, n - dissolve);
	ALBEDO = base_color;
	EMISSION = edge_color * edge * 4.0;
	ROUGHNESS = 0.4;
	METALLIC = 0.0;
}
  • render_mode sets fixed-function options: unshaded, cull_disabled, blend_add, depth_draw_always and others.
  • VERTEX in vertex() is in model space for spatial shaders by default.
  • Sampler hints set filtering and repeat: filter_nearest for pixel art, repeat_enable for tiling. Assign a NoiseTexture2D (with a FastNoiseLite) to noise in the inspector: no image file needed.
  • instance uniform values are stored per mesh instance, not per material. mesh_instance.set_instance_shader_parameter("wobble", 0.1) changes one enemy without duplicating the material (compare the shared-material problem in Field Notes: Typing, Physics & Memory).
  • discard throws the pixel away. It disables some depth optimisations, so use it on objects that need it, not everywhere.

Reading the screen

Post-processing in 2D reads what has already been drawn. Godot 4 replaced the old SCREEN_TEXTURE built-in with a uniform hint:

gdshader
shader_type canvas_item;

uniform sampler2D screen_tex : hint_screen_texture, filter_linear_mipmap;
uniform float blur : hint_range(0.0, 4.0) = 2.0;

void fragment() {
	COLOR = textureLod(screen_tex, SCREEN_UV, blur);
}

Put it on a ColorRect that covers the screen (anchors Full Rect) in a CanvasLayer above the game. hint_depth_texture and hint_normal_roughness_texture do the same for 3D depth and normals.

Checking shaders from code

Godot compiles shader code when it is first used, even without a GPU, so a script (or a test) can catch shader typos. Here are both 3D shaders above, plus one with a deliberate error:

gdscript · try it yourself
extends SceneTree

const DISSOLVE := """
shader_type spatial;
render_mode cull_disabled;
uniform vec3 base_color : source_color = vec3(0.2, 0.6, 1.0);
uniform sampler2D noise : filter_linear, repeat_enable;
uniform float dissolve : hint_range(0.0, 1.0) = 0.0;
uniform vec3 edge_color : source_color = vec3(1.0, 0.5, 0.1);
instance uniform float wobble = 0.0;
void vertex() {
	VERTEX.y += sin(TIME * 3.0 + VERTEX.x * 4.0) * wobble;
}
void fragment() {
	float n = texture(noise, UV).r;
	if (n < dissolve) {
		discard;
	}
	float edge = 1.0 - smoothstep(0.0, 0.05, n - dissolve);
	ALBEDO = base_color;
	EMISSION = edge_color * edge * 4.0;
	ROUGHNESS = 0.4;
	METALLIC = 0.0;
}
"""

const SCREEN_BLUR := """
shader_type canvas_item;
uniform sampler2D screen_tex : hint_screen_texture, filter_linear_mipmap;
uniform float blur : hint_range(0.0, 4.0) = 2.0;
void fragment() {
	COLOR = textureLod(screen_tex, SCREEN_UV, blur);
}
"""

const BROKEN := """
shader_type spatial;
void fragment() {
	ALBEDO = 1.0;
}
"""

func check(label: String, code: String) -> void:
	var shader := Shader.new()
	shader.code = code
	var names: Array[String] = []
	for u in shader.get_shader_uniform_list():   # compiles the shader
		names.append(u.name)
	print(label, ": ", names)

func _init():
	check("dissolve", DISSOLVE)
	check("screen blur", SCREEN_BLUR)
	check("broken", BROKEN)
	quit()
dissolve: ["base_color", "noise", "dissolve", "edge_color"]
screen blur: ["blur"]
--Main Shader--
    2 | shader_type spatial;
    3 | void fragment() {
E   4->  ALBEDO = 1.0;
    5 | }
    6 |
SHADER ERROR: Invalid arguments to operator '=': 'vec3, float'.
          at: (null) (:4)
          GDScript backtrace (most recent call first):
              [0] check (res://main.gd:47)
              [1] _init (res://main.gd:54)
ERROR: Shader compilation failed.
   at: shader_set_code (servers/rendering/dummy/storage/material_storage.cpp:192)
   GDScript backtrace (most recent call first):
       [0] check (res://main.gd:47)
       [1] _init (res://main.gd:54)
broken: []

The instance uniform and the screen texture are not in the material's parameter list: one lives on the instance, the other is bound by the engine. The broken shader shows the same error the editor's shader panel would: ALBEDO is a vec3, so write ALBEDO = vec3(1.0);.

The same effect, live

The shading language is close enough to GLSL that porting is mostly renaming. Here is the dissolve as a live WebGL shader in this page (procedural value noise instead of a texture; ALBEDO/EMISSION become one output colour):

glsl · try it yourself
float hash(vec2 p) { return fract(sin(dot(p, vec2(127.1, 311.7))) * 43758.5453); }
float noise(vec2 p) {
    vec2 i = floor(p), f = fract(p);
    vec2 u = f * f * (3.0 - 2.0 * f);
    return mix(mix(hash(i), hash(i + vec2(1, 0)), u.x), mix(hash(i + vec2(0, 1)), hash(i + vec2(1, 1)), u.x), u.y);
}

void mainImage(out vec4 fragColor, in vec2 fragCoord) {
    vec2 uv = fragCoord / iResolution.xy;
    float n = 0.65 * noise(uv * 8.0) + 0.35 * noise(uv * 16.0);
    float dissolve = 0.5 + 0.5 * sin(iTime * 0.8);          // animate 0..1
    vec3 base_color = vec3(0.2, 0.6, 1.0);
    vec3 edge_color = vec3(1.0, 0.5, 0.1);
    if (n < dissolve) { fragColor = vec4(0.05, 0.05, 0.08, 1.0); return; }   // "discard"
    float edge = 1.0 - smoothstep(0.0, 0.05, n - dissolve);
    fragColor = vec4(base_color + edge_color * edge * 4.0, 1.0);
}
Godot GLSL / Shadertoy
TIME iTime
UV fragCoord / iResolution.xy (or a varying)
COLOR / ALBEDO + EMISSION fragColor
uniform float x : hint_range(0, 1) uniform float x; (no hints)
texture(TEXTURE, UV) texture(iChannel0, uv)

Visual shaders and when to write code

Godot also has VisualShader: the same shaders as a node graph (choose New VisualShader instead of New Shader). It is a good fit for artists and for exploring. Code wins for anything with loops, functions, or diffs in version control. A visual shader can be converted to code from its resource's context menu, which is a nice way to learn the built-in names.

Global uniforms (Project Settings > Shader Globals) let many shaders read one value, such as wind direction or the player position for grass that bends away. Use them with global uniform vec3 player_position;, and set them with RenderingServer.global_shader_parameter_set().

Compare with Unity's Shader Graph and Unreal's material editor in One Dissolve, Three Engines, and the engine overview in Godot Shading Language.

Test yourself

Which built-in does a canvas_item fragment shader write to set the final colour?

  1. ALBEDO
  2. COLOR
  3. gl_FragColor
  4. fragColor

How do you animate a shader uniform flash_amount with a Tween?

  1. tween_property(material, "flash_amount", 0.0, 0.2)
  2. tween_property(material, "shader_parameter/flash_amount", 0.0, 0.2)
  3. Shader uniforms can't be animated
  4. tween_property(self, "COLOR", 0.0, 0.2)

Many enemies share one material, but each needs its own dissolve value. What avoids duplicating the material?

  1. A const in the shader
  2. An instance uniform, set with set_instance_shader_parameter()
  3. A global uniform
  4. Two fragment() functions