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;
HTEXTURE tex;
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:

  dt=hge->Timer_GetDelta();
  t+=dt;

  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);
      col=int((cosf(t*5+(i+j)/2)+1)*35);
      dis->SetColor(j, i, 0xFF<<24 | col<<16 | col<<8 | col);
    }

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

  hge->Gfx_BeginScene();
  hge->Gfx_Clear(0);
  dis->Render(meshx, meshy);
  hge->Gfx_EndScene();

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

  tex=hge->Texture_Load("texture.jpg");
  dis=new hgeDistortionMesh(nCols, nRows);
  dis->SetTexture(tex);
  dis->SetTextureRect(0, 0, 512, 512);
  dis->SetBlendMode(BLEND_COLORADD|BLEND_ALPHABLEND|BLEND_ZWRITE);
  dis->Clear(0xFF000000);

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

  delete dis;
  hge->Texture_Free(tex);

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.