本节是对笔记2代码的扩展。利用glut生成简单的动画效果。
最近学习中遇到的几点困惑:
1.OpenGL到底是什么?以SGI的GL三维图形库为基础制定的一个通用共享的开放式三维图形标准。定义上来看,OpenGL只是一个标准。
2.OpenGL如何工作?
3.OpenGL和OpenGL扩展之间的关系?
4.使用OpenGL中某些特定功能编写的效果,被我自己的机子的显卡支持可以运行,在别人的机子上是否无法运行?在Mac, linux上是怎么样解决这个问题的?
·随着学习的深入会搞清楚这些最基本的问题。希望有大神可以指教!
本次的代码如下:
GLfloat x1 = 0.0f;
GLfloat y1 = 0.0f;
GLfloat rsize = 25;
GLfloat xstep = 1.0f;
GLfloat ystep = 1.0f;
GLfloat width = 0.0f;
GLfloat height = 0.0f;
void RenderScene(void)
{
//Using the current color clear the window
glClear(GL_COLOR_BUFFER_BIT);
//Set the draw color to red
glColor3f(1.0f, 0.0f, 0.0f);
//use the current draw color draw a rectangle
glRectf(x1, y1, rsize+x1, y1-rsize);
//Refresh the drawing commands
glutSwapBuffers();
}
void SetupRC(void)
{
glClearColor(0.6f, 0.4f, 0.7f, 1.0f);
}
void ChangeSize(GLsizei w, GLsizei h)
{
//To prevent the dividend is zero
if (h == 0)
{
h = 1;
}
glViewport(0, 0, w, h);
//reset coordinate system
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
//build clipping region(left, right, bottom, top, near, far)
GLfloat aspectRatio = (GLfloat)w/h;
GLfloat nRange = 100.0f;
if (w <= h)
{
glOrtho(-nRange, nRange, -nRange/aspectRatio, nRange/aspectRatio, 1.0, -1.0);
width = nRange;
height = nRange/aspectRatio;
}
else
{
glOrtho(-nRange*aspectRatio, nRange*aspectRatio, -nRange, nRange, 1.0, -1.0);
width = nRange*aspectRatio;
height = nRange;
}
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
}
void TimerFunction(int value)
{
if (x1<=-width || x1+rsize>=width)
{
xstep = - xstep;
}
if(y1 >= height || y1-rsize <= -height)
{
ystep = -ystep;
}
x1 += xstep;
y1 += ystep;
//Draw the scene with the new coordinates
glutPostRedisplay();
glutTimerFunc(33, TimerFunction, 1);
}
int main(int argc, char* argv[])
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE|GLUT_RGBA);
glutInitWindowSize(800, 600);
glutCreateWindow("GLAnimation");
glutDisplayFunc(RenderScene);
glutReshapeFunc(ChangeSize);
glutTimerFunc(10, TimerFunction, 1);
SetupRC();
glutMainLoop();
return 0;
}
代码运行的结果如下:
本节代码下载地址(visual studio 2012):http://download.csdn.net/detail/airbigboy/6326567
glut:
void glutTimerFunc( unsigned int time, void (* callback)( int ), int value );
time:多长时间后调用回调函数,第二个参数为回调函数的指针,value为TimerFunction的ID
该函数为间隔time时间后(单位为毫秒)调用一次回调函数。所以需要在TimerFunction中每次都调用。