Up to date

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

Преобразование GLSL в шейдеры Godot

В этом документе объясняются различия между языком шейдеров Godot и GLSL, и даются практические советы по переносу шейдеров из других источников, таких как Shadertoy и The Book of Shaders, в шейдеры Godot.

Для получения подробной информации о языке шейдеров Godot, пожалуйста, обратитесь к ссылке Shading Language.

GLSL

В Godot используется язык шейдеров, основанный на GLSL, с добавлением нескольких функций, отвечающих за качество жизни. Соответственно, большинство функций, доступных в GLSL, доступны и в языке шейдеров Godot.

Шейдерные программы

В GLSL каждый шейдер использует отдельную программу. У вас есть одна программа для вершинного шейдера и одна для фрагментного шейдера. В Godot у вас есть один шейдер, который содержит функцию vertex и/или fragment. Если вы решили написать только одну функцию, Godot предоставит другую.

Godot позволяет совместно использовать унифицированные переменные и функции, определяя фрагментный и вершинный шейдеры в одном файле. В GLSL вершинные и фрагментные программы не могут совместно использовать переменные, за исключением случаев, когда используются вариации.

Атрибуты вершин

В GLSL вы можете передавать информацию о каждой вершине с помощью атрибутов и иметь возможность передавать её как можно больше или меньше. В Godot у вас есть определенное количество входных атрибутов, включая VERTEX (позиция), COLOR, UV, UV2, NORMAL. На странице каждого шейдера в разделе документации "Ссылки на шейдеры" приводится полный список вершинных атрибутов.

gl_Position

gl_Position получает конечную позицию вершины, указанной в вершинном шейдере. Она задаётся пользователем в пространстве клипа. Обычно в GLSL положение вершины в пространстве модели передается с помощью атрибута вершины под названием position, а преобразование из пространства модели в пространство клипа выполняется вручную.

В Godot, VERTEX определяет положение вершины в пространстве модели в начале функции vertex. Godot также обрабатывает окончательное преобразование в пространство клипа после выполнения пользовательской функции vertex. Если вы хотите пропустить преобразование из пространства модели в пространство вида, вы можете установить render_mode на skip_vertex_transform. Если вы хотите пропустить все преобразования, установите render_mode в skip_vertex_transform и установите PROJECTION_MATRIX в mat4(1.0), чтобы обнулить окончательное преобразование из пространства вида в пространство клипа.

Varуings

Varyings - это тип переменных, которые можно передавать из вершинного шейдера во фрагментный шейдер. В современном GLSL (3.0 и выше) переменные определяются с помощью ключевых слов in и out. Переменная, выходящая из вершинного шейдера, определяется с помощью out в вершинном шейдере и in во фрагментном шейдере.

Main

В GLSL каждая шейдерная программа выглядит как самодостаточная программа в стиле языка Си. Соответственно, главной точкой входа является main. Если вы копируете вершинный шейдер, переименуйте main в vertex, а если вы копируете фрагментный шейдер, переименуйте main в fragment.

Макросы

The Godot shader preprocessor supports the following macros:

  • #define / #undef

  • #if, #elif, #else, #endif, defined(), #ifdef, #ifndef

  • #include (only .gdshaderinc files and with a maximum depth of 25)

  • #pragma disable_preprocessor, which disables preprocessing for the rest of the file

Переменные

В GLSL есть множество встроенных переменных, которые жёстко закодированы. Эти переменные не являются унифицированными, поэтому их нельзя редактировать из основной программы.

Переменная

Тип

Equivalent

Описание

gl_FragColor

out vec4

COLOR

Output color for each pixel.

gl_FragCoord

vec4

FRAGCOORD

For full screen quads. For smaller quads, use UV.

gl_Position

vec4

VERTEX

Position of Vertex, output from Vertex Shader.

gl_PointSize

float

POINT_SIZE

Size of Point primitive.

gl_PointCoord

vec2

POINT_COORD

Position on point when drawing Point primitives.

gl_FrontFаcing

bool

FRONT_FACING

True if front face of primitive.

