Up to date

This page is up to date for Godot 4.2. If you still find outdated information, please open an issue.

Shaders CanvasItem

Los shaders CanvasItem se usan para dibujar todos los elementos 2D en Godot. Estos incluyen todos los nodos que heredan de CanvasItems, y todos los elementos GUI.

Los shaders CanvasItem contienen menos variables incorporadas y funcionalidad que los shaders espaciales, pero mantienen la misma estructura básica con funciones de vértice, fragmento y procesador de luz.

Modos de renderizado

Modo de renderizado

Descripción

blend_mix

Modo de blending por mezcla (alfa es transparencia), es el modo por defecto.

blend_add

Modo de blending aditivo.

blend_sub

Modo de blending substractivo.

blend_mul

Modo de blending multiplicativo.

blend_premul_alpha

Modo de blending con alfa premultiplicado.

blend_disabled

Desactivar la mezcla, los valores (incluido el alfa) se escriben tal cual.

unshaded

El resultado es sólo albedo. El material no recibe luces ni shading.

light_only

Sólo dibuja en light pass (cuando se usa multipass).

skip_vertex_transform

VERTEX needs to be transformed manually in vertex function.

world_vertex_coords

VERTEX is modified in world coordinates instead of local.

Funciones propias

Los valores marcados como "in" son de sólo lectura. Los valores marcados como "out" son de escritura opcional y no necesariamente contendrán valores sensibles. Los valores marcados como "inout" proporcionan un valor por defecto sensato y pueden escribirse opcionalmente. Los valores marcados como "in" no son objeto de escritura y no están marcados.

Funciones incorporadas globales

Las internas globales están disponibles en todas partes, incluyendo las funciones personalizadas.

Integrado

Descripción

en real TIME

Global time since the engine has started, in seconds (always positive). It's subject to the rollover setting (which is 3,600 seconds by default). It's not affected by time_scale or pausing, but you can define a global shader uniform to add a "scaled" TIME variable if desired.

in float PI

A PI constant (3.141592). A ration of circle's circumference to its diameter and amount of radians in half turn.

in float TAU

A TAU constant (6.283185). An equivalent of PI * 2 and amount of radians in full turn.

in float E

A E constant (2.718281). Euler's number and a base of the natural logarithm.

Incorporados en Vertex

