your_first_3d_shader.rst 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394
  1. .. _doc_your_first_spatial_shader:
  2. Your first 3D shader
  3. ====================
  4. You have decided to start writing your own custom Spatial shader. Maybe you saw
  5. a cool trick online that was done with shaders, or you have found that the
  6. :ref:`StandardMaterial3D <class_StandardMaterial3D>` isn't quite meeting your
  7. needs. Either way, you have decided to write your own and now you need to figure
  8. out where to start.
  9. This tutorial will explain how to write a Spatial shader and will cover more
  10. topics than the :ref:`CanvasItem <doc_your_first_canvasitem_shader>` tutorial.
  11. Spatial shaders have more built-in functionality than CanvasItem shaders. The
  12. expectation with spatial shaders is that Godot has already provided the
  13. functionality for common use cases and all the user needs to do in the shader is
  14. set the proper parameters. This is especially true for a PBR (physically based
  15. rendering) workflow.
  16. This is a two-part tutorial. In this first part we will create terrain using
  17. vertex displacement from a heightmap in the
  18. vertex function. In the :ref:`second part <doc_your_second_spatial_shader>` we
  19. will take the concepts from this tutorial and set up
  20. custom materials in a fragment shader by writing an ocean water shader.
  21. .. note:: This tutorial assumes some basic shader knowledge such as types
  22. (``vec2``, ``float``, ``sampler2D``), and functions. If you are
  23. uncomfortable with these concepts it is best to get a gentle
  24. introduction from `The Book of Shaders
  25. <https://thebookofshaders.com>`_ before completing this tutorial.
  26. Where to assign my material
  27. ---------------------------
  28. In 3D, objects are drawn using :ref:`Meshes <class_Mesh>`. Meshes are a resource
  29. type that store geometry (the shape of your object) and materials (the color and
  30. how the object reacts to light) in units called "surfaces". A Mesh can have
  31. multiple surfaces, or just one. Typically, you would import a mesh from another
  32. program (e.g. Blender). But Godot also has a few :ref:`PrimitiveMeshes
  33. <class_primitivemesh>` that allow you to add basic geometry to a scene without
  34. importing Meshes.
  35. There are multiple node types that you can use to draw a mesh. The main one is
  36. :ref:`MeshInstance3D <class_MeshInstance3D>`, but you can also use :ref:`GPUParticles3D
  37. <class_GPUParticles3D>`, :ref:`MultiMeshes <class_MultiMesh>` (with a
  38. :ref:`MultiMeshInstance3D <class_MultiMeshInstance3D>`), or others.
  39. Typically, a material is associated with a given surface in a mesh, but some
  40. nodes, like MeshInstance3D, allow you to override the material for a specific
  41. surface, or for all surfaces.
  42. If you set a material on the surface or mesh itself, then all MeshInstance3Ds that
  43. share that mesh will share that material. However, if you want to reuse the same
  44. mesh across multiple mesh instances, but have different materials for each
  45. instance then you should set the material on the MeshInstance3D.
  46. For this tutorial we will set our material on the mesh itself rather than taking
  47. advantage of the MeshInstance3D's ability to override materials.
  48. Setting up
  49. ----------
  50. Add a new :ref:`MeshInstance3D <class_MeshInstance3D>` node to your scene.
  51. In the inspector tab, set the MeshInstance3D's **Mesh** property to a new
  52. :ref:`PlaneMesh <class_planemesh>` resource, by clicking on ``<empty>`` and
  53. choosing **New PlaneMesh**. Then expand the resource by clicking on the image of
  54. a plane that appears.
  55. This adds a plane to our scene.
  56. Then, in the viewport, click in the upper left corner on the **Perspective** button.
  57. In the menu that appears, select **Display Wireframe**.
  58. This will allow you to see the triangles making up the plane.
  59. .. image:: img/plane.webp
  60. Now set **Subdivide Width** and **Subdivide Depth** of the :ref:`PlaneMesh <class_planemesh>` to ``32``.
  61. .. image:: img/plane-sub-set.webp
  62. You can see that there are now many more triangles in the
  63. :ref:`MeshInstance3D<class_MeshInstance3D>`. This will give us more vertices to work with
  64. and thus allow us to add more detail.
  65. .. image:: img/plane-sub.webp
  66. :ref:`PrimitiveMeshes <class_primitivemesh>`, like PlaneMesh, only have one
  67. surface, so instead of an array of materials there is only one. Set the
  68. **Material** to a new ShaderMaterial, then expand the material by clicking on
  69. the sphere that appears.
  70. .. note::
  71. Materials that inherit from the :ref:`class_Material` resource, such as :ref:`class_StandardMaterial3D`
  72. and :ref:`class_ParticleProcessMaterial`, can be converted to a :ref:`class_ShaderMaterial`
  73. and their existing properties will be converted to an accompanying text shader.
  74. To do so, right-click on the material in the FileSystem dock and choose
  75. **Convert to ShaderMaterial**. You can also do so by right-clicking on any
  76. property holding a reference to the material in the inspector.
  77. Now set the material's **Shader** to a new Shader by clicking ``<empty>`` and
  78. select **New Shader...**. Leave the default settings, give your shader a name,
  79. and click **Create**.
  80. Click on the shader in the inspector, and the shader editor should now pop up. You
  81. are ready to begin writing your first Spatial shader!
  82. Shader magic
  83. ------------
  84. .. image:: img/shader-editor.webp
  85. The new shader is already generated with a ``shader_type`` variable, the
  86. ``vertex()`` function, and the ``fragment()`` function. The first thing Godot
  87. shaders need is a declaration of what type of shader they are. In this case the
  88. ``shader_type`` is set to ``spatial`` because this is a spatial shader.
  89. .. code-block:: glsl
  90. shader_type spatial;
  91. The ``vertex()`` function determines where the vertices of your :ref:`MeshInstance3D<class_MeshInstance3D>`
  92. appear in the final scene. We will be using it to offset the height of each vertex
  93. and make our flat plane appear like a little terrain.
  94. With nothing in the ``vertex()`` function, Godot will use its default vertex
  95. shader. We can start to make changes by adding a single line:
  96. .. code-block:: glsl
  97. void vertex() {
  98. VERTEX.y += cos(VERTEX.x) * sin(VERTEX.z);
  99. }
  100. Adding this line, you should get an image like the one below.
  101. .. image:: img/cos.webp
  102. Okay, let's unpack this. The ``y`` value of the ``VERTEX`` is being increased.
  103. And we are passing the ``x`` and ``z`` components of the ``VERTEX`` as arguments
  104. to :ref:`cos() <shader_func_cos>` and :ref:`sin() <shader_func_sin>`; that gives
  105. us a wave-like appearance across the ``x`` and ``z`` axes.
  106. What we want to achieve is the look of little hills; after all. ``cos()`` and
  107. ``sin()`` already look kind of like hills. We do so by scaling the inputs to the
  108. ``cos()`` and ``sin()`` functions.
  109. .. code-block:: glsl
  110. void vertex() {
  111. VERTEX.y += cos(VERTEX.x * 4.0) * sin(VERTEX.z * 4.0);
  112. }
  113. .. image:: img/cos4.webp
  114. This looks better, but it is still too spiky and repetitive, let's make it a
  115. little more interesting.
  116. Noise heightmap
  117. ---------------
  118. Noise is a very popular tool for faking the look of terrain. Think of it as
  119. similar to the cosine function where you have repeating hills except, with
  120. noise, each hill has a different height.
  121. Godot provides the :ref:`NoiseTexture2D <class_noisetexture2D>` resource for
  122. generating a noise texture that can be accessed from a shader.
  123. To access a texture in a shader add the following code near the top of your
  124. shader, outside the ``vertex()`` function.
  125. .. code-block:: glsl
  126. uniform sampler2D noise;
  127. This will allow you to send a noise texture to the shader. Now look in the
  128. inspector under your material. You should see a section called **Shader Parameters**.
  129. If you open it up, you'll see a parameter called "Noise".
  130. Set this **Noise** parameter to a new :ref:`NoiseTexture2D <class_noisetexture2D>`.
  131. Then in your NoiseTexture2D, set its **Noise** property to a new
  132. :ref:`FastNoiseLite <class_fastnoiselite>`. The FastNoiseLite class is used by
  133. the NoiseTexture2D to generate a heightmap.
  134. Once you set it up and should look like this.
  135. .. image:: img/noise-set.webp
  136. Now, access the noise texture using the ``texture()`` function:
  137. .. code-block:: glsl
  138. void vertex() {
  139. float height = texture(noise, VERTEX.xz / 2.0 + 0.5).x;
  140. VERTEX.y += height;
  141. }
  142. :ref:`texture() <shader_func_texture>` takes a texture as the first argument and
  143. a ``vec2`` for the position on the texture as the second argument. We use the
  144. ``x`` and ``z`` channels of ``VERTEX`` to determine where on the texture to look
  145. up.
  146. Since the PlaneMesh coordinates are within the ``[-1.0, 1.0]`` range (for a size
  147. of ``2.0``), while the texture coordinates are within ``[0.0, 1.0]``, to remap
  148. the coordinates we divide by the size of the PlaneMesh by ``2.0`` and add
  149. ``0.5`` .
  150. ``texture()`` returns a ``vec4`` of the ``r, g, b, a`` channels at the position.
  151. Since the noise texture is grayscale, all of the values are the same, so we can
  152. use any one of the channels as the height. In this case we'll use the ``r``, or
  153. ``x`` channel.
  154. .. note::
  155. ``xyzw`` is the same as ``rgba`` in GLSL, so instead of ``texture().x``
  156. above, we could use ``texture().r``. See the `OpenGL documentation
  157. <https://www.khronos.org/opengl/wiki/Data_Type_(GLSL)#Vectors>`_ for more
  158. details.
  159. Using this code you can see the texture creates random looking hills.
  160. .. image:: img/noise.webp
  161. Right now it is too spiky, we want to soften the hills a bit. To do that, we
  162. will use a uniform. You already used a uniform above to pass in the noise
  163. texture, now let's learn how they work.
  164. Uniforms
  165. --------
  166. :ref:`Uniform variables <doc_shading_language_uniforms>` allow you to pass data
  167. from the game into the shader. They are
  168. very useful for controlling shader effects. Uniforms can be almost any datatype
  169. that can be used in the shader. To use a uniform, you declare it in your
  170. :ref:`Shader<class_Shader>` using the keyword ``uniform``.
  171. Let's make a uniform that changes the height of the terrain.
  172. .. code-block:: glsl
  173. uniform float height_scale = 0.5;
  174. Godot lets you initialize a uniform with a value; here, ``height_scale`` is set
  175. to ``0.5``. You can set uniforms from GDScript by calling the function
  176. :ref:`set_shader_parameter() <class_ShaderMaterial_method_set_shader_parameter>`
  177. on the material corresponding to the shader. The value passed from GDScript
  178. takes precedence over the value used to initialize it in the shader.
  179. .. code-block:: gdscript
  180. # called from the MeshInstance3D
  181. mesh.material.set_shader_parameter("height_scale", 0.5)
  182. .. note:: Changing uniforms in Spatial-based nodes is different from
  183. CanvasItem-based nodes. Here, we set the material inside the PlaneMesh
  184. resource. In other mesh resources you may need to first access the
  185. material by calling ``surface_get_material()``. While in the
  186. MeshInstance3D you would access the material using
  187. ``get_surface_material()`` or ``material_override``.
  188. Remember that the string passed into ``set_shader_parameter()`` must match the name
  189. of the uniform variable in the shader. You can use the
  190. uniform variable anywhere inside your shader. Here, we will
  191. use it to set the height value instead of arbitrarily multiplying by ``0.5``.
  192. .. code-block:: glsl
  193. VERTEX.y += height * height_scale;
  194. Now it looks much better.
  195. .. image:: img/noise-low.webp
  196. Using uniforms, we can even change the value every frame to animate the height
  197. of the terrain. Combined with :ref:`Tweens <class_Tween>`, this can be
  198. especially useful for animations.
  199. Interacting with light
  200. ----------------------
  201. First, turn wireframe off. To do so, open the **Perspective** menu in the
  202. upper-left of the viewport again, and select **Display Normal**. Additionally in
  203. the 3D scene toolbar, turn off preview sunlight.
  204. .. image:: img/normal.webp
  205. Note how the mesh color goes flat. This is because the lighting on it is flat.
  206. Let's add a light!
  207. First, we will add an :ref:`OmniLight3D<class_OmniLight3D>` to the scene, and
  208. drag it up so it is above the terrain.
  209. .. image:: img/light.webp
  210. You can see the light affecting the terrain, but it looks odd. The problem is
  211. the light is affecting the terrain as if it were a flat plane. This is because
  212. the light shader uses the normals from the :ref:`Mesh <class_mesh>` to calculate
  213. light.
  214. The normals are stored in the Mesh, but we are changing the shape of the Mesh in
  215. the shader, so the normals are no longer correct. To fix this, we can
  216. recalculate the normals in the shader or use a normal texture that corresponds
  217. to our noise. Godot makes both easy for us.
  218. You can calculate the new normal manually in the vertex function and then just
  219. set ``NORMAL``. With ``NORMAL`` set, Godot will do all the difficult lighting
  220. calculations for us. We will cover this method in the next part of this
  221. tutorial, for now we will read normals from a texture.
  222. Instead we will rely on the NoiseTexture again to calculate normals for us. We
  223. do that by passing in a second noise texture.
  224. .. code-block:: glsl
  225. uniform sampler2D normalmap;
  226. Set this second uniform texture to another :ref:`NoiseTexture2D <class_noisetexture2D>` with another
  227. :ref:`FastNoiseLite <class_fastnoiselite>`. But this time, check **As Normal Map**.
  228. .. image:: img/normal-set.webp
  229. When we have normals that correspond to a specific vertex we set ``NORMAL``, but
  230. if you have a normalmap that comes from a texture, set the normal using
  231. ``NORMAL_MAP`` in the ``fragment()`` function. This way Godot will handle
  232. wrapping the texture around the mesh automatically.
  233. Lastly, in order to ensure that we are reading from the same places on the noise
  234. texture and the normalmap texture, we are going to pass the ``VERTEX.xz``
  235. position from the ``vertex()`` function to the ``fragment()`` function. We do
  236. that using a :ref:`varying <doc_shading_language_varyings>`.
  237. Above the ``vertex()`` define a ``varying vec2`` called ``tex_position``. And
  238. inside the ``vertex()`` function assign ``VERTEX.xz`` to ``tex_position``.
  239. .. code-block:: glsl
  240. varying vec2 tex_position;
  241. void vertex() {
  242. tex_position = VERTEX.xz / 2.0 + 0.5;
  243. float height = texture(noise, tex_position).x;
  244. VERTEX.y += height * height_scale;
  245. }
  246. And now we can access ``tex_position`` from the ``fragment()`` function.
  247. .. code-block:: glsl
  248. void fragment() {
  249. NORMAL_MAP = texture(normalmap, tex_position).xyz;
  250. }
  251. With the normals in place the light now reacts to the height of the mesh
  252. dynamically.
  253. .. image:: img/normalmap.webp
  254. We can even drag the light around and the lighting will update automatically.
  255. .. image:: img/normalmap2.webp
  256. Full code
  257. ---------
  258. Here is the full code for this tutorial. You can see it is not very long as
  259. Godot handles most of the difficult stuff for you.
  260. .. code-block:: glsl
  261. shader_type spatial;
  262. uniform float height_scale = 0.5;
  263. uniform sampler2D noise;
  264. uniform sampler2D normalmap;
  265. varying vec2 tex_position;
  266. void vertex() {
  267. tex_position = VERTEX.xz / 2.0 + 0.5;
  268. float height = texture(noise, tex_position).x;
  269. VERTEX.y += height * height_scale;
  270. }
  271. void fragment() {
  272. NORMAL_MAP = texture(normalmap, tex_position).xyz;
  273. }
  274. That is everything for this part. Hopefully, you now understand the basics of
  275. vertex shaders in Godot. In the next part of this tutorial we will write a
  276. fragment function to accompany this vertex function and we will cover a more
  277. advanced technique to turn this terrain into an ocean of moving waves.