Координаты

gl_FragCoord in GLSL and FRAGCOORD in the Godot shading language use the same coordinate system. If using UV in Godot, the y-coordinate will be flipped upside down.

Точность

In GLSL, you can define the precision of a given type (float or int) at the top of the shader with the precision keyword. In Godot, you can set the precision of individual variables as you need by placing precision qualifiers lowp, mediump, and highp before the type when defining the variable. For more information, see the Shading Language reference.

Shаdertoy

Shadertoy is a website that makes it easy to write fragment shaders and create pure magic.

Shadertoy does not give the user full control over the shader. It handles all the input and uniforms and only lets the user write the fragment shader.

Типы

Shadertoy uses the webgl spec, so it runs a slightly different version of GLSL. However, it still has the regular types, including constants and macros.

mаinImage

The main point of entry to a Shadertoy shader is the mainImage function. mainImage has two parameters, fragColor and fragCoord, which correspond to COLOR and FRAGCOORD in Godot, respectively. These parameters are handled automatically in Godot, so you do not need to include them as parameters yourself. Anything in the mainImage function should be copied into the fragment function when porting to Godot.

Переменные

Чтобы сделать написание фрагментных шейдеров простым и легким, Shadertoy обрабатывает передачу множества полезной информации из основной программы в фрагментный шейдер за вас. Некоторые из них не имеют аналогов в Godot, потому что Godot решил не делать их доступными по умолчанию. Это нормально, потому что Godot дает вам возможность создавать свои собственные формы. Для переменных, эквиваленты которых перечислены как "Provide with Uniform", пользователи сами отвечают за создание такой формы. Описание дает читателю подсказку о том, что можно передать в качестве замены.

Переменная

Тип

Equivalent

Описание

frаgColor

out vec4

COLOR

Output color for each pixel.

fragCoord

vec2

FRAGCOORD.xy

For full screen quads. For smaller quads, use UV.

iRеsolution

vec3

1.0 / SCREEN_PIXEL_SIZE

Can also pass in manually.

iTime

float

TIME

Time since shader started.

iTimeDelta

float

Provide with Uniform

Time to render previous frame.

iFrame

float

Provide with Uniform

Frame number.

iChannelTime[4]

float

Provide with Uniform

Time since that particular texture started.

iMouse

vec4

Provide with Uniform

Mouse position in pixel coordinates.

iDate

vec4

Provide with Uniform

Current date, expressed in seconds.

iChannelResolution[4]

vec3

1.0 / TEXTURE_PIXEL_SIZE

Resolution of particular texture.

iChanneli

Sampler2D

TEXTURE

Godot provides only one built-in; user can make more.

Координаты

fragCoord behaves the same as gl_FragCoord in GLSL and FRAGCOORD in Godot.

The Book of Shaders

Similar to Shadertoy, The Book of Shaders provides access to a fragment shader in the web browser, with which the user may interact. The user is restricted to writing fragment shader code with a set list of uniforms passed in and with no ability to add additional uniforms.

For further help on porting shaders to various frameworks generally, The Book of Shaders provides a page on running shaders in various frameworks.

Типы

The Book of Shaders uses the webgl spec, so it runs a slightly different version of GLSL. However, it still has the regular types, including constants and macros.

Main

The entry point for a Book of Shaders fragment shader is main, just like in GLSL. Everything written in a Book of Shaders main function should be copied into Godot's fragment function.

Переменные

The Book of Shaders sticks closer to plain GLSL than Shadertoy does. It also implements fewer uniforms than Shadertoy.

Переменная

Тип

Equivalent

Описание

gl_FragColor

out vec4

COLOR

Output color for each pixel.

gl_FragCoord

vec4

FRAGCOORD

For full screen quads. For smaller quads, use UV.

u_resolution

vec2

1.0 / SCREEN_PIXEL_SIZE

Can also pass in manually.

u_time

float

TIME

Time since shader started.

u_mouse

vec2

Provide with Uniform

Mouse position in pixel coordinates.

Координаты

The Book of Shaders uses the same coordinate system as GLSL.