Saturday, April 23, 2016

A Moving Mesh

Are you looking to something, that easy to implement for your CGV project?
Then you are here going to get a simple program you to can add something to it and make a good workable project. This program is called Moving Mesh.

The Moving mesh is like what we use to have in DD when TV lost the signal and we get a cross horizontal moving long rectangle in different color moving fast. You can view the same in image below.

Let Program the Moving Mesh

First we are going to add all the Header files and global variable will be declare.
```#include<glut.h>
#include<stdio.h>
#include<math.h>
#include<stdlib.h>

static  GLdouble  viewer[]={0,0,5};
float dx=0.5,dy=0.5;
float angle=0;```

To draw a mesh we are defining the mesh() function which uses the concept of looping and draw with help of vertices (primitive function). The code is given below -

```void mesh()
{
float a=0.5,b=0.5,c=1;
float  i, j;
for(i=0;i<15;i+=dx)
for(j=0;j<15;j+=dy)
{
glBegin(GL_POLYGON);
glColor3f(a,b,c*fabs(sin(100*i+angle)));
glVertex2f( i, j);
glVertex2f( i+dx, j);
glVertex2f( i+dx, j+dy);
glVertex2f( i, j+dy);
glVertex2f( i, j);
glEnd();
}
}```
Now Display the Mesh with the display function as given below. Also we make sure the mesh continues to display and work well, we defined the idel and reshape functions.

```void display()
{
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
gluLookAt(viewer[0],viewer[1],viewer[2],0,0,0,0,1,0);
glTranslated(4,4,-5);
mesh();
glFlush();
glutSwapBuffers();
}
void idle()
{
angle++;
if(angle>360) angle=0;
glutPostRedisplay();
}
void myReshape(int w,int h)
{
glViewport(0,0,w,h);
glMatrixMode(GL_PROJECTION);
glOrtho(-2,20,-2,20,-10,20);
glMatrixMode(GL_MODELVIEW);
}```

Now time for the main program which is as usual almost same for all the C/C++ OpenGL Programs.

```int main(int argc,char **argv)
{

glutInit(&argc,argv);
glutInitDisplayMode(GLUT_DOUBLE|GLUT_RGB|GLUT_DEPTH);
glutInitWindowSize(500,500);
glutInitWindowPosition(0,0);
glutCreateWindow("A Moving Mesh");
glutDisplayFunc(display);
glutReshapeFunc(myReshape);
glutIdleFunc(idle);
glClearColor(1.0,1.0,1.0,1.0);
glEnable(GL_DEPTH_TEST);
glutMainLoop();
return 0;
}```

You can add something to this program and make it interactive, like a keyboard or mouse function to start and stop motion.