Vertex data (VERTEX) is presented in local space (pixel coordinates, relative to the Node2D's origin). If not written to, these values will not be modified and be passed through as they came.

The user can disable the built-in model to world transform (world to screen and projection will still happen later) and do it manually with the following code:

shader_type canvas_item;
render_mode skip_vertex_transform;

void vertex() {

    VERTEX = (MODEL_MATRIX * vec4(VERTEX, 0.0, 1.0)).xy;
}

Otros típos integrados, como UV y COLOR, también se pasan a la función fragment si no están modificados.

Para el instanciamiento, la variable INSTANCE_CUSTOM contiene los datos personalizados de la instancia. Cuando se usan partículas, esta información es normalment:

  • x: Ángulo de rotación en radianes.

  • y: Fase durante la vida (0 a 1).

  • z: Fotograma de animación.

Integrado

Descripción

in mat4 MODEL_MATRIX

Local space to world space transform. World space is the coordinates you normally use in the editor.

in mat4 CANVAS_MATRIX

World space to canvas space transform. In canvas space the origin is the upper-left corner of the screen and coordinates ranging from (0, 0) to viewport size.

in mat4 SCREEN_MATRIX

Canvas space to clip space. In clip space coordinates ranging from (-1, -1) to (1, 1).

in int INSTANCE_ID

ID de instancia para el instanciamiento.

in vec4 INSTANCE_CUSTOM

Datos personalizados de la instancia.

in booleano AT_LIGHT_PASS

Siempre false.

in vec2 TEXTURE_PIXEL_SIZE

Normalized pixel size of default 2D texture. For a Sprite2D with a texture of size 64x32px, TEXTURE_PIXEL_SIZE = vec2(1/64, 1/32)

inout vec2 VERTEX

Vertex, in local space.

in int VERTEX_ID

The index of the current vertex in the vertex buffer.

inout vec2 UV

Normalized texture coordinates. Range from 0 to 1.

inout vec4 COLOR

El color del vértice primitivo.

inout real POINT_SIZE

Tamaño del punto para el dibujo del punto.

Incorporados en Fragment

Certain Nodes (for example, Sprite2Ds) display a texture by default. However, when a custom fragment function is attached to these nodes, the texture lookup needs to be done manually. Godot provides the texture color in the COLOR built-in variable multiplied by the node's color. To read the texture color by itself, you can use:

COLOR = texture(TEXTURE, UV);

Similarly, if a normal map is used in the CanvasTexture, Godot uses it by default and assigns its value to the built-in NORMAL variable. If you are using a normal map meant for use in 3D, it will appear inverted. In order to use it in your shader, you must assign it to the NORMALMAP property. Godot will handle converting it for use in 2D and overwriting NORMAL.

NORMALMAP = texture(NORMAL_TEXTURE, UV).rgb;

Integrado

Descripción

in vec4 FRAGCOORD

Coordinate of pixel center. In screen space. xy specifies position in window. Origin is lower-left.

in vec2 SCREEN_PIXEL_SIZE

El tamaño de los píxeles individuales. Igual a la inversa de la resolución.

in vec2 POINT_COORD

Coordenadas para dibujar puntos.

sampler2D TEXTURE

Textura 2D por defecto.

in vec2 TEXTURE_PIXEL_SIZE

Normalized pixel size of default 2D texture. For a Sprite2D with a texture of size 64x32px, TEXTURE_PIXEL_SIZE = vec2(1/64, 1/32)

in booleano AT_LIGHT_PASS

Siempre false.

sampler2D SPECULAR_SHININESS_TEXTURE

Specular shininess texture of this object.

in vec4 SPECULAR_SHININESS

Specular shininess color, as sampled from the texture.

in vec2 UV

UV de la función del vértice.

in vec2 SCREEN_UV

Muestra la coordenada UV para el píxel actual.

sampler2D SCREEN_TEXTURE

Removed in Godot 4. Use a sampler2D with hint_screen_texture instead.

inout vec3 NORMAL

Lectura normal de NORMAL_TEXTURE. Escrito.

sampler2D NORMAL_TEXTURE

Textura normal 2D por defecto.

out vec3 NORMAL_MAP

Configures normal maps meant for 3D for use in 2D. If used, overrides NORMAL.

out float NORMAL_MAP_DEPTH

Profundidad del Normalmap para el escalado.

inout vec2 VERTEX

Pixel position in screen space.

inout vec2 SHADOW_VERTEX

Same as VERTEX but can be written to alter shadows.

inout vec3 LIGHT_VERTEX

Same as VERTEX but can be written to alter lighting. Z component represents height.

inout vec4 COLOR

Color from vertex function multiplied by the TEXTURE color. Also output color value.

Incorporados en Light

Light processor functions work differently in Godot 4.x than they did in Godot 3.x. In Godot 4.x all lighting is done during the regular draw pass. In other words, Godot no longer draws the object again for each light.

Use render_mode unshaded if you do not want the light processor function to run. Use render_mode light_only if you only want to see the impact of lighting on an object; this can be useful when you only want the object visible where it is covered by light.

If you define a light function it will replace the built in light function, even if your light function is empty.

Below is an example of a light shader that takes a CanvasItem's normal map into account:

void light() {
  float cNdotL = max(0.0, dot(NORMAL, LIGHT_DIRECTION));
  LIGHT = vec4(LIGHT_COLOR.rgb * COLOR.rgb * LIGHT_ENERGY * cNdotL, LIGHT_COLOR.a);
}

Integrado

Descripción

in vec4 FRAGCOORD

Coordinate of pixel center. In screen space. xy specifies position in window. Origin is lower-left.

in vec3 NORMAL

Normal de entrada.

in vec4 COLOR

Input Color. This is the output of the fragment function.

in vec2 UV

UV de la función de vértice, equivalente a la UV en la función de fragmento.

sampler2D TEXTURE

Textura actual en uso para CanvasItem.

in vec2 TEXTURE_PIXEL_SIZE

Normalized pixel size of TEXTURE. For a Sprite2D with a TEXTURE of size 64x32px, TEXTURE_PIXEL_SIZE = vec2(1/64, 1/32)

in vec2 SCREEN_UV

Muestra la coordenada UV para el píxel actual.

in vec2 POINT_COORD

UV para Point Sprite.

in vec4 LIGHT_COLOR

Color of Light multiplied by Light's texture.

in float LIGHT_ENERGY

Energy multiplier of Light.

in vec3 LIGHT_POSITION

Position of Light in screen space. If using a DirectionalLight2D this is always vec3(0,0,0).

in vec3 LIGHT_DIRECTION

Direction of Light in screen space.

in bool LIGHT_IS_DIRECTIONAL

true if this pass is a DirectionalLight2D.

in vec3 LIGHT_VERTEX

Pixel position, in screen space as modified in the fragment function.

inout vec4 LIGHT

Output color for this Light.

in vec4 SPECULAR_SHININESS

Specular shininess, as set in the object's texture.

out vec4 SHADOW_MODULATE

Multiply shadows cast at this point by this color.

SDF functions

There are a few additional functions implemented to sample an automatically generated Signed Distance Field texture. These functions available for Fragment and Light functions of CanvasItem shaders.

The signed distance field is generated from LightOccluder2D nodes present in the scene with the SDF Collision property enabled (which is the default). See the 2D lights and shadows documentation for more information.

Función

Descripción

float texture_sdf (vec2 sdf_pos)

Realiza una lectura de textura SDF.

vec2 texture_sdf_normal (vec2 sdf_pos)

Calculates a normal from the SDF texture.

vec2 sdf_to_screen_uv (vec2 sdf_pos)

Converts a SDF to screen UV.

vec2 screen_uv_to_sdf (vec2 uv)

Convierte UV de pantalla a SDF.