Tutorial 05 - Using distortion mesh

In this tutorial we will learn how to use distortion mesh, a technique allowing you to create effects like water, lenses, page wraps, various twists and even real-time morphing. In this tutorial we use static texture, but you could render your whole game scene onto a texture using render targets functionality and then put it on the screen via distortion mesh to achieve some cool real-time effects.


First, we include the required headers and declare the variables to handle our texture and distortion mesh:

#include <hge.h>
#include <hgedistort.h>
#include <math.h>

HGE *hge = 0;
hgeDistortionMesh *dis;

Then we declare some constants we will use. Here we define the mesh resolution and on-screen position:

const int nRows=16;
const int nCols=16;

const float meshx=144;
const float meshy=44;

In the FrameFunc (frame function) we need some variables too. A couple of them for timing and the rest are used for displacements calculation:

  float dt;
  static float t=0.0f;
  int i, j, col;

Well, here's the tricky part. To animate our mesh we calculate it's displacements and coloring based on time elapsed:


  for(i=0; i<nRows; i++)
    for(j=1; j<nCols-1; j++)
      dis->SetDisplacement(j, i, cosf(t*5+j/2)*15,0,HGEDISP_NODE);
      dis->SetColor(j, i, 0xFF<<24 | col<<16 | col<<8 | col);

And finally we render the mesh to the screen within the RenderFunc:

  dis->Render(meshx, meshy);

In the WinMain function we should load a texture and initialize the mesh:

  dis=new hgeDistortionMesh(nCols, nRows);
  dis->SetTextureRect(0, 0, 512, 512);

And during shutdown we should delete the texture and the mesh from memory:

  delete dis;

Voila! It's that simple.

The complete source code with detailed comments for this tutorial you may find in the folder tutorials\tutorial05. The required media files you'll find in the folder tutorials\precompiled.