Animating a surface with vertex displacement

A straightforward way to leverage shaders for animation is to simply transform the vertices within the vertex shader based on some time-dependent function. The OpenGL application supplies static geometry, and the vertex shader modifies the geometry using the current time (supplied as a uniform variable). This moves the computation of the vertex position from the CPU to the GPU, and leverages whatever parallelism the graphics driver makes available.

In this example, we'll create a waving surface by transforming the vertices of a tessellated quad based on a sine wave. We'll send down the pipeline a set of triangles that make up a flat surface in the x-z plane. In the vertex shader, we'll transform the y coordinate of each vertex based on a time-dependent sine function, and compute the normal vector of the transformed vertex. The following image shows the desired result (you'll have to imagine that the waves are travelling across the surface from left to right):

Alternatively, we could use a noise texture to animate the vertices (that make up the surface) based on a random function. (See Chapter 9, Using Noise in Shaders, for details on noise textures.)

Before we jump into the code, let's take a look at the mathematics that we'll need.

We'll transform the coordinate of the surface as a function of the current time and the modeling coordinate. To do so, we'll use the basic plane wave equation, as shown in the following diagram:

A is the wave's amplitude (the height of the peaks), the lambda (λ) is the wavelength (the distance between successive peaks), and v is the wave's velocity. The previous diagram shows an example of the wave when t = 0 and the wavelength is equal to one. We'll configure these coefficients through uniform variables.

In order to render the surface with proper shading, we also need the normal vector at the transformed location. We can compute the normal vector using the (partial) derivative of the previous function. The result is the following equation:

Of course, this vector should be normalized before we use it in our shading model.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
13.59.9.236