Godot Shading Language
Godot 4 has its own shading language. It looks almost exactly like GLSL ES 3.0, so everything you wrote in this course carries over, but Godot handles the boilerplate: you never declare in/out variables, matrices or main(). You write up to three functions, vertex(), fragment() and light(), and read and write built-in variables such as UV, TIME, ALBEDO and EMISSION. Godot then compiles your code into its renderers (Forward+, Mobile and Compatibility).
Shader types
The first line of every Godot shader picks what it is for:
shader_type |
Used on | Typical uses |
|---|---|---|
spatial |
3D meshes (a ShaderMaterial on a MeshInstance3D) |
surfaces, water, dissolve, vertex wind |
canvas_item |
2D nodes (Sprite2D, ColorRect, Control) |
sprite effects, 2D post-processing, UI |
particles |
GPUParticles2D/3D process materials |
custom particle motion |
sky |
the Sky resource of a WorldEnvironment |
procedural skies |
fog |
FogVolume nodes |
volumetric fog shapes |
Create one with New ShaderMaterial in a mesh's material slot, then New Shader inside it (or FileSystem > right-click > Create New > Resource > Shader). The file is saved as .gdshader.
A first spatial shader
shader_type spatial;
uniform vec4 base_color : source_color = vec4(0.2, 0.6, 1.0, 1.0);
uniform float roughness_value : hint_range(0.0, 1.0) = 0.4;
void fragment() {
ALBEDO = base_color.rgb;
ROUGHNESS = roughness_value;
METALLIC = 0.0;
}Already this is a fully lit PBR surface with shadows, because in a spatial shader fragment() only fills in the material; Godot's renderer does the lighting. That is the same split as Unreal's material outputs and Unity's Lit Shader Graph.
uniformdeclares a parameter that shows up in the Inspector of the ShaderMaterial. Setting it from code:material.set_shader_parameter("base_color", Color.RED).: source_colormarks a color as sRGB, so Godot converts it to linear for you and shows a color picker. Use it on every color and albedo texture uniform.: hint_range(min, max)(optional third argument: step) shows a slider.
Built-ins you will use most
In vertex() (positions are in model space by default):
| Built-in | Type | Meaning |
|---|---|---|
VERTEX |
inout vec3 |
vertex position |
NORMAL |
inout vec3 |
vertex normal |
UV |
inout vec2 |
first UV set |
COLOR |
inout vec4 |
vertex color |
TIME |
in float |
seconds, available in every function |
In fragment() (vectors are in view space):
| Built-in | Type | Meaning |
|---|---|---|
ALBEDO |
out vec3 |
base color |
ALPHA |
out float |
opacity (makes the material transparent when written) |
ALPHA_SCISSOR_THRESHOLD |
out float |
alpha test instead of blending: pixels with ALPHA below it are discarded |
METALLIC, ROUGHNESS |
out float |
PBR parameters |
EMISSION |
out vec3 |
light the surface emits (glows with bloom/Glow enabled) |
NORMAL_MAP |
out vec3 |
a tangent-space normal map sample |
RIM, RIM_TINT |
out float |
Godot's built-in rim lighting |
NORMAL, VIEW |
vec3 |
surface normal, direction from the surface to the camera |
UV, VERTEX, FRAGCOORD |
interpolated UV, view-space position, window position |
Vertex animation: a flag in the wind
shader_type spatial;
render_mode cull_disabled; // draw both sides of the flag
uniform sampler2D flag_texture : source_color, filter_linear_mipmap;
uniform float wave_speed = 3.0;
uniform float wave_height : hint_range(0.0, 0.5) = 0.15;
void vertex() {
// UV.x = 0 at the pole, 1 at the free end: the pole side does not move
float wave = sin(VERTEX.x * 4.0 - TIME * wave_speed) * wave_height * UV.x;
VERTEX.z += wave;
// Approximate the bent normal from the wave's slope
float slope = cos(VERTEX.x * 4.0 - TIME * wave_speed) * 4.0 * wave_height * UV.x;
NORMAL = normalize(vec3(-slope, 0.0, 1.0));
}
void fragment() {
ALBEDO = texture(flag_texture, UV).rgb;
ROUGHNESS = 0.8;
}Put it on a subdivided PlaneMesh or QuadMesh (raise Subdivide Width); vertex displacement needs vertices to move. filter_linear_mipmap and repeat_enable are sampler hints: Godot 4 sets texture filtering and repeat in the shader, not on the texture.
Fresnel, varyings and render modes
shader_type spatial;
render_mode blend_add, unshaded, cull_back, depth_draw_never;
uniform vec4 glow_color : source_color = vec4(0.2, 0.9, 1.0, 1.0);
uniform float power = 3.0;
varying vec3 world_pos;
void vertex() {
world_pos = (MODEL_MATRIX * vec4(VERTEX, 1.0)).xyz;
}
void fragment() {
float fresnel = pow(1.0 - clamp(dot(NORMAL, VIEW), 0.0, 1.0), power);
float scan = step(0.5, fract(world_pos.y * 10.0 - TIME));
ALBEDO = glow_color.rgb * fresnel * (0.6 + 0.4 * scan);
}render_modesets fixed pipeline state:blend_add(additive blending),unshaded(no lighting:ALBEDOis the final color),cull_disabled/cull_front,depth_draw_never/depth_draw_always,specular_toon,diffuse_toon, and more.varyingpasses a value fromvertex()tofragment(), like a GLSLout/inpair.MODEL_MATRIXtransforms model space to world space. Other matrices:VIEW_MATRIX,INV_VIEW_MATRIX,PROJECTION_MATRIX.NORMALandVIEWare both view space infragment(), so their dot product is the Fresnel term from Rim Light and Fresnel.
Custom lighting with light()
Write a light() function and Godot calls it once per light for each pixel. You add your contribution to DIFFUSE_LIGHT and SPECULAR_LIGHT:
shader_type spatial;
uniform vec4 albedo : source_color = vec4(0.9, 0.4, 0.3, 1.0);
uniform int bands = 3;
void fragment() {
ALBEDO = albedo.rgb;
}
void light() {
float ndl = clamp(dot(NORMAL, LIGHT), 0.0, 1.0);
float toon = floor(ndl * float(bands)) / float(bands); // cel-shaded steps
DIFFUSE_LIGHT += toon * ATTENUATION * LIGHT_COLOR / PI;
}Use +=: overwriting would drop every light but the last. The Toon and Cel Shading lesson explains the banding.
Note: Godot 4 scales
LIGHT_COLORby π for physically based lights, which is why examples (including Godot's own) divide byPI. Without it, toon lighting looks blown out.
canvas_item shaders: 2D
A canvas_item shader on a Sprite2D or ColorRect is the closest thing in Godot to this course's playgrounds. COLOR is the output, TEXTURE the node's texture, and SCREEN_UV the position on screen:
shader_type canvas_item;
uniform float flash : hint_range(0.0, 1.0) = 0.0; // set to 1.0 when the enemy is hit
void fragment() {
vec4 tex = texture(TEXTURE, UV);
COLOR = vec4(mix(tex.rgb, vec3(1.0), flash), tex.a);
}The same effect as a live shader here, with flash driven by time instead of a script:
void mainImage(out vec4 fragColor, in vec2 fragCoord) {
vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y;
float body = 1.0 - smoothstep(0.30, 0.31, length(uv)); // a round "sprite"
vec3 tex = mix(vec3(0.1), vec3(0.85, 0.25, 0.3), body);
float flash = pow(max(0.0, sin(iTime * 3.0)), 8.0); // short white pulses
fragColor = vec4(mix(tex, vec3(1.0), flash * body), 1.0);
}For full-screen 2D effects, put a canvas_item shader on a ColorRect that covers the screen and read the screen with uniform sampler2D screen_tex : hint_screen_texture; (Godot 4 replaced the old SCREEN_TEXTURE built-in with this hint).
Porting GLSL to Godot
| GLSL (this course) | Godot |
|---|---|
void mainImage(...) |
void fragment() |
iTime |
TIME |
fragColor = vec4(c, 1.0) |
COLOR = vec4(c, 1.0) (canvas_item) or ALBEDO = c (spatial) |
fragCoord / iResolution.xy |
UV (on the node) or SCREEN_UV |
uniform vec3 color; |
uniform vec3 color : source_color; |
discard; |
discard; (same) |
See the Godot course for materials, WorldEnvironment glow and the editor side.
Test yourself
In a Godot spatial shader, what does writing ALBEDO in fragment() do?
- Sets the final pixel color, ignoring lights
- Sets the surface base color, which Godot's renderer then lights
- Sets the vertex color
- Sets the emission
What does : source_color on a uniform vec4 do?
- Makes it read-only
- Marks it as an sRGB color: color picker in the Inspector and conversion to linear
- Stores it per instance
- Makes it a texture
Why should a light() function use DIFFUSE_LIGHT += ... instead of =?
=is a syntax error- light() runs once per light, and
=would discard the other lights' contributions - It is faster
- Godot requires all outputs to be accumulated