Assuming that you have read Drawing a desert

Here is a WebGL experiment showing what’s taking place in Sketch.h and Sketch.cpp from the Water project’s source folder.

Sketch.h

We can see 2 new classes: SeaSurface and SeaPatch.

SeaSurface

Have a look at SeaSurface.h and SeaSurface.cpp. This class is simulating the surface of the sea, with deep water waves. It’s possible to precalculate a table of values by sampling the surface. Then, we can use the getDisplacement() method to returns a value for some sample, given a specific time and some swell factor.

SeaPatch

Have a look at SeaPatch.h and SeaPatch.cpp. A SeaPatch is a rectangular area which uses a SeaSurface to provide values for generating geometry in an optimized fashion: instead of operating on batches, we operate on their underlying buffers directly. This is similar to NoisePatch, explained in details in Drawing a desert. The only difference is that this class is sampling the surface within its setup() method.

Sketch.cpp

Sketch::Sketch()
:
fogColorShader(InputSource::resource("FogColorShader.vert"), InputSource::resource("FogColorShader.frag")),
patch(&surface)
{}

In the sketch’s constuctor, we initialize our custom shader, then we create our SeaPatch by assigning it a pointer to the SeaSurface. Note that the surface is created using the default parameters.

Inside setup()

patch.setFrontFace(CCW);
patch.setup(-200, -200, 400, 400, 4, SeaPatch::MODE_FILL | SeaPatch::MODE_GRID_H | SeaPatch::MODE_GRID_V);

We define that the mesh in our patch will be drawn in CCW mode. Then we call setup() by passing some position, some size and a grid-size. We also state that we want a mesh and as well as the horizontal and vertical lines of the grid. This method is filling the internal buffers with the proper vertex indices.

Inside update()

patch.update(clock()->getTime() * 45 / 60.0, 1);

We update the patch by passing some time value and a swell factor of 1, which is the maximum value allowed.

That’s all. The rest of the sketch is totally similar to Drawing a desert.