shader_preprocessor.rst 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404
  1. .. _doc_shader_preprocessor:
  2. Shader preprocessor
  3. ===================
  4. Why use a shader preprocessor?
  5. ------------------------------
  6. In programming languages, a *preprocessor* allows changing the code before the
  7. compiler reads it. Unlike the compiler, the preprocessor does not care about
  8. whether the syntax of the preprocessed code is valid. The preprocessor always
  9. performs what the *directives* tell it to do. A directive is a statement
  10. starting with a hash symbol (``#``). It is not a *keyword* of the shader
  11. language (such as ``if`` or ``for``), but a special kind of token within the
  12. language.
  13. From Godot 4.0 onwards, you can use a shader preprocessor within text-based
  14. shaders. The syntax is similar to what most GLSL shader compilers support
  15. (which in turn is similar to the C/C++ preprocessor).
  16. .. note::
  17. The shader preprocessor is not available in :ref:`visual shaders <doc_visual_shaders>`.
  18. If you need to introduce preprocessor statements to a visual shader, you can
  19. convert it to a text-based shader using the **Convert to Shader** option in
  20. the VisualShader inspector resource dropdown. This conversion is a one-way
  21. operation; text shaders cannot be converted back to visual shaders.
  22. Directives
  23. ----------
  24. General syntax
  25. ^^^^^^^^^^^^^^
  26. - Preprocessor directives do not use brackets (``{}``), but can use parentheses.
  27. - Preprocessor directives **never** end with semicolons.
  28. - Preprocessor directives can span several lines by ending each line with a
  29. blackslash (``\``). The first line break *not* featuring a backslash will end
  30. the preprocessor statement.
  31. #define
  32. ^^^^^^^
  33. \ **Syntax:** ``#define <identifier> [replacement_code]``.
  34. Defines the identifier after that directive as a macro, and replaces all
  35. successive occurrences of it with the replacement code given in the shader.
  36. Replacement is performed on a "whole words" basis, which means no replacement is
  37. performed if the string is part of another string (without any spaces separating
  38. it).
  39. Defines with replacements may also have one or more *arguments*, which can then
  40. be passed when referencing the define (similar to a function call).
  41. If the replacement code is not defined, the identifier may only be used with
  42. ``#ifdef`` or ``#ifndef`` directives.
  43. Compared to constants (``const CONSTANT = value;``), ``#define`` can be used
  44. anywhere within the shader. ``#define`` can also be used to insert arbitrary
  45. shader code at any location, while constants can't do that.
  46. .. code-block:: glsl
  47. shader_type spatial;
  48. // Notice the lack of semicolon at the end of the line, as the replacement text
  49. // shouldn't insert a semicolon on its own.
  50. #define USE_MY_COLOR
  51. #define MY_COLOR vec3(1, 0, 0)
  52. // Replacement with arguments.
  53. // All arguments are required (no default values can be provided).
  54. #define BRIGHTEN_COLOR(r, g, b) vec3(r + 0.5, g + 0.5, b + 0.5)
  55. // Multiline replacement using backslashes for continuation:
  56. #define SAMPLE(param1, param2, param3, param4) long_function_call( \
  57. param1, \
  58. param2, \
  59. param3, \
  60. param4 \
  61. )
  62. void fragment() {
  63. #ifdef USE_MY_COLOR
  64. ALBEDO = MY_COLOR;
  65. #endif
  66. }
  67. Defining a ``#define`` for an identifier that is already defined results in an
  68. error. To prevent this, use ``#undef <identifier>``.
  69. #undef
  70. ^^^^^^
  71. **Syntax:** ``#undef identifier``
  72. The ``#undef`` directive may be used to cancel a previously defined ``#define`` directive:
  73. .. code-block:: glsl
  74. #define MY_COLOR vec3(1, 0, 0)
  75. vec3 get_red_color() {
  76. return MY_COLOR;
  77. }
  78. #undef MY_COLOR
  79. #define MY_COLOR vec3(0, 1, 0)
  80. vec3 get_green_color() {
  81. return MY_COLOR;
  82. }
  83. // Like in most preprocessors, undefining a define that was not previously defined is allowed
  84. // (and won't print any warning or error).
  85. #undef THIS_DOES_NOT_EXIST
  86. Without ``#undef`` in the above example, there would be a macro redefinition error.
  87. #if
  88. ^^^
  89. **Syntax:** ``#if <condition>``
  90. The ``#if`` directive checks whether the ``condition`` passed. If it evaluates
  91. to a non-zero value, the code block is included, otherwise it is skipped.
  92. To evaluate correctly, the condition must be an expression giving a simple
  93. floating-point, integer or boolean result. There may be multiple condition
  94. blocks connected by ``&&`` (AND) or ``||`` (OR) operators. It may be continued
  95. by a ``#else`` block, but **must** be ended with the ``#endif`` directive.
  96. .. code-block:: glsl
  97. #define VAR 3
  98. #define USE_LIGHT 0 // Evaluates to `false`.
  99. #define USE_COLOR 1 // Evaluates to `true`.
  100. #if VAR == 3 && (USE_LIGHT || USE_COLOR)
  101. // Condition is `true`. Include this portion in the final shader.
  102. #endif
  103. Using the ``defined()`` *preprocessor function*, you can check whether the
  104. passed identifier is defined a by ``#define`` placed above that directive. This
  105. is useful for creating multiple shader versions in the same file. It may be
  106. continued by a `#else` block, but must be ended with the ``#endif`` directive.
  107. The ``defined()`` function's result can be negated by using the ``!`` (boolean NOT)
  108. symbol in front of it. This can be used to check whether a define is *not* set.
  109. .. code-block:: glsl
  110. #define USE_LIGHT
  111. #define USE_COLOR
  112. // Correct syntax:
  113. #if defined(USE_LIGHT) || defined(USE_COLOR) || !defined(USE_REFRACTION)
  114. // Condition is `true`. Include this portion in the final shader.
  115. #endif
  116. Be careful, as ``defined()`` must only wrap a single identifier within parentheses, never more:
  117. .. code-block:: glsl
  118. // Incorrect syntax (parentheses are not placed where they should be):
  119. #if defined(USE_LIGHT || USE_COLOR || !USE_REFRACTION)
  120. // This will cause an error or not behave as expected.
  121. #endif
  122. .. tip::
  123. In the shader editor, preprocessor branches that evaluate to ``false`` (and
  124. are therefore excluded from the final compiled shader) will appear grayed
  125. out. This does not apply to run-time ``if`` statements.
  126. **#if preprocessor versus if statement: Performance caveats**
  127. The :ref:`shading language <doc_shading_language>` supports run-time ``if`` statements:
  128. .. code-block:: glsl
  129. uniform bool USE_LIGHT = true;
  130. if (USE_LIGHT) {
  131. // This part is included in the compiled shader, and always run.
  132. } else {
  133. // This part is included in the compiled shader, but never run.
  134. }
  135. If the uniform is never changed, this behaves identical to the following usage
  136. of the ``#if`` preprocessor statement:
  137. .. code-block:: glsl
  138. #define USE_LIGHT
  139. #if defined(USE_LIGHT)
  140. // This part is included in the compiled shader, and always run.
  141. #else
  142. // This part is *not* included in the compiled shader (and therefore never run).
  143. #endif
  144. However, the ``#if`` variant can be faster in certain scenarios. This is because
  145. all run-time branches in a shader are still compiled and variables within
  146. those branches may still take up register space, even if they are never run in
  147. practice.
  148. Modern GPUs are `quite effective <https://medium.com/@jasonbooth_86226/branching-on-a-gpu-18bfc83694f2>`__
  149. at performing "static" branching. "Static" branching refers to ``if`` statements where
  150. *all* pixels/vertices evaluate to the same result in a given shader invocation. However,
  151. high amounts of :abbr:`VGPRs (Vector General-Purpose Register)` (which can be caused by
  152. having too many branches) can still slow down shader execution significantly.
  153. #elif
  154. ^^^^^
  155. The ``#elif`` directive stands for "else if" and checks the condition passed if
  156. the above ``#if`` evaluated to ``false``. ``#elif`` can only be used within an
  157. ``#if`` block. It is possible to use several ``#elif``s in the same ``#if`` statement.
  158. .. code-block:: glsl
  159. #define VAR 3
  160. #define USE_LIGHT 0 // Evaluates to `false`.
  161. #define USE_COLOR 1 // Evaluates to `true`.
  162. #if VAR == 3 && (USE_LIGHT || USE_COLOR)
  163. // Condition is `true`. Include this portion in the final shader.
  164. #endif
  165. Like with ``#if``, the ``defined()`` preprocessor function can be used:
  166. .. code-block:: glsl
  167. #define SHADOW_QUALITY_MEDIUM
  168. #if defined(SHADOW_QUALITY_HIGH)
  169. // High shadow quality.
  170. #elif defined(SHADOW_QUALITY_MEDIUM)
  171. // Medium shadow quality.
  172. #else
  173. // Low shadow quality.
  174. #endif
  175. #ifdef
  176. ^^^^^^
  177. **Syntax:** ``#ifdef <identifier>``
  178. This is a shorthand for ``#if defined(...)``. Checks whether the passed
  179. identifier is defined by ``#define`` placed above that directive. This is useful
  180. for creating multiple shader versions in the same file. It may be continued by a
  181. ``#else`` block, but must be ended with the `#endif` directive.
  182. .. code-block:: glsl
  183. #define USE_LIGHT
  184. #ifdef USE_LIGHT
  185. #endif
  186. The processor does *not* support ``#elifdef`` as a shortcut for ``#elif defined(...)``.
  187. Instead, use the following series of ``#ifdef`` and ``#else`` when you need more
  188. than two branches:
  189. .. code-block:: glsl
  190. #define SHADOW_QUALITY_MEDIUM
  191. #ifdef SHADOW_QUALITY_HIGH
  192. // High shadow quality.
  193. #else
  194. #ifdef SHADOW_QUALITY_MEDIUM
  195. // Medium shadow quality.
  196. #else
  197. // Low shadow quality.
  198. #endif // This ends `SHADOW_QUALITY_MEDIUM`'s branch.
  199. #endif // This ends `SHADOW_QUALITY_HIGH`'s branch.
  200. #ifndef
  201. ^^^^^^^
  202. **Syntax:** ``#ifndef <identifier>``
  203. This is a shorthand for ``#if !defined(...)``. Similar to ``#ifdef``, but checks
  204. whether the passed identifier is **not** defined by `#define` before that
  205. directive.
  206. This is the exact opposite of ``#ifdef``; it will always match in situations
  207. where ``#ifdef`` would never match, and vice versa.
  208. .. code-block:: glsl
  209. #define USE_LIGHT
  210. #ifndef USE_LIGHT
  211. // Evaluates to `false`. This portion won't be included in the final shader.
  212. #endif
  213. #ifndef USE_COLOR
  214. // Evaluates to `true`. This portion will be included in the final shader.
  215. #endif
  216. #else
  217. ^^^^^
  218. **Syntax:** ``#else``
  219. Defines the optional block which is included when the previously defined `#if`,
  220. ``#ifdef` or `#ifndef`` directive evaluates to false.
  221. .. code-block:: glsl
  222. shader_type spatial;
  223. #define MY_COLOR vec3(1.0, 0, 0)
  224. void fragment() {
  225. #ifndef MY_COLOR
  226. ALBEDO = MY_COLOR;
  227. #else
  228. ALBEDO = vec3(0, 0, 1.0);
  229. #endif
  230. }
  231. #endif
  232. ^^^^^^
  233. **Syntax:** ``#endif``
  234. Used as terminator for the ``#if``, ``#`ifdef``, ``#ifndef`` or subsequent ``#else`` directives.
  235. #include
  236. ^^^^^^^^
  237. \ **Syntax:** `#include "path"`.
  238. The ``#include`` directive includes the *entire* content of a shader include
  239. file in a shader. ``"path"`` can be an absolute ``res://`` path or relative to
  240. the current shader file. Relative paths are only allowed in shaders that are
  241. saved to ``.gdshader`` or ``.gdshaderinc`` files, while absolute paths can be
  242. used in shaders that are built into a scene/resource file.
  243. This directive may be used in any place, but is recommended at
  244. the beginning of the shader file, after the ``shader_type`` to prevent possible
  245. errors. The shader include may be created by using a **File > Create Shader
  246. Include** menu option of the shader editor.
  247. ``#include`` is useful for creating libraries of helper functions (or macros)
  248. and reducing code duplication. When using ``#include``, be careful about naming
  249. collisions, as redefining functions or macros is not allowed.
  250. ``#include`` is subject to several restrictions:
  251. - Only shader include resources (ending with ``.gdshaderinc``) can be included.
  252. ``.gdshader`` files cannot be included by another shader, but a
  253. ``.gdshaderinc`` file can include other ``.gdshaderinc`` files.
  254. - Cyclic dependencies are **not** allowed and will result in an error.
  255. - To avoid infinite recursion, include depth is limited to 25 steps.
  256. Example shader include file:
  257. .. code-block:: glsl
  258. // fancy_color.gdshaderinc
  259. // While technically allowed, there is usually no `shader_type` declaration in include files.
  260. vec3 get_fancy_color() {
  261. return vec3(0.3, 0.6, 0.9);
  262. }
  263. Example base shader (using the include file we created above):
  264. .. code-block:: glsl
  265. // material.gdshader
  266. shader_type spatial;
  267. #include "res://fancy_color.gdshaderinc"
  268. void fragment() {
  269. // No error, as we've included a definition for `get_fancy_color()` via the shader include.
  270. COLOR = get_fancy_color();
  271. }
  272. #pragma
  273. ^^^^^^^
  274. \ **Syntax:** `#pragma value`.
  275. The `#pragma` directive provides additional information to the preprocessor or compiler.
  276. Currently, it may have only one value: ``disable_preprocessor``. If you don't need
  277. the preprocessor, use that directive to speed up shader compilation by excluding
  278. the preprocessor step.
  279. .. code-block:: glsl
  280. #pragma disable_preprocessor
  281. #if USE_LIGHT
  282. // This causes a shader compilation error, as the `#if USE_LIGHT` and `#endif`
  283. // are included as-is in the final shader code.
  284. #endif