OpenGL 画多只恐龙 运用选择/缩放/平移操作
抽取自书本,简化了下,这本书真是讨厌,写个简单的程序花那么多弯路,也许对为大程序准备吧;
说实话,书本作者的代码还真是乱啊,编程水平也不像大神水准。《计算机图像学 OpenGL版》第三版 清华大学出版社
//画多只恐龙
//rorger, 2011
#include "vector"
#include "fstream"
#include "glut.h"
#include "iostream"
using namespace std;
struct Point{
int x ;
int y ;
};
enum Direction
{
LEFT,RIGHT,UP,DOWN
} ;
Direction oriDirection=LEFT,myDirection ;
float horizontalDir=1.0;
float verticalDir = 1.0 ;
typedef vector<Point> Polygon;
typedef vector<Polygon> PolyLines ;
PolyLines dimo ;
bool beRotated=true;
void loadData(char * fileName)
{
ifstream inStream ;
inStream.open(fileName);
if (inStream.fail())
{
cout<<"can not open file :"<<fileName<<endl;
return;
}
GLint numPolygon ,numPolyLines ;
Point currentPoint ;
inStream >> numPolyLines;
Polygon currentPolygon ;
for (int i =0 ; i < numPolyLines;i++)
{
inStream >> numPolygon ;
currentPolygon.clear();
for (int j=0;j<numPolygon ;j++)
{
inStream >> currentPoint.x>>currentPoint.y ;
currentPolygon.push_back(currentPoint);
}
dimo.push_back(currentPolygon);
}
inStream.close();
cout<<"read file: "<<fileName<<"success!"<<endl;
}
void drawDimo()
{
for (unsigned int i=0;i<dimo.size();i++)
{
glBegin(GL_LINE_STRIP);
for (unsigned int j=0;j<dimo[i].size();j++)
{
glVertex2i(dimo[i][j].x,dimo[i][j].y);
}
glEnd();
}
}
void myDisplay(void)
{
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glClear(GL_COLOR_BUFFER_BIT);
glMatrixMode(GL_MODELVIEW);
glTranslatef(320.0,240.0,0.0);
glScaled(0.1,0.1,1.0);
glColor3f(0.0f, 1.0f, 0.0f);
for (float theta=0;theta<360;theta+=30)
{
glPushMatrix();
glMatrixMode(GL_MODELVIEW);
glRotatef(theta,0.0,0.0,1.0);
glTranslatef(0.0,850,0.0);
if(!beRotated)
glRotatef(-theta,0.0,0.0,1.0);
switch(myDirection)
{
case LEFT:
horizontalDir=1.0;
glScaled(horizontalDir,verticalDir,1.0);
break;
case RIGHT:
horizontalDir=-1.0;
glScaled(horizontalDir,verticalDir,1.0);
break;
case DOWN:
verticalDir=-1.0;
glScaled(horizontalDir,verticalDir,1.0);
break;
case UP:
verticalDir=1.0;
glScaled(horizontalDir,verticalDir,1.0);
break;
}
drawDimo();
glPopMatrix();
}
glFlush();
}
void myInit(void)
{
glClearColor(0.0, 0.0, 0.0, 0.0);
glColor3f(0.0f, 1.0f, 0.0f);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(0,650,0,480);
loadData("dino.dat");
}
void myKeyboardFunc(unsigned char key,int x, int y)
{
switch ( key)
{
case 'q':
case 'Q':
exit(0);
break;
case ' ':
beRotated=!beRotated;
break;
case 'a':
case 'A':
myDirection= LEFT;
break;
case 'd':
case 'D':
myDirection = RIGHT;
break;
case 'w':
case 'W':
myDirection = UP;
break;
case 's':
case 'S':
myDirection=DOWN;
break;
}
glutPostRedisplay();
}
int main(int argc,char** argv)
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
glutInitWindowSize(640,480);
glutInitWindowPosition(100,150);
glutCreateWindow("MyDimo");
glutDisplayFunc(myDisplay);
glutKeyboardFunc(myKeyboardFunc);
myInit( );
glutMainLoop( );
}
书上是按q退出,按空格可以改变恐龙的旋转和平移;
我特意增加了 w a s d 四个方向键,控制方向;感觉不错;
上图:
关于 dimo.dat文件可以在上一篇博文中找到