- 定义数据类型
-
typedef struct{ GLfloat x; // x 坐标 GLfloat y; // y 坐标 } Vertex2F; typedef struct{ GLfloat r; // red (0~1) GLfloat g; // green GLfloat b; // blue GLfloat a; // alpha } Color4F;
- 定义顶端数据
-
static Color4F red_color = {1.0f,0.0f,0.0f,1.0f}; static Color4F green_color = {0.0f,1.0f,0.0f,1.0f}; static Color4F blue_color = {0.0f,0.0f,1.0f,1.0f}; static Vertex2F trangle_vertexes [3] = { {10,10},{100,10},{100,100} }; static Vertex2F rect_vertexes [4] = { {20,200},{200,200}, {20,300},{200,300} }; static Vertex2F polygon_vertexes [6] = { {350,50},{450,120}, {450,220},{350,300}, {250,220},{250,120}, };
- 绘制三角形
-
void draw_trangle(){ glEnableClientState(GL_VERTEX_ARRAY); glColor4f(red_color.r,red_color.g,red_color.b,red_color.a); glVertexPointer(sizeof(Vertex2F)/sizeof(GLfloat),GL_FLOAT,0,trangle_vertexes); glDrawArrays(GL_TRIANGLE_STRIP,0,3); }
- 绘制矩形
-
void draw_rect(){ glEnableClientState(GL_VERTEX_ARRAY); glColor4f(green_color.r,green_color.g,green_color.b,green_color.a); glVertexPointer(sizeof(Vertex2F)/sizeof(GLfloat),GL_FLOAT,0,rect_vertexes); glDrawArrays(GL_TRIANGLE_STRIP,0,4); }
- 绘制任意多边形
-
void draw_polygon(){ glEnableClientState(GL_VERTEX_ARRAY); glColor4f(blue_color.r,blue_color.g,blue_color.b,blue_color.a); glVertexPointer(sizeof(Vertex2F)/sizeof(GLfloat),GL_FLOAT,0,polygon_vertexes); glDrawArrays(GL_TRIANGLE_FAN,0,6); }
- 统一坐标系(默认opengl的尺寸是整个窗口是坐标是x=0.5,y=0.5,width=1.0,height=1.0),经过下面的处理可以让窗口的大小和opengl里面的大小一致
-
void reshape(int width,int height){ glViewport(0, 0, width, height); const float& fovy = 60; const float& zeye = height /(tan(fovy*M_PI_2/180)*2); glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluPerspective(fovy, (GLfloat) width / height, 0.5f, 150000.0f); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); gluLookAt(width / 2, height / 2, zeye, width / 2, height / 2, 0, 0.0f, 1.0f,0.0f); }
- 在display函数中调用
-
void display(){ glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); draw_trangle(); draw_rect(); draw_polygon(); glutSwapBuffers(); glutPostRedisplay(); }
- 生成程序
g++ DrawShapes.cpp -lGLEW -lGL -lGLU -lglut -o DrawShapes
- 运行效果
opengl 开发笔记-绘制图形(图元)
最新推荐文章于 2024-11-05 17:26:03 发布