shading_language.rst 58 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275
  1. .. _doc_shading_language:
  2. Shading language
  3. ================
  4. Introduction
  5. ------------
  6. Godot uses a shading language similar to GLSL ES 3.0. Most datatypes and
  7. functions are supported, and the few remaining ones will likely be added over
  8. time.
  9. If you are already familiar with GLSL, the :ref:`Godot Shader Migration
  10. Guide<doc_converting_glsl_to_godot_shaders>` is a resource that will help you
  11. transition from regular GLSL to Godot's shading language.
  12. .. _doc_shading_language_data_types:
  13. Data types
  14. ----------
  15. Most GLSL ES 3.0 datatypes are supported:
  16. +------------------------+---------------------------------------------------------------------------------+
  17. | Type | Description |
  18. +========================+=================================================================================+
  19. | **void** | Void datatype, useful only for functions that return nothing. |
  20. +------------------------+---------------------------------------------------------------------------------+
  21. | **bool** | Boolean datatype, can only contain ``true`` or ``false``. |
  22. +------------------------+---------------------------------------------------------------------------------+
  23. | **bvec2** | Two-component vector of booleans. |
  24. +------------------------+---------------------------------------------------------------------------------+
  25. | **bvec3** | Three-component vector of booleans. |
  26. +------------------------+---------------------------------------------------------------------------------+
  27. | **bvec4** | Four-component vector of booleans. |
  28. +------------------------+---------------------------------------------------------------------------------+
  29. | **int** | 32 bit signed scalar integer. |
  30. +------------------------+---------------------------------------------------------------------------------+
  31. | **ivec2** | Two-component vector of signed integers. |
  32. +------------------------+---------------------------------------------------------------------------------+
  33. | **ivec3** | Three-component vector of signed integers. |
  34. +------------------------+---------------------------------------------------------------------------------+
  35. | **ivec4** | Four-component vector of signed integers. |
  36. +------------------------+---------------------------------------------------------------------------------+
  37. | **uint** | Unsigned scalar integer; can't contain negative numbers. |
  38. +------------------------+---------------------------------------------------------------------------------+
  39. | **uvec2** | Two-component vector of unsigned integers. |
  40. +------------------------+---------------------------------------------------------------------------------+
  41. | **uvec3** | Three-component vector of unsigned integers. |
  42. +------------------------+---------------------------------------------------------------------------------+
  43. | **uvec4** | Four-component vector of unsigned integers. |
  44. +------------------------+---------------------------------------------------------------------------------+
  45. | **float** | 32 bit floating-point scalar. |
  46. +------------------------+---------------------------------------------------------------------------------+
  47. | **vec2** | Two-component vector of floating-point values. |
  48. +------------------------+---------------------------------------------------------------------------------+
  49. | **vec3** | Three-component vector of floating-point values. |
  50. +------------------------+---------------------------------------------------------------------------------+
  51. | **vec4** | Four-component vector of floating-point values. |
  52. +------------------------+---------------------------------------------------------------------------------+
  53. | **mat2** | 2x2 matrix, in column major order. |
  54. +------------------------+---------------------------------------------------------------------------------+
  55. | **mat3** | 3x3 matrix, in column major order. |
  56. +------------------------+---------------------------------------------------------------------------------+
  57. | **mat4** | 4x4 matrix, in column major order. |
  58. +------------------------+---------------------------------------------------------------------------------+
  59. | **sampler2D** | Sampler type for binding 2D textures, which are read as float. |
  60. +------------------------+---------------------------------------------------------------------------------+
  61. | **isampler2D** | Sampler type for binding 2D textures, which are read as signed integer. |
  62. +------------------------+---------------------------------------------------------------------------------+
  63. | **usampler2D** | Sampler type for binding 2D textures, which are read as unsigned integer. |
  64. +------------------------+---------------------------------------------------------------------------------+
  65. | **sampler2DArray** | Sampler type for binding 2D texture arrays, which are read as float. |
  66. +------------------------+---------------------------------------------------------------------------------+
  67. | **isampler2DArray** | Sampler type for binding 2D texture arrays, which are read as signed integer. |
  68. +------------------------+---------------------------------------------------------------------------------+
  69. | **usampler2DArray** | Sampler type for binding 2D texture arrays, which are read as unsigned integer. |
  70. +------------------------+---------------------------------------------------------------------------------+
  71. | **sampler3D** | Sampler type for binding 3D textures, which are read as float. |
  72. +------------------------+---------------------------------------------------------------------------------+
  73. | **isampler3D** | Sampler type for binding 3D textures, which are read as signed integer. |
  74. +------------------------+---------------------------------------------------------------------------------+
  75. | **usampler3D** | Sampler type for binding 3D textures, which are read as unsigned integer. |
  76. +------------------------+---------------------------------------------------------------------------------+
  77. | **samplerCube** | Sampler type for binding Cubemaps, which are read as float. |
  78. +------------------------+---------------------------------------------------------------------------------+
  79. | **samplerCubeArray** | Sampler type for binding Cubemap arrays, which are read as float. |
  80. | | Only supported in Forward+ and Mobile, not Compatibility. |
  81. +------------------------+---------------------------------------------------------------------------------+
  82. | **samplerExternalOES** | External sampler type. |
  83. | | Only supported in Compatibility/Android platform. |
  84. +------------------------+---------------------------------------------------------------------------------+
  85. .. warning::
  86. Local variables are not initialized to a default value such as ``0.0``. If
  87. you use a variable without assigning it first, it will contain whatever
  88. value was already present at that memory location, and unpredictable visual
  89. glitches will appear. However, uniforms and varyings are initialized to a
  90. default value.
  91. Comments
  92. ~~~~~~~~
  93. The shading language supports the same comment syntax as used in C# and C++,
  94. using ``//`` for single-line comments and ``/* */`` for multi-line comments:
  95. .. code-block:: glsl
  96. // Single-line comment.
  97. int a = 2; // Another single-line comment.
  98. /*
  99. Multi-line comment.
  100. The comment ends when the ending delimiter is found
  101. (here, it's on the line below).
  102. */
  103. int b = 3;
  104. Additionally, you can use documentation comments that are displayed in the
  105. inspector when hovering a shader parameter. Documentation comments are currently
  106. only supported when placed immediately above a ``uniform`` declaration. These
  107. documentation comments only support the **multiline** comment syntax and must use
  108. **two** leading asterisks (``/**``) instead of just one (``/*``):
  109. .. code-block:: glsl
  110. /**
  111. * This is a documentation comment.
  112. * These lines will appear in the inspector when hovering the shader parameter
  113. * named "Something".
  114. * You can use [b]BBCode[/b] [i]formatting[/i] in the comment.
  115. */
  116. uniform int something = 1;
  117. The asterisks on the follow-up lines are not required, but are recommended as
  118. per the :ref:`doc_shaders_style_guide`. These asterisks are automatically
  119. stripped by the inspector, so they won't appear in the tooltip.
  120. Casting
  121. ~~~~~~~
  122. Just like GLSL ES 3.0, implicit casting between scalars and vectors of the same
  123. size but different type is not allowed. Casting of types of different size is
  124. also not allowed. Conversion must be done explicitly via constructors.
  125. Example:
  126. .. code-block:: glsl
  127. float a = 2; // invalid
  128. float a = 2.0; // valid
  129. float a = float(2); // valid
  130. Default integer constants are signed, so casting is always needed to convert to
  131. unsigned:
  132. .. code-block:: glsl
  133. int a = 2; // valid
  134. uint a = 2; // invalid
  135. uint a = uint(2); // valid
  136. Members
  137. ~~~~~~~
  138. Individual scalar members of vector types are accessed via the "x", "y", "z" and
  139. "w" members. Alternatively, using "r", "g", "b" and "a" also works and is
  140. equivalent. Use whatever fits best for your needs.
  141. For matrices, use the ``m[column][row]`` indexing syntax to access each scalar,
  142. or ``m[column]`` to access a vector by column index. For example, for accessing the
  143. y-component of the translation from a mat4 transform matrix (4th column, 2nd line) you use ``m[3][1]`` or ``m[3].y``.
  144. Constructing
  145. ~~~~~~~~~~~~
  146. Construction of vector types must always pass:
  147. .. code-block:: glsl
  148. // The required amount of scalars
  149. vec4 a = vec4(0.0, 1.0, 2.0, 3.0);
  150. // Complementary vectors and/or scalars
  151. vec4 a = vec4(vec2(0.0, 1.0), vec2(2.0, 3.0));
  152. vec4 a = vec4(vec3(0.0, 1.0, 2.0), 3.0);
  153. // A single scalar for the whole vector
  154. vec4 a = vec4(0.0);
  155. Construction of matrix types requires vectors of the same dimension as the
  156. matrix, interpreted as columns. You can also build a diagonal matrix using ``matx(float)`` syntax.
  157. Accordingly, ``mat4(1.0)`` is an identity matrix.
  158. .. code-block:: glsl
  159. mat2 m2 = mat2(vec2(1.0, 0.0), vec2(0.0, 1.0));
  160. mat3 m3 = mat3(vec3(1.0, 0.0, 0.0), vec3(0.0, 1.0, 0.0), vec3(0.0, 0.0, 1.0));
  161. mat4 identity = mat4(1.0);
  162. Matrices can also be built from a matrix of another dimension. There are two
  163. rules:
  164. 1. If a larger matrix is constructed from a smaller matrix, the additional rows
  165. and columns are set to the values they would have in an identity matrix.
  166. 2. If a smaller matrix is constructed from a larger matrix, the top, left
  167. submatrix of the larger matrix is used.
  168. .. code-block:: glsl
  169. mat3 basis = mat3(MODEL_MATRIX);
  170. mat4 m4 = mat4(basis);
  171. mat2 m2 = mat2(m4);
  172. Swizzling
  173. ~~~~~~~~~
  174. It is possible to obtain any combination of components in any order, as long as
  175. the result is another vector type (or scalar). This is easier shown than
  176. explained:
  177. .. code-block:: glsl
  178. vec4 a = vec4(0.0, 1.0, 2.0, 3.0);
  179. vec3 b = a.rgb; // Creates a vec3 with vec4 components.
  180. vec3 b = a.ggg; // Also valid; creates a vec3 and fills it with a single vec4 component.
  181. vec3 b = a.bgr; // "b" will be vec3(2.0, 1.0, 0.0).
  182. vec3 b = a.xyz; // Also rgba, xyzw are equivalent.
  183. vec3 b = a.stp; // And stpq (for texture coordinates).
  184. float c = b.w; // Invalid, because "w" is not present in vec3 b.
  185. vec3 c = b.xrt; // Invalid, mixing different styles is forbidden.
  186. b.rrr = a.rgb; // Invalid, assignment with duplication.
  187. b.bgr = a.rgb; // Valid assignment. "b"'s "blue" component will be "a"'s "red" and vice versa.
  188. Precision
  189. ~~~~~~~~~
  190. It is possible to add precision modifiers to datatypes; use them for uniforms,
  191. variables, arguments and varyings:
  192. .. code-block:: glsl
  193. lowp vec4 a = vec4(0.0, 1.0, 2.0, 3.0); // low precision, usually 8 bits per component mapped to 0-1
  194. mediump vec4 a = vec4(0.0, 1.0, 2.0, 3.0); // medium precision, usually 16 bits or half float
  195. highp vec4 a = vec4(0.0, 1.0, 2.0, 3.0); // high precision, uses full float or integer range (32 bit default)
  196. Using lower precision for some operations can speed up the math involved (at the
  197. cost of less precision). This is rarely needed in the vertex processor function
  198. (where full precision is needed most of the time), but is often useful in the
  199. fragment processor.
  200. Some architectures (mainly mobile) can benefit significantly from this, but
  201. there are downsides such as the additional overhead of conversion between
  202. precisions. Refer to the documentation of the target architecture for further
  203. information. In many cases, mobile drivers cause inconsistent or unexpected
  204. behavior and it is best to avoid specifying precision unless necessary.
  205. Arrays
  206. ------
  207. Arrays are containers for multiple variables of a similar type.
  208. Local arrays
  209. ~~~~~~~~~~~~
  210. Local arrays are declared in functions. They can use all of the allowed
  211. datatypes, except samplers. The array declaration follows a C-style syntax:
  212. ``[const] + [precision] + typename + identifier + [array size]``.
  213. .. code-block:: glsl
  214. void fragment() {
  215. float arr[3];
  216. }
  217. They can be initialized at the beginning like:
  218. .. code-block:: glsl
  219. float float_arr[3] = float[3] (1.0, 0.5, 0.0); // first constructor
  220. int int_arr[3] = int[] (2, 1, 0); // second constructor
  221. vec2 vec2_arr[3] = { vec2(1.0, 1.0), vec2(0.5, 0.5), vec2(0.0, 0.0) }; // third constructor
  222. bool bool_arr[] = { true, true, false }; // fourth constructor - size is defined automatically from the element count
  223. You can declare multiple arrays (even with different sizes) in one expression:
  224. .. code-block:: glsl
  225. float a[3] = float[3] (1.0, 0.5, 0.0),
  226. b[2] = { 1.0, 0.5 },
  227. c[] = { 0.7 },
  228. d = 0.0,
  229. e[5];
  230. To access an array element, use the indexing syntax:
  231. .. code-block:: glsl
  232. float arr[3];
  233. arr[0] = 1.0; // setter
  234. COLOR.r = arr[0]; // getter
  235. Arrays also have a built-in function ``.length()`` (not to be confused with the
  236. built-in ``length()`` function). It doesn't accept any parameters and will
  237. return the array's size.
  238. .. code-block:: glsl
  239. float arr[] = { 0.0, 1.0, 0.5, -1.0 };
  240. for (int i = 0; i < arr.length(); i++) {
  241. // ...
  242. }
  243. .. note::
  244. If you use an index either below 0 or greater than array size - the shader will
  245. crash and break rendering. To prevent this, use ``length()``, ``if``, or
  246. ``clamp()`` functions to ensure the index is between 0 and the array's
  247. length. Always carefully test and check your code. If you pass a constant
  248. expression or a number, the editor will check its bounds to prevent
  249. this crash.
  250. Global arrays
  251. ~~~~~~~~~~~~~
  252. You can declare arrays in global space as either ``const`` or ``uniform``:
  253. .. code-block:: glsl
  254. shader_type spatial;
  255. const lowp vec3 v[1] = lowp vec3[1] ( vec3(0, 0, 1) );
  256. uniform lowp vec3 w[1];
  257. void fragment() {
  258. ALBEDO = v[0] + w[0];
  259. }
  260. .. note::
  261. Global arrays use the same syntax as local arrays, except with a ``const``
  262. or ``uniform`` added to their declaration. Note that uniform arrays can't
  263. have a default value.
  264. Constants
  265. ---------
  266. Use the ``const`` keyword before the variable declaration to make that variable
  267. immutable, which means that it cannot be modified. All basic types, except
  268. samplers can be declared as constants. Accessing and using a constant value is
  269. slightly faster than using a uniform. Constants must be initialized at their
  270. declaration.
  271. .. code-block:: glsl
  272. const vec2 a = vec2(0.0, 1.0);
  273. vec2 b;
  274. a = b; // invalid
  275. b = a; // valid
  276. Constants cannot be modified and additionally cannot have hints, but multiple of
  277. them (if they have the same type) can be declared in a single expression e.g
  278. .. code-block:: glsl
  279. const vec2 V1 = vec2(1, 1), V2 = vec2(2, 2);
  280. Similar to variables, arrays can also be declared with ``const``.
  281. .. code-block:: glsl
  282. const float arr[] = { 1.0, 0.5, 0.0 };
  283. arr[0] = 1.0; // invalid
  284. COLOR.r = arr[0]; // valid
  285. Constants can be declared both globally (outside of any function) or locally
  286. (inside a function). Global constants are useful when you want to have access to
  287. a value throughout your shader that does not need to be modified. Like uniforms,
  288. global constants are shared between all shader stages, but they are not
  289. accessible outside of the shader.
  290. .. code-block:: glsl
  291. shader_type spatial;
  292. const float GOLDEN_RATIO = 1.618033988749894;
  293. Constants of the ``float`` type must be initialized using ``.`` notation after the
  294. decimal part or by using the scientific notation. The optional ``f`` post-suffix is
  295. also supported.
  296. .. code-block:: glsl
  297. float a = 1.0;
  298. float b = 1.0f; // same, using suffix for clarity
  299. float c = 1e-1; // gives 0.1 by using the scientific notation
  300. Constants of the ``uint`` (unsigned int) type must have a ``u`` suffix to differentiate them from signed integers.
  301. Alternatively, this can be done by using the ``uint(x)`` built-in conversion function.
  302. .. code-block:: glsl
  303. uint a = 1u;
  304. uint b = uint(1);
  305. Structs
  306. -------
  307. Structs are compound types which can be used for better abstraction of shader
  308. code. You can declare them at the global scope like:
  309. .. code-block:: glsl
  310. struct PointLight {
  311. vec3 position;
  312. vec3 color;
  313. float intensity;
  314. };
  315. After declaration, you can instantiate and initialize them like:
  316. .. code-block:: glsl
  317. void fragment()
  318. {
  319. PointLight light;
  320. light.position = vec3(0.0);
  321. light.color = vec3(1.0, 0.0, 0.0);
  322. light.intensity = 0.5;
  323. }
  324. Or use struct constructor for same purpose:
  325. .. code-block:: glsl
  326. PointLight light = PointLight(vec3(0.0), vec3(1.0, 0.0, 0.0), 0.5);
  327. Structs may contain other struct or array, you can also instance them as global
  328. constant:
  329. .. code-block:: glsl
  330. shader_type spatial;
  331. ...
  332. struct Scene {
  333. PointLight lights[2];
  334. };
  335. const Scene scene = Scene(PointLight[2](PointLight(vec3(0.0, 0.0, 0.0), vec3(1.0, 0.0, 0.0), 1.0), PointLight(vec3(0.0, 0.0, 0.0), vec3(1.0, 0.0, 0.0), 1.0)));
  336. void fragment()
  337. {
  338. ALBEDO = scene.lights[0].color;
  339. }
  340. You can also pass them to functions:
  341. .. code-block:: glsl
  342. shader_type canvas_item;
  343. ...
  344. Scene construct_scene(PointLight light1, PointLight light2) {
  345. return Scene({light1, light2});
  346. }
  347. void fragment()
  348. {
  349. COLOR.rgb = construct_scene(PointLight(vec3(0.0, 0.0, 0.0), vec3(1.0, 0.0, 0.0), 1.0), PointLight(vec3(0.0, 0.0, 0.0), vec3(1.0, 0.0, 1.0), 1.0)).lights[0].color;
  350. }
  351. Operators
  352. ---------
  353. Godot shading language supports the same set of operators as GLSL ES 3.0. Below
  354. is the list of them in precedence order:
  355. .. table::
  356. :class: nowrap-col3
  357. +-------------+------------------------+------------------+
  358. | Precedence | Class | Operator |
  359. +-------------+------------------------+------------------+
  360. | 1 (highest) | parenthetical grouping | **()** |
  361. +-------------+------------------------+------------------+
  362. | 2 | unary | **+, -, !, ~** |
  363. +-------------+------------------------+------------------+
  364. | 3 | multiplicative | **/, \*, %** |
  365. +-------------+------------------------+------------------+
  366. | 4 | additive | **+, -** |
  367. +-------------+------------------------+------------------+
  368. | 5 | bit-wise shift | **<<, >>** |
  369. +-------------+------------------------+------------------+
  370. | 6 | relational | **<, >, <=, >=** |
  371. +-------------+------------------------+------------------+
  372. | 7 | equality | **==, !=** |
  373. +-------------+------------------------+------------------+
  374. | 8 | bit-wise AND | **&** |
  375. +-------------+------------------------+------------------+
  376. | 9 | bit-wise exclusive OR | **^** |
  377. +-------------+------------------------+------------------+
  378. | 10 | bit-wise inclusive OR | **|** |
  379. +-------------+------------------------+------------------+
  380. | 11 | logical AND | **&&** |
  381. +-------------+------------------------+------------------+
  382. | 12 (lowest) | logical inclusive OR | **||** |
  383. +-------------+------------------------+------------------+
  384. .. note::
  385. Most operators that accept vectors or matrices (multiplication, division, etc) operate component-wise, meaning the function
  386. is applied to the first value of each vector and then on the second value of each vector, etc. Some examples:
  387. .. table::
  388. :class: nowrap-col2 nowrap-col1
  389. :widths: auto
  390. +---------------------------------------+------------------------------------------------------+
  391. | Operation | Equivalent Scalar Operation |
  392. +=======================================+======================================================+
  393. | ``vec3(4, 5, 6) + 2`` | ``vec3(4 + 2, 5 + 2, 6 + 2)`` |
  394. +---------------------------------------+------------------------------------------------------+
  395. | ``vec2(3, 4) * vec2(10, 20)`` | ``vec2(3 * 10, 4 * 20)`` |
  396. +---------------------------------------+------------------------------------------------------+
  397. | ``mat2(vec2(1, 2), vec2(3, 4)) + 10`` | ``mat2(vec2(1 + 10, 2 + 10), vec2(3 + 10, 4 + 10))`` |
  398. +---------------------------------------+------------------------------------------------------+
  399. The `GLSL Language Specification <http://www.opengl.org/registry/doc/GLSLangSpec.4.30.6.pdf>`_ says under section 5.10 Vector and Matrix Operations:
  400. With a few exceptions, operations are component-wise. Usually, when an operator operates on a
  401. vector or matrix, it is operating independently on each component of the vector or matrix,
  402. in a component-wise fashion. [...] The exceptions are matrix multiplied by vector,
  403. vector multiplied by matrix, and matrix multiplied by matrix. These do not operate component-wise,
  404. but rather perform the correct linear algebraic multiply.
  405. Flow control
  406. ------------
  407. Godot Shading language supports the most common types of flow control:
  408. .. code-block:: glsl
  409. // `if`, `else if` and `else`.
  410. if (cond) {
  411. } else if (other_cond) {
  412. } else {
  413. }
  414. // Ternary operator.
  415. // This is an expression that behaves like `if`/`else` and returns the value.
  416. // If `cond` evaluates to `true`, `result` will be `9`.
  417. // Otherwise, `result` will be `5`.
  418. int result = cond ? 9 : 5;
  419. // `switch`.
  420. switch (i) { // `i` should be a signed integer expression.
  421. case -1:
  422. break;
  423. case 0:
  424. return; // `break` or `return` to avoid running the next `case`.
  425. case 1: // Fallthrough (no `break` or `return`): will run the next `case`.
  426. case 2:
  427. break;
  428. //...
  429. default: // Only run if no `case` above matches. Optional.
  430. break;
  431. }
  432. // `for` loop. Best used when the number of elements to iterate on
  433. // is known in advance.
  434. for (int i = 0; i < 10; i++) {
  435. }
  436. // `while` loop. Best used when the number of elements to iterate on
  437. // is not known in advance.
  438. while (cond) {
  439. }
  440. // `do while`. Like `while`, but always runs at least once even if `cond`
  441. // never evaluates to `true`.
  442. do {
  443. } while (cond);
  444. Keep in mind that in modern GPUs, an infinite loop can exist and can freeze
  445. your application (including editor). Godot can't protect you from this, so be
  446. careful not to make this mistake!
  447. Also, when comparing floating-point values against a number, make sure to
  448. compare them against a *range* instead of an exact number.
  449. A comparison like ``if (value == 0.3)`` may not evaluate to ``true``.
  450. Floating-point math is often approximate and can defy expectations. It can also
  451. behave differently depending on the hardware.
  452. **Don't** do this.
  453. .. code-block:: glsl
  454. float value = 0.1 + 0.2;
  455. // May not evaluate to `true`!
  456. if (value == 0.3) {
  457. // ...
  458. }
  459. Instead, always perform a range comparison with an epsilon value. The larger the
  460. floating-point number (and the less precise the floating-point number), the
  461. larger the epsilon value should be.
  462. .. code-block:: glsl
  463. const float EPSILON = 0.0001;
  464. if (value >= 0.3 - EPSILON && value <= 0.3 + EPSILON) {
  465. // ...
  466. }
  467. See `floating-point-gui.de <https://floating-point-gui.de/>`__ for more
  468. information.
  469. Discarding
  470. ----------
  471. Fragment, light, and custom functions (called from fragment or light) can use the
  472. ``discard`` keyword. If used, the fragment is discarded and nothing is written.
  473. Beware that ``discard`` has a performance cost when used, as it will prevent the
  474. depth prepass from being effective on any surfaces using the shader. Also, a
  475. discarded pixel still needs to be rendered in the vertex shader, which means a
  476. shader that uses ``discard`` on all of its pixels is still more expensive to
  477. render compared to not rendering any object in the first place.
  478. Functions
  479. ---------
  480. It is possible to define functions in a Godot shader. They use the following
  481. syntax:
  482. .. code-block:: glsl
  483. ret_type func_name(args) {
  484. return ret_type; // if returning a value
  485. }
  486. // a more specific example:
  487. int sum2(int a, int b) {
  488. return a + b;
  489. }
  490. You can only use functions that have been defined above (higher in the editor)
  491. the function from which you are calling them. Redefining a function that has
  492. already been defined above (or is a built-in function name) will cause an error.
  493. Function arguments can have special qualifiers:
  494. * **in**: Means the argument is only for reading (default).
  495. * **out**: Means the argument is only for writing.
  496. * **inout**: Means the argument is fully passed via reference.
  497. * **const**: Means the argument is a constant and cannot be changed, may be
  498. combined with **in** qualifier.
  499. Example below:
  500. .. code-block:: glsl
  501. void sum2(int a, int b, inout int result) {
  502. result = a + b;
  503. }
  504. Function overloading is supported. You can define multiple functions with the same
  505. name, but different arguments. Note that `implicit casting <Casting_>`_ in overloaded
  506. function calls is not allowed, such as from ``int`` to ``float`` (``1`` to ``1.0``).
  507. .. code-block:: glsl
  508. vec3 get_color(int t) {
  509. return vec3(1, 0, 0); // Red color.
  510. }
  511. vec3 get_color(float t) {
  512. return vec3(0, 1, 0); // Green color.
  513. }
  514. void fragment() {
  515. vec3 red = get_color(1);
  516. vec3 green = get_color(1.0);
  517. }
  518. .. _doc_shading_language_varyings:
  519. Varyings
  520. --------
  521. To send data from the vertex to the fragment (or light) processor function, *varyings* are
  522. used. They are set for every primitive vertex in the *vertex processor*, and the
  523. value is interpolated for every pixel in the *fragment processor*.
  524. .. code-block:: glsl
  525. shader_type spatial;
  526. varying vec3 some_color;
  527. void vertex() {
  528. some_color = NORMAL; // Make the normal the color.
  529. }
  530. void fragment() {
  531. ALBEDO = some_color;
  532. }
  533. void light() {
  534. DIFFUSE_LIGHT = some_color * 100; // optionally
  535. }
  536. Varying can also be an array:
  537. .. code-block:: glsl
  538. shader_type spatial;
  539. varying float var_arr[3];
  540. void vertex() {
  541. var_arr[0] = 1.0;
  542. var_arr[1] = 0.0;
  543. }
  544. void fragment() {
  545. ALBEDO = vec3(var_arr[0], var_arr[1], var_arr[2]); // red color
  546. }
  547. It's also possible to send data from *fragment* to *light* processors using *varying* keyword. To do so you can assign it in the *fragment* and later use it in the *light* function.
  548. .. code-block:: glsl
  549. shader_type spatial;
  550. varying vec3 some_light;
  551. void fragment() {
  552. some_light = ALBEDO * 100.0; // Make a shining light.
  553. }
  554. void light() {
  555. DIFFUSE_LIGHT = some_light;
  556. }
  557. Note that varying may not be assigned in custom functions or a *light processor* function like:
  558. .. code-block:: glsl
  559. shader_type spatial;
  560. varying float test;
  561. void foo() {
  562. test = 0.0; // Error.
  563. }
  564. void vertex() {
  565. test = 0.0;
  566. }
  567. void light() {
  568. test = 0.0; // Error too.
  569. }
  570. This limitation was introduced to prevent incorrect usage before initialization.
  571. Interpolation qualifiers
  572. ------------------------
  573. Certain values are interpolated during the shading pipeline. You can modify how
  574. these interpolations are done by using *interpolation qualifiers*.
  575. .. code-block:: glsl
  576. shader_type spatial;
  577. varying flat vec3 our_color;
  578. void vertex() {
  579. our_color = COLOR.rgb;
  580. }
  581. void fragment() {
  582. ALBEDO = our_color;
  583. }
  584. There are two possible interpolation qualifiers:
  585. +-------------------+---------------------------------------------------------------------------------+
  586. | Qualifier | Description |
  587. +===================+=================================================================================+
  588. | **flat** | The value is not interpolated. |
  589. +-------------------+---------------------------------------------------------------------------------+
  590. | **smooth** | The value is interpolated in a perspective-correct fashion. This is the default.|
  591. +-------------------+---------------------------------------------------------------------------------+
  592. .. _doc_shading_language_uniforms:
  593. Uniforms
  594. --------
  595. Passing values to shaders is possible with *uniforms*, which are defined in the
  596. global scope of the shader, outside of functions. When a shader is later
  597. assigned to a material, the uniforms will appear as editable parameters in the
  598. material's inspector. Uniforms can't be written from within the shader. Any
  599. :ref:`data type <doc_shading_language_data_types>` except for ``void`` can be a uniform.
  600. .. code-block:: glsl
  601. shader_type spatial;
  602. uniform float some_value;
  603. uniform vec3 colors[3];
  604. You can set uniforms in the editor in the material's inspector. Alternately, you
  605. can set them :ref:`from code <doc_shading_language_setting_uniforms_from_code>`.
  606. Uniform hints
  607. ~~~~~~~~~~~~~
  608. Godot provides optional uniform hints to make the compiler understand what the
  609. uniform is used for, and how the editor should allow users to modify it.
  610. .. code-block:: glsl
  611. shader_type spatial;
  612. uniform vec4 color : source_color;
  613. uniform float amount : hint_range(0, 1);
  614. uniform vec4 other_color : source_color = vec4(1.0); // Default values go after the hint.
  615. uniform sampler2D image : source_color;
  616. Uniforms can also be assigned default values:
  617. .. code-block:: glsl
  618. shader_type spatial;
  619. uniform vec4 some_vector = vec4(0.0);
  620. uniform vec4 some_color : source_color = vec4(1.0);
  621. Note that when adding a default value and a hint, the default value goes after the hint.
  622. Full list of uniform hints below:
  623. +----------------------+--------------------------------------------------+-----------------------------------------------------------------------------+
  624. | Type | Hint | Description |
  625. +======================+==================================================+=============================================================================+
  626. | **vec3, vec4** | source_color | Used as color. |
  627. +----------------------+--------------------------------------------------+-----------------------------------------------------------------------------+
  628. | **int** | hint_enum("String1", "String2") | Displays int input as a dropdown widget in the editor. |
  629. +----------------------+--------------------------------------------------+-----------------------------------------------------------------------------+
  630. | **int, float** | hint_range(min, max[, step]) | Restricted to values in a range (with min/max/step). |
  631. +----------------------+--------------------------------------------------+-----------------------------------------------------------------------------+
  632. | **sampler2D** | source_color | Used as albedo color. |
  633. +----------------------+--------------------------------------------------+-----------------------------------------------------------------------------+
  634. | **sampler2D** | hint_normal | Used as normalmap. |
  635. +----------------------+--------------------------------------------------+-----------------------------------------------------------------------------+
  636. | **sampler2D** | hint_default_white | As value or albedo color, default to opaque white. |
  637. +----------------------+--------------------------------------------------+-----------------------------------------------------------------------------+
  638. | **sampler2D** | hint_default_black | As value or albedo color, default to opaque black. |
  639. +----------------------+--------------------------------------------------+-----------------------------------------------------------------------------+
  640. | **sampler2D** | hint_default_transparent | As value or albedo color, default to transparent black. |
  641. +----------------------+--------------------------------------------------+-----------------------------------------------------------------------------+
  642. | **sampler2D** | hint_anisotropy | As flowmap, default to right. |
  643. +----------------------+--------------------------------------------------+-----------------------------------------------------------------------------+
  644. | **sampler2D** | hint_roughness[_r, _g, _b, _a, _normal, _gray] | Used for roughness limiter on import (attempts reducing specular aliasing). |
  645. | | | ``_normal`` is a normal map that guides the roughness limiter, |
  646. | | | with roughness increasing in areas that have high-frequency detail. |
  647. +----------------------+--------------------------------------------------+-----------------------------------------------------------------------------+
  648. | **sampler2D** | filter[_nearest, _linear][_mipmap][_anisotropic] | Enabled specified texture filtering. |
  649. +----------------------+--------------------------------------------------+-----------------------------------------------------------------------------+
  650. | **sampler2D** | repeat[_enable, _disable] | Enabled texture repeating. |
  651. +----------------------+--------------------------------------------------+-----------------------------------------------------------------------------+
  652. | **sampler2D** | hint_screen_texture | Texture is the screen texture. |
  653. +----------------------+--------------------------------------------------+-----------------------------------------------------------------------------+
  654. | **sampler2D** | hint_depth_texture | Texture is the depth texture. |
  655. +----------------------+--------------------------------------------------+-----------------------------------------------------------------------------+
  656. | **sampler2D** | hint_normal_roughness_texture | Texture is the normal roughness texture (only supported in Forward+). |
  657. +----------------------+--------------------------------------------------+-----------------------------------------------------------------------------+
  658. Using ``hint_enum``
  659. ^^^^^^^^^^^^^^^^^^^
  660. You can access ``int`` values as a readable dropdown widget using the ``hint_enum`` uniform:
  661. .. code-block::
  662. uniform int noise_type : hint_enum("OpenSimplex2", "Cellular", "Perlin", "Value") = 0;
  663. You can assign explicit values to the ``hint_enum`` uniform using colon syntax similar to GDScript:
  664. .. code-block::
  665. uniform int character_speed: hint_enum("Slow:30", "Average:60", "Very Fast:200") = 60;
  666. The value will be stored as an integer, corresponding to the index of the selected
  667. option (i.e. ``0``, ``1``, or ``2``) or the value assigned by colon syntax
  668. (i.e. ``30``, ``60``, or ``200``). When setting the value with
  669. ``set_shader_parameter()``, you must use the integer value, not the ``String``
  670. name.
  671. Using ``source_color``
  672. ^^^^^^^^^^^^^^^^^^^^^^
  673. Any texture which contains *sRGB color data* requires a ``source_color`` hint
  674. in order to be correctly sampled. This is because Godot renders in linear
  675. color space, but some textures contain sRGB color data. If this hint is not
  676. used, the texture will appear washed out.
  677. Albedo and color textures should typically have a ``source_color`` hint. Normal,
  678. roughness, metallic, and height textures typically do not need a ``source_color``
  679. hint.
  680. Using ``source_color`` hint is required in the Forward+ and Mobile renderers,
  681. and in ``canvas_item`` shaders when :ref:`HDR 2D<class_ProjectSettings_property_rendering/viewport/hdr_2d>`
  682. is enabled. The ``source_color`` hint is optional for the Compatibility renderer,
  683. and for ``canvas_item`` shaders if ``HDR 2D`` is disabled. However, it is
  684. recommended to always use the ``source_color`` hint, because it works even
  685. if you change renderers or disable ``HDR 2D``.
  686. Uniform groups
  687. ~~~~~~~~~~~~~~
  688. To group multiple uniforms in a section in the inspector, you can use a
  689. ``group_uniform`` keyword like this:
  690. .. code-block:: glsl
  691. group_uniforms MyGroup;
  692. uniform sampler2D test;
  693. You can close the group by using:
  694. .. code-block:: glsl
  695. group_uniforms;
  696. The syntax also supports subgroups (it's not mandatory to declare the base group before this):
  697. .. code-block:: glsl
  698. group_uniforms MyGroup.MySubgroup;
  699. .. _doc_shading_language_global_uniforms:
  700. Global uniforms
  701. ~~~~~~~~~~~~~~~
  702. Sometimes, you want to modify a parameter in many different shaders at once.
  703. With a regular uniform, this takes a lot of work as all these shaders need to be
  704. tracked and the uniform needs to be set for each of them. Global uniforms allow
  705. you to create and update uniforms that will be available in all shaders, in
  706. every shader type (``canvas_item``, ``spatial``, ``particles``, ``sky`` and
  707. ``fog``).
  708. Global uniforms are especially useful for environmental effects that affect many
  709. objects in a scene, like having foliage bend when the player is nearby, or having
  710. objects move with the wind.
  711. .. note:: *Global uniforms* are not the same as *global scope* for an individual
  712. shader. While regular uniforms are defined outside of shader functions and are
  713. therefore the global scope of the shader, global uniforms are global to all
  714. shaders in the entire project (but within each shader, are also in the global
  715. scope).
  716. To create a global uniform, open the **Project Settings** then go to the
  717. **Shader Globals** tab. Specify a name for the uniform (case-sensitive) and a
  718. type, then click **Add** in the top-right corner of the dialog. You can then
  719. edit the value assigned to the uniform by clicking the value in the list of
  720. uniforms:
  721. .. figure:: img/shading_language_adding_global_uniforms.webp
  722. :align: center
  723. :alt: Adding a global uniform in the Shader Globals tab of the Project Settings
  724. Adding a global uniform in the Shader Globals tab of the Project Settings
  725. After creating a global uniform, you can use it in a shader as follows:
  726. .. code-block:: glsl
  727. shader_type canvas_item;
  728. global uniform vec4 my_color;
  729. void fragment() {
  730. COLOR = my_color.rgb;
  731. }
  732. Note that the global uniform *must* exist in the Project Settings at the time
  733. the shader is saved, or compilation will fail. While you can assign a default
  734. value using ``global uniform vec4 my_color = ...`` in the shader code, it will
  735. be ignored as the global uniform must always be defined in the Project Settings
  736. anyway.
  737. To change the value of a global uniform at runtime, use the
  738. :ref:`RenderingServer.global_shader_parameter_set <class_RenderingServer_method_global_shader_parameter_set>`
  739. method in a script:
  740. .. code-block:: gdscript
  741. RenderingServer.global_shader_parameter_set("my_color", Color(0.3, 0.6, 1.0))
  742. Assigning global uniform values can be done as many times as desired without
  743. impacting performance, as setting data doesn't require synchronization between
  744. the CPU and GPU.
  745. You can also add or remove global uniforms at runtime:
  746. .. code-block:: gdscript
  747. RenderingServer.global_shader_parameter_add("my_color", RenderingServer.GLOBAL_VAR_TYPE_COLOR, Color(0.3, 0.6, 1.0))
  748. RenderingServer.global_shader_parameter_remove("my_color")
  749. Adding or removing global uniforms at runtime has a performance cost, although
  750. it's not as pronounced compared to getting global uniform values from a script
  751. (see the warning below).
  752. .. warning::
  753. While you *can* query the value of a global uniform at runtime in a script
  754. using ``RenderingServer.global_shader_parameter_get("uniform_name")``, this
  755. has a large performance penalty as the rendering thread needs to synchronize
  756. with the calling thread.
  757. Therefore, it's not recommended to read global shader uniform values
  758. continuously in a script. If you need to read values in a script after
  759. setting them, consider creating an :ref:`autoload <doc_singletons_autoload>`
  760. where you store the values you need to query at the same time you're setting
  761. them as global uniforms.
  762. .. _doc_shading_language_per_instance_uniforms:
  763. Per-instance uniforms
  764. ~~~~~~~~~~~~~~~~~~~~~
  765. .. note::
  766. Per-instance uniforms are available in both ``canvas_item`` (2D) and ``spatial`` (3D) shaders.
  767. Sometimes, you want to modify a parameter on each node using the material. As an
  768. example, in a forest full of trees, when you want each tree to have a slightly
  769. different color that is editable by hand. Without per-instance uniforms, this
  770. requires creating a unique material for each tree (each with a slightly
  771. different hue). This makes material management more complex, and also has a
  772. performance overhead due to the scene requiring more unique material instances.
  773. Vertex colors could also be used here, but they'd require creating unique copies
  774. of the mesh for each different color, which also has a performance overhead.
  775. Per-instance uniforms are set on each GeometryInstance3D, rather than on each
  776. Material instance. Take this into account when working with meshes that have
  777. multiple materials assigned to them, or MultiMesh setups.
  778. .. code-block:: glsl
  779. shader_type spatial;
  780. // Provide a hint to edit as a color. Optionally, a default value can be provided.
  781. // If no default value is provided, the type's default is used (e.g. opaque black for colors).
  782. instance uniform vec4 my_color : source_color = vec4(1.0, 0.5, 0.0, 1.0);
  783. void fragment() {
  784. ALBEDO = my_color.rgb;
  785. }
  786. After saving the shader, you can change the per-instance uniform's value using
  787. the inspector:
  788. .. figure:: img/shading_language_per_instance_uniforms_inspector.webp
  789. :align: center
  790. :alt: Setting a per-instance uniform's value in the GeometryInstance3D section of the inspector
  791. Setting a per-instance uniform's value in the GeometryInstance3D section of the inspector
  792. Per-instance uniform values can also be set at runtime using
  793. :ref:`set_instance_shader_parameter <class_GeometryInstance3D_method_set_instance_shader_parameter>`
  794. method on a node that inherits from :ref:`class_GeometryInstance3D`:
  795. .. code-block:: gdscript
  796. $MeshInstance3D.set_instance_shader_parameter("my_color", Color(0.3, 0.6, 1.0))
  797. When using per-instance uniforms, there are some restrictions you should be aware of:
  798. - **Per-instance uniforms do not support textures**, only regular scalar and
  799. vector types. As a workaround, you can pass a texture array as a regular
  800. uniform, then pass the index of the texture to be drawn using a per-instance
  801. uniform.
  802. - There is a practical maximum limit of 16 instance uniforms per shader.
  803. - If your mesh uses multiple materials, the parameters for the first mesh
  804. material found will "win" over the subsequent ones, unless they have the same
  805. name, index *and* type. In this case, all parameters are affected correctly.
  806. - If you run into the above situation, you can avoid clashes by manually
  807. specifying the index (0-15) of the instance uniform by using the
  808. ``instance_index`` hint:
  809. .. code-block:: glsl
  810. instance uniform vec4 my_color : source_color, instance_index(5);
  811. .. _doc_shading_language_setting_uniforms_from_code:
  812. Setting uniforms from code
  813. ~~~~~~~~~~~~~~~~~~~~~~~~~~
  814. You can set uniforms from GDScript using the
  815. :ref:`set_shader_parameter() <class_ShaderMaterial_method_set_shader_parameter>`
  816. method:
  817. .. code-block:: gdscript
  818. material.set_shader_parameter("some_value", some_value)
  819. material.set_shader_parameter("colors", [Vector3(1, 0, 0), Vector3(0, 1, 0), Vector3(0, 0, 1)])
  820. .. note:: The first argument to ``set_shader_parameter()`` is the name of the uniform
  821. in the shader. It must match *exactly* to the name of the uniform in
  822. the shader or else it will not be recognized.
  823. GDScript uses different variable types than GLSL does, so when passing variables
  824. from GDScript to shaders, Godot converts the type automatically. Below is a
  825. table of the corresponding types:
  826. +------------------------+-------------------------+------------------------------------------------------------+
  827. | GLSL type | GDScript type | Notes |
  828. +========================+=========================+============================================================+
  829. | **bool** | **bool** | |
  830. +------------------------+-------------------------+------------------------------------------------------------+
  831. | **bvec2** | **int** | Bitwise packed int where bit 0 (LSB) corresponds to x. |
  832. | | | |
  833. | | | For example, a bvec2 of (bx, by) could be created in |
  834. | | | the following way: |
  835. | | | |
  836. | | | .. code-block:: gdscript |
  837. | | | |
  838. | | | bvec2_input: int = (int(bx)) | (int(by) << 1) |
  839. | | | |
  840. +------------------------+-------------------------+------------------------------------------------------------+
  841. | **bvec3** | **int** | Bitwise packed int where bit 0 (LSB) corresponds to x. |
  842. +------------------------+-------------------------+------------------------------------------------------------+
  843. | **bvec4** | **int** | Bitwise packed int where bit 0 (LSB) corresponds to x. |
  844. +------------------------+-------------------------+------------------------------------------------------------+
  845. | **int** | **int** | |
  846. +------------------------+-------------------------+------------------------------------------------------------+
  847. | **ivec2** | **Vector2i** | |
  848. +------------------------+-------------------------+------------------------------------------------------------+
  849. | **ivec3** | **Vector3i** | |
  850. +------------------------+-------------------------+------------------------------------------------------------+
  851. | **ivec4** | **Vector4i** | |
  852. +------------------------+-------------------------+------------------------------------------------------------+
  853. | **uint** | **int** | |
  854. +------------------------+-------------------------+------------------------------------------------------------+
  855. | **uvec2** | **Vector2i** | |
  856. +------------------------+-------------------------+------------------------------------------------------------+
  857. | **uvec3** | **Vector3i** | |
  858. +------------------------+-------------------------+------------------------------------------------------------+
  859. | **uvec4** | **Vector4i** | |
  860. +------------------------+-------------------------+------------------------------------------------------------+
  861. | **float** | **float** | |
  862. +------------------------+-------------------------+------------------------------------------------------------+
  863. | **vec2** | **Vector2** | |
  864. +------------------------+-------------------------+------------------------------------------------------------+
  865. | **vec3** | **Vector3**, **Color** | When Color is used, it will be interpreted as (r, g, b). |
  866. +------------------------+-------------------------+------------------------------------------------------------+
  867. | **vec4** | **Vector4**, **Color**, | When Color is used, it will be interpreted as (r, g, b, a).|
  868. | | **Rect2**, **Plane**, | |
  869. | | **Quaternion** | When Rect2 is used, it will be interpreted as |
  870. | | | (position.x, position.y, size.x, size.y). |
  871. | | | |
  872. | | | When Plane is used it will be interpreted as |
  873. | | | (normal.x, normal.y, normal.z, d). |
  874. | | | |
  875. | | | |
  876. +------------------------+-------------------------+------------------------------------------------------------+
  877. | **mat2** | **Transform2D** | |
  878. | | | |
  879. +------------------------+-------------------------+------------------------------------------------------------+
  880. | **mat3** | **Basis** | |
  881. +------------------------+-------------------------+------------------------------------------------------------+
  882. | **mat4** | **Projection**, | When a Transform3D is used, the w Vector is set to the |
  883. | | **Transform3D** | identity. |
  884. +------------------------+-------------------------+------------------------------------------------------------+
  885. | **sampler2D** | **Texture2D** | |
  886. +------------------------+-------------------------+------------------------------------------------------------+
  887. | **isampler2D** | **Texture2D** | |
  888. +------------------------+-------------------------+------------------------------------------------------------+
  889. | **usampler2D** | **Texture2D** | |
  890. +------------------------+-------------------------+------------------------------------------------------------+
  891. | **sampler2DArray** | **Texture2DArray** | |
  892. +------------------------+-------------------------+------------------------------------------------------------+
  893. | **isampler2DArray** | **Texture2DArray** | |
  894. +------------------------+-------------------------+------------------------------------------------------------+
  895. | **usampler2DArray** | **Texture2DArray** | |
  896. +------------------------+-------------------------+------------------------------------------------------------+
  897. | **sampler3D** | **Texture3D** | |
  898. +------------------------+-------------------------+------------------------------------------------------------+
  899. | **isampler3D** | **Texture3D** | |
  900. +------------------------+-------------------------+------------------------------------------------------------+
  901. | **usampler3D** | **Texture3D** | |
  902. +------------------------+-------------------------+------------------------------------------------------------+
  903. | **samplerCube** | **Cubemap** | See :ref:`doc_importing_images_changing_import_type` for |
  904. | | | instructions on importing cubemaps for use in Godot. |
  905. +------------------------+-------------------------+------------------------------------------------------------+
  906. | **samplerCubeArray** | **CubemapArray** | Only supported in Forward+ and Mobile, not Compatibility. |
  907. +------------------------+-------------------------+------------------------------------------------------------+
  908. | **samplerExternalOES** | **ExternalTexture** | Only supported in Compatibility/Android platform. |
  909. +------------------------+-------------------------+------------------------------------------------------------+
  910. .. note:: Be careful when setting shader uniforms from GDScript, since no error
  911. will be thrown if the type does not match. Your shader will just exhibit
  912. undefined behavior. Specifically, this includes setting a GDScript
  913. int/float (64 bit) into a Godot shader language int/float (32 bit).
  914. This may lead to unintended consequences in cases where high
  915. precision is required.
  916. Uniform limits
  917. ~~~~~~~~~~~~~~
  918. There is a limit to the total size of shader uniforms that you can use
  919. in a single shader. On most desktop platforms, this limit is ``65536``
  920. bytes, or 4096 ``vec4`` uniforms. On mobile platforms, the limit is
  921. typically ``16384`` bytes, or 1024 ``vec4`` uniforms. Vector uniforms
  922. smaller than a ``vec4``, such as ``vec2`` or ``vec3``, are padded to
  923. the size of a ``vec4``. Scalar uniforms such as ``int`` or ``float``
  924. are not padded, and ``bool`` is padded to the size of an ``int``.
  925. Arrays count as the total size of their contents. If you need a uniform
  926. array that is larger than this limit, consider packing the data into a
  927. texture instead, since the *contents* of a texture do not count towards
  928. this limit, only the size of the sampler uniform.
  929. Built-in variables
  930. ------------------
  931. A large number of built-in variables are available, like ``UV``, ``COLOR`` and
  932. ``VERTEX``. What variables are available depends on the type of shader
  933. (``spatial``, ``canvas_item``, ``particle``, etc) and the
  934. function used (``vertex``, ``fragment``, ``light``, ``start``, ``process``,
  935. ``sky``, or ``fog``). For a list of the built-in variables that are available,
  936. please see the corresponding pages:
  937. - :ref:`Spatial shaders <doc_spatial_shader>`
  938. - :ref:`Canvas item shaders <doc_canvas_item_shader>`
  939. - :ref:`Particle shaders <doc_particle_shader>`
  940. - :ref:`Sky shaders <doc_sky_shader>`
  941. - :ref:`Fog shaders <doc_fog_shader>`
  942. Built-in functions
  943. ------------------
  944. A large number of built-in functions are supported, conforming to GLSL ES 3.0.
  945. See the :ref:`Built-in functions <doc_shader_functions>` page for details.