shader_preprocessor.rst 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493
  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 (with the exception of ``#define``,
  28. where this is allowed but potentially dangerous).
  29. - Preprocessor directives can span several lines by ending each line with a
  30. backslash (``\``). The first line break *not* featuring a backslash will end
  31. the preprocessor statement.
  32. #define
  33. ^^^^^^^
  34. **Syntax:** ``#define <identifier> [replacement_code]``.
  35. Defines the identifier after that directive as a macro, and replaces all
  36. successive occurrences of it with the replacement code given in the shader.
  37. Replacement is performed on a "whole words" basis, which means no replacement is
  38. performed if the string is part of another string (without any spaces or
  39. operators separating it).
  40. Defines with replacements may also have one or more *arguments*, which can then
  41. be passed when referencing the define (similar to a function call).
  42. If the replacement code is not defined, the identifier may only be used with
  43. ``#ifdef`` or ``#ifndef`` directives.
  44. If the *concatenation* symbol (``##``) is present in the replacement code then
  45. it will be removed upon macro insertion, together with any space surrounding
  46. it, and join the surrounding words and arguments into a new token.
  47. .. code-block:: glsl
  48. uniform sampler2D material0;
  49. #define SAMPLE(N) vec4 tex##N = texture(material##N, UV)
  50. void fragment() {
  51. SAMPLE(0);
  52. ALBEDO = tex0.rgb;
  53. }
  54. Compared to constants (``const CONSTANT = value;``), ``#define`` can be used
  55. anywhere within the shader (including in uniform hints).
  56. ``#define`` can also be used to insert arbitrary shader code at any location,
  57. while constants can't do that.
  58. .. code-block:: glsl
  59. shader_type spatial;
  60. // Notice the lack of semicolon at the end of the line, as the replacement text
  61. // shouldn't insert a semicolon on its own.
  62. // If the directive ends with a semicolon, the semicolon is inserted in every usage
  63. // of the directive, even when this causes a syntax error.
  64. #define USE_MY_COLOR
  65. #define MY_COLOR vec3(1, 0, 0)
  66. // Replacement with arguments.
  67. // All arguments are required (no default values can be provided).
  68. #define BRIGHTEN_COLOR(r, g, b) vec3(r + 0.5, g + 0.5, b + 0.5)
  69. // Multiline replacement using backslashes for continuation:
  70. #define SAMPLE(param1, param2, param3, param4) long_function_call( \
  71. param1, \
  72. param2, \
  73. param3, \
  74. param4 \
  75. )
  76. void fragment() {
  77. #ifdef USE_MY_COLOR
  78. ALBEDO = MY_COLOR;
  79. #endif
  80. }
  81. Defining a ``#define`` for an identifier that is already defined results in an
  82. error. To prevent this, use ``#undef <identifier>``.
  83. #undef
  84. ^^^^^^
  85. **Syntax:** ``#undef identifier``
  86. The ``#undef`` directive may be used to cancel a previously defined ``#define`` directive:
  87. .. code-block:: glsl
  88. #define MY_COLOR vec3(1, 0, 0)
  89. vec3 get_red_color() {
  90. return MY_COLOR;
  91. }
  92. #undef MY_COLOR
  93. #define MY_COLOR vec3(0, 1, 0)
  94. vec3 get_green_color() {
  95. return MY_COLOR;
  96. }
  97. // Like in most preprocessors, undefining a define that was not previously defined is allowed
  98. // (and won't print any warning or error).
  99. #undef THIS_DOES_NOT_EXIST
  100. Without ``#undef`` in the above example, there would be a macro redefinition error.
  101. #if
  102. ^^^
  103. **Syntax:** ``#if <condition>``
  104. The ``#if`` directive checks whether the ``condition`` passed. If it evaluates
  105. to a non-zero value, the code block is included, otherwise it is skipped.
  106. To evaluate correctly, the condition must be an expression giving a simple
  107. floating-point, integer or boolean result. There may be multiple condition
  108. blocks connected by ``&&`` (AND) or ``||`` (OR) operators. It may be continued
  109. by a ``#else`` block, but **must** be ended with the ``#endif`` directive.
  110. .. code-block:: glsl
  111. #define VAR 3
  112. #define USE_LIGHT 0 // Evaluates to `false`.
  113. #define USE_COLOR 1 // Evaluates to `true`.
  114. #if VAR == 3 && (USE_LIGHT || USE_COLOR)
  115. // Condition is `true`. Include this portion in the final shader.
  116. #endif
  117. Using the ``defined()`` *preprocessor function*, you can check whether the
  118. passed identifier is defined a by ``#define`` placed above that directive. This
  119. is useful for creating multiple shader versions in the same file. It may be
  120. continued by a ``#else`` block, but must be ended with the ``#endif`` directive.
  121. The ``defined()`` function's result can be negated by using the ``!`` (boolean NOT)
  122. symbol in front of it. This can be used to check whether a define is *not* set.
  123. .. code-block:: glsl
  124. #define USE_LIGHT
  125. #define USE_COLOR
  126. // Correct syntax:
  127. #if defined(USE_LIGHT) || defined(USE_COLOR) || !defined(USE_REFRACTION)
  128. // Condition is `true`. Include this portion in the final shader.
  129. #endif
  130. Be careful, as ``defined()`` must only wrap a single identifier within parentheses, never more:
  131. .. code-block:: glsl
  132. // Incorrect syntax (parentheses are not placed where they should be):
  133. #if defined(USE_LIGHT || USE_COLOR || !USE_REFRACTION)
  134. // This will cause an error or not behave as expected.
  135. #endif
  136. .. tip::
  137. In the shader editor, preprocessor branches that evaluate to ``false`` (and
  138. are therefore excluded from the final compiled shader) will appear grayed
  139. out. This does not apply to runtime ``if`` statements.
  140. **#if preprocessor versus if statement: Performance caveats**
  141. The :ref:`shading language <doc_shading_language>` supports runtime ``if`` statements:
  142. .. code-block:: glsl
  143. uniform bool USE_LIGHT = true;
  144. if (USE_LIGHT) {
  145. // This part is included in the compiled shader, and always run.
  146. } else {
  147. // This part is included in the compiled shader, but never run.
  148. }
  149. If the uniform is never changed, this behaves identical to the following usage
  150. of the ``#if`` preprocessor statement:
  151. .. code-block:: glsl
  152. #define USE_LIGHT
  153. #if defined(USE_LIGHT)
  154. // This part is included in the compiled shader, and always run.
  155. #else
  156. // This part is *not* included in the compiled shader (and therefore never run).
  157. #endif
  158. However, the ``#if`` variant can be faster in certain scenarios. This is because
  159. all runtime branches in a shader are still compiled and variables within
  160. those branches may still take up register space, even if they are never run in
  161. practice.
  162. Modern GPUs are `quite effective <https://medium.com/@jasonbooth_86226/branching-on-a-gpu-18bfc83694f2>`__
  163. at performing "static" branching. "Static" branching refers to ``if`` statements where
  164. *all* pixels/vertices evaluate to the same result in a given shader invocation. However,
  165. high amounts of :abbr:`VGPRs (Vector General-Purpose Register)` (which can be caused by
  166. having too many branches) can still slow down shader execution significantly.
  167. #elif
  168. ^^^^^
  169. The ``#elif`` directive stands for "else if" and checks the condition passed if
  170. the above ``#if`` evaluated to ``false``. ``#elif`` can only be used within an
  171. ``#if`` block. It is possible to use several ``#elif`` statements after an ``#if`` statement.
  172. .. code-block:: glsl
  173. #define VAR 2
  174. #if VAR == 0
  175. // Not included.
  176. #elif VAR == 1
  177. // Not included.
  178. #elif VAR == 2
  179. // Condition is `true`. Include this portion in the final shader.
  180. #else
  181. // Not included.
  182. #endif
  183. Like with ``#if``, the ``defined()`` preprocessor function can be used:
  184. .. code-block:: glsl
  185. #define SHADOW_QUALITY_MEDIUM
  186. #if defined(SHADOW_QUALITY_HIGH)
  187. // High shadow quality.
  188. #elif defined(SHADOW_QUALITY_MEDIUM)
  189. // Medium shadow quality.
  190. #else
  191. // Low shadow quality.
  192. #endif
  193. #ifdef
  194. ^^^^^^
  195. **Syntax:** ``#ifdef <identifier>``
  196. This is a shorthand for ``#if defined(...)``. Checks whether the passed
  197. identifier is defined by ``#define`` placed above that directive. This is useful
  198. for creating multiple shader versions in the same file. It may be continued by a
  199. ``#else`` block, but must be ended with the ``#endif`` directive.
  200. .. code-block:: glsl
  201. #define USE_LIGHT
  202. #ifdef USE_LIGHT
  203. // USE_LIGHT is defined. Include this portion in the final shader.
  204. #endif
  205. The processor does *not* support ``#elifdef`` as a shortcut for ``#elif defined(...)``.
  206. Instead, use the following series of ``#ifdef`` and ``#else`` when you need more
  207. than two branches:
  208. .. code-block:: glsl
  209. #define SHADOW_QUALITY_MEDIUM
  210. #ifdef SHADOW_QUALITY_HIGH
  211. // High shadow quality.
  212. #else
  213. #ifdef SHADOW_QUALITY_MEDIUM
  214. // Medium shadow quality.
  215. #else
  216. // Low shadow quality.
  217. #endif // This ends `SHADOW_QUALITY_MEDIUM`'s branch.
  218. #endif // This ends `SHADOW_QUALITY_HIGH`'s branch.
  219. #ifndef
  220. ^^^^^^^
  221. **Syntax:** ``#ifndef <identifier>``
  222. This is a shorthand for ``#if !defined(...)``. Similar to ``#ifdef``, but checks
  223. whether the passed identifier is **not** defined by ``#define`` before that
  224. directive.
  225. This is the exact opposite of ``#ifdef``; it will always match in situations
  226. where ``#ifdef`` would never match, and vice versa.
  227. .. code-block:: glsl
  228. #define USE_LIGHT
  229. #ifndef USE_LIGHT
  230. // Evaluates to `false`. This portion won't be included in the final shader.
  231. #endif
  232. #ifndef USE_COLOR
  233. // Evaluates to `true`. This portion will be included in the final shader.
  234. #endif
  235. #else
  236. ^^^^^
  237. **Syntax:** ``#else``
  238. Defines the optional block which is included when the previously defined ``#if``,
  239. ``#elif``, ``#ifdef`` or ``#ifndef`` directive evaluates to false.
  240. .. code-block:: glsl
  241. shader_type spatial;
  242. #define MY_COLOR vec3(1.0, 0, 0)
  243. void fragment() {
  244. #ifdef MY_COLOR
  245. ALBEDO = MY_COLOR;
  246. #else
  247. ALBEDO = vec3(0, 0, 1.0);
  248. #endif
  249. }
  250. #endif
  251. ^^^^^^
  252. **Syntax:** ``#endif``
  253. Used as terminator for the ``#if``, ``#ifdef``, ``#ifndef`` or subsequent ``#else`` directives.
  254. #error
  255. ^^^^^^
  256. **Syntax:** ``#error <message>``
  257. The ``#error`` directive forces the preprocessor to emit an error with optional message.
  258. For example, it's useful when used within ``#if`` block to provide a strict limitation of the
  259. defined value.
  260. .. code-block:: glsl
  261. #define MAX_LOD 3
  262. #define LOD 4
  263. #if LOD > MAX_LOD
  264. #error LOD exceeds MAX_LOD
  265. #endif
  266. #include
  267. ^^^^^^^^
  268. **Syntax:** ``#include "path"``
  269. The ``#include`` directive includes the *entire* content of a shader include
  270. file in a shader. ``"path"`` can be an absolute ``res://`` path or relative to
  271. the current shader file. Relative paths are only allowed in shaders that are
  272. saved to ``.gdshader`` or ``.gdshaderinc`` files, while absolute paths can be
  273. used in shaders that are built into a scene/resource file.
  274. You can create new shader includes by using the **File > Create Shader Include**
  275. menu option of the shader editor, or by creating a new :ref:`ShaderInclude<class_ShaderInclude>` resource
  276. in the FileSystem dock.
  277. Shader includes can be included from within any shader, or other shader include, at
  278. any point in the file.
  279. When including shader includes in the global scope of a shader, it is recommended
  280. to do this after the initial ``shader_type`` statement.
  281. You can also include shader includes from within the body a function. Please note that
  282. the shader editor is likely going to report errors for your shader include's code, as it
  283. may not be valid outside of the context that it was written for. You can either choose
  284. to ignore these errors (the shader will still compile fine), or you can wrap the include
  285. in an ``#ifdef`` block that checks for a define from your shader.
  286. ``#include`` is useful for creating libraries of helper functions (or macros)
  287. and reducing code duplication. When using ``#include``, be careful about naming
  288. collisions, as redefining functions or macros is not allowed.
  289. ``#include`` is subject to several restrictions:
  290. - Only shader include resources (ending with ``.gdshaderinc``) can be included.
  291. ``.gdshader`` files cannot be included by another shader, but a
  292. ``.gdshaderinc`` file can include other ``.gdshaderinc`` files.
  293. - Cyclic dependencies are **not** allowed and will result in an error.
  294. - To avoid infinite recursion, include depth is limited to 25 steps.
  295. Example shader include file:
  296. .. code-block:: glsl
  297. // fancy_color.gdshaderinc
  298. // While technically allowed, there is usually no `shader_type` declaration in include files.
  299. vec3 get_fancy_color() {
  300. return vec3(0.3, 0.6, 0.9);
  301. }
  302. Example base shader (using the include file we created above):
  303. .. code-block:: glsl
  304. // material.gdshader
  305. shader_type spatial;
  306. #include "res://fancy_color.gdshaderinc"
  307. void fragment() {
  308. // No error, as we've included a definition for `get_fancy_color()` via the shader include.
  309. COLOR = get_fancy_color();
  310. }
  311. #pragma
  312. ^^^^^^^
  313. **Syntax:** ``#pragma value``
  314. The ``#pragma`` directive provides additional information to the preprocessor or compiler.
  315. Currently, it may have only one value: ``disable_preprocessor``. If you don't need
  316. the preprocessor, use that directive to speed up shader compilation by excluding
  317. the preprocessor step.
  318. .. code-block:: glsl
  319. #pragma disable_preprocessor
  320. #if USE_LIGHT
  321. // This causes a shader compilation error, as the `#if USE_LIGHT` and `#endif`
  322. // are included as-is in the final shader code.
  323. #endif
  324. Built-in defines
  325. ----------------
  326. Current renderer
  327. ^^^^^^^^^^^^^^^^
  328. Since Godot 4.4, you can check which renderer is currently used with the built-in
  329. defines ``CURRENT_RENDERER``, ``RENDERER_COMPATIBILITY``, ``RENDERER_MOBILE``,
  330. and ``RENDERER_FORWARD_PLUS``:
  331. - ``CURRENT_RENDERER`` is set to either ``0``, ``1``, or ``2`` depending on the
  332. current renderer.
  333. - ``RENDERER_COMPATIBILITY`` is always ``0``.
  334. - ``RENDERER_MOBILE`` is always ``1``.
  335. - ``RENDERER_FORWARD_PLUS`` is always ``2``.
  336. As an example, this shader sets ``ALBEDO`` to a different color in each renderer:
  337. .. code-block:: glsl
  338. shader_type spatial;
  339. void fragment() {
  340. #if CURRENT_RENDERER == RENDERER_COMPATIBILITY
  341. ALBEDO = vec3(0.0, 0.0, 1.0);
  342. #elif CURRENT_RENDERER == RENDERER_MOBILE
  343. ALBEDO = vec3(1.0, 0.0, 0.0);
  344. #else // CURRENT_RENDERER == RENDERER_FORWARD_PLUS
  345. ALBEDO = vec3(0.0, 1.0, 0.0);
  346. #endif
  347. }