your_first_2d_shader.rst 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249
  1. .. _doc_your_first_canvasitem_shader:
  2. Your first 2D shader
  3. ====================
  4. Introduction
  5. ------------
  6. Shaders are special programs that execute on the GPU and are used for rendering
  7. graphics. All modern rendering is done with shaders. For a more detailed
  8. description of what shaders are please see :ref:`What are shaders
  9. <doc_introduction_to_shaders>`.
  10. This tutorial will focus on the practical aspects of writing shader programs by
  11. walking you through the process of writing a shader with both vertex and
  12. fragment functions. This tutorial targets absolute beginners to shaders.
  13. .. note:: If you have experience writing shaders and are just looking for an
  14. overview of how shaders work in Godot, see the :ref:`Shading Reference
  15. <toc-shading-reference>`.
  16. Setup
  17. -----
  18. :ref:`CanvasItem <doc_canvas_item_shader>` shaders are used to draw all 2D
  19. objects in Godot, while :ref:`Spatial <doc_spatial_shader>` shaders are
  20. used to draw all 3D objects.
  21. In order to use a shader it must be attached inside a :ref:`Material
  22. <class_material>` which must be attached to an object. Materials are a type of
  23. :ref:`Resource <doc_resources>`. To draw multiple objects with the same
  24. material, the material must be attached to each object.
  25. All objects derived from a :ref:`CanvasItem <class_canvasitem>` have a material
  26. property. This includes all :ref:`GUI elements <class_Control>`, :ref:`Sprites
  27. <class_sprite>`, :ref:`TileMaps <class_tilemap>`, :ref:`MeshInstance2Ds
  28. <class_meshinstance2d>` etc. They also have an option to inherit their parent's
  29. material. This can be useful if you have a large number of nodes that you want
  30. to use the same material.
  31. To begin, create a Sprite node. You can use any CanvasItem, but for this
  32. tutorial we will use a Sprite.
  33. In the Inspector, click beside "Texture" where it says "[empty]" and select
  34. "Load", then select "Icon.png". For new projects, this is the Godot icon. You
  35. should now see the icon in the viewport.
  36. Next, look down in the Inspector, under the CanvasItem section, click beside
  37. "Material" and select "New ShaderMaterial". This creates a new Material
  38. resource. Click on the sphere that appears. Godot currently doesn't know whether
  39. you are writing a CanvasItem Shader or a Spatial Shader and it previews the
  40. output of spatial shaders. So what you are seeing is the output of the default
  41. Spatial Shader.
  42. Click beside "Shader" and select "New Shader". Finally, click on the new shader
  43. resource and the shader editor will open. You are now ready to begin writing
  44. your first shader.
  45. Your first CanvasItem shader
  46. ----------------------------
  47. In Godot, all shaders start with a line specifying what type of shader they are.
  48. It uses the following format:
  49. .. code-block:: glsl
  50. shader_type canvas_item;
  51. Because we are writing a CanvasItem shader, we specify ``canvas_item`` in the
  52. first line. All our code will go beneath this declaration.
  53. This line tells the engine which built-in variables and functionality to supply
  54. you with.
  55. In Godot you can override three functions to control how the shader operates;
  56. ``vertex``, ``fragment``, and ``light``. This tutorial will walk you through
  57. writing a shader with both vertex and fragment functions. Light functions are
  58. significantly more complex than vertex and fragment functions and so will not be
  59. covered here.
  60. Your first fragment function
  61. ----------------------------
  62. The fragment function runs for every pixel in a Sprite and determines what color
  63. that pixel should be.
  64. They are restricted to the pixels covered by the Sprite, that means you cannot
  65. use one to, for example, create an outline around a Sprite.
  66. The most basic fragment function does nothing except assign a single color to
  67. every pixel.
  68. We do so by writing a ``vec4`` to the built-in variable ``COLOR``. ``vec4`` is
  69. shorthand for constructing a vector with 4 numbers. For more information about
  70. vectors see the :ref:`Vector math tutorial <doc_vector_math>` ``COLOR`` is both
  71. an input variable to the fragment function and the final output from it.
  72. .. code-block:: glsl
  73. void fragment(){
  74. COLOR = vec4(0.4, 0.6, 0.9, 1.0);
  75. }
  76. .. image:: img/blue-box.png
  77. Congratulations! You're done. You have successfully written your first shader in
  78. Godot.
  79. Now let's make things more complex.
  80. There are many inputs to the fragment function that you can use for calculating
  81. ``COLOR``. ``UV`` is one of them. UV coordinates are specified in your Sprite
  82. (without you knowing it!) and they tell the shader where to read from textures
  83. for each part of the mesh.
  84. In the fragment function you can only read from ``UV``, but you can use it in
  85. other functions or to assign values to ``COLOR`` directly.
  86. ``UV`` varies between 0-1 from left-right and from top-bottom.
  87. .. image:: img/iconuv.png
  88. .. code-block:: glsl
  89. void fragment() {
  90. COLOR = vec4(UV, 0.5, 1.0);
  91. }
  92. .. image:: img/UV.png
  93. Using ``TEXTURE`` built-in
  94. ^^^^^^^^^^^^^^^^^^^^^^^^^^
  95. When you want to adjust a color in a Sprite you cannot just adjust the color
  96. from the texture manually like in the code below.
  97. .. code-block:: glsl
  98. void fragment(){
  99. //this shader will result in an all white rectangle
  100. COLOR.b = 1.0;
  101. }
  102. The default fragment function reads from a texture and displays it. When you
  103. overwrite the default fragment function, you lose that functionality, so you
  104. have to implement it yourself. You read from textures using the ``texture``
  105. function. Certain nodes, like Sprites, have a dedicated texture variable that
  106. can be accessed in the shader using ``TEXTURE``. Use it together with ``UV`` and
  107. ``texture`` to draw the Sprite.
  108. .. code-block:: glsl
  109. void fragment(){
  110. COLOR = texture(TEXTURE, UV); //read from texture
  111. COLOR.b = 1.0; //set blue channel to 1.0
  112. }
  113. .. image:: img/blue-tex.png
  114. Uniform input
  115. ^^^^^^^^^^^^^
  116. Uniform input is used to pass data into a shader that will be the same across
  117. the entire shader.
  118. You can use uniforms by defining them at the top of your shader like so:
  119. .. code-block:: glsl
  120. uniform float size;
  121. For more information about usage see the :ref:`Shading Language doc
  122. <doc_shading_language>`.
  123. Add a uniform to change the amount of blue in our Sprite.
  124. .. code-block:: glsl
  125. uniform float blue = 1.0; // you can assign a default value to uniforms
  126. void fragment(){
  127. COLOR = texture(TEXTURE, UV); //read from texture
  128. COLOR.b = blue;
  129. }
  130. Now you can change the amount of blue in the Sprite from the editor. Look back
  131. at the Inspector under where you created your shader. You should see a section
  132. called "Shader Param". Unfold that section and you will see the uniform you just
  133. declared. If you change the value in the editor, it will overwrite the default
  134. value you provided in the shader.
  135. Interacting with shaders from code
  136. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  137. You can change uniforms from code using the function ``set_shader_param()``
  138. which is called on the node's material resource. With a Sprite node, the
  139. following code can be used to set the ``blue`` uniform.
  140. ::
  141. var blue_value = 1.0
  142. material.set_shader_param("blue", blue_value)
  143. Note that the name of the uniform is a string. The string must match exactly
  144. with how it is written in the shader, including spelling and case.
  145. Your first vertex function
  146. --------------------------
  147. Now that we have a fragment function, let's write a vertex function.
  148. Use the vertex function to calculate where on the screen each vertex should end
  149. up.
  150. The most important variable in the vertex function is ``VERTEX``. Initially, it
  151. specifies the vertex coordinates in your model, but you also write to it to
  152. determine where to actually draw those vertices. ``VERTEX`` is a ``vec2`` that
  153. is initially presented in local-space (i.e. not relative to the camera,
  154. viewport, or parent nodes).
  155. You can offset the vertices by directly adding to ``VERTEX``.
  156. .. code-block:: glsl
  157. void vertex() {
  158. VERTEX += vec2(10.0, 0.0);
  159. }
  160. Combined with the ``TIME`` built-in variable, this can be used for simple
  161. animation.
  162. .. code-block:: glsl
  163. void vertex() {
  164. // Animate Sprite moving in big circle around its location
  165. VERTEX += vec2(cos(TIME)*100.0, sin(TIME)*100.0);
  166. }
  167. Conclusion
  168. ----------
  169. At their core, shaders do what you have seen so far, they compute ``VERTEX`` and
  170. ``COLOR``. It is up to you to dream up more complex mathematical strategies for
  171. assigning values to those variables.
  172. For inspiration, take a look at some of the more advanced shader tutorials, and
  173. look at other sites like `Shadertoy
  174. <https://www.shadertoy.com/results?query=&sort=popular&from=10&num=4>`_ and `The
  175. Book of Shaders <https://thebookofshaders.com>`_.