/* gltest.c 一个用OPENGL画圆的程序 */
/* 输入原点坐标和半径 */
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <GL/glut.h>
#define pai 3.14
int m;//细分次数
float r;//圆半径
struct POINT // 点结构
{
float x;
float y;
};
struct POINT *pstuVertex;// 保存细分后多边形各顶点坐标
struct POINT stuO;// 保存圆心坐标
// 求细分后的顶点坐标
// pstuV 保存细分后的各顶点坐标,使用前初始化
// pO 圆心坐标
// m 细分次数
void get_vertex( struct POINT *pstuV,struct POINT *pO,int m,float r)
{
int n;
float fAngle=2*pai/(float)m;
pstuV[0].x=pO->x;//保存圆心坐标
pstuV[0].y=pO->y;
for( n=0;n<m;n++)
{
pstuV[n+1].x=r*cos(n*fAngle)+pstuV[0].x;
pstuV[n+1].y=r*sin(n*fAngle)+pstuV[0].y;
}
}
// 初始化顶点结构缓冲区
// pstuP 传递多边形细分后的顶点坐标
// m 细分次数,在这确定缓冲区尺寸
struct POINT * init_array( int m )
{
struct POINT *pstuP;
pstuP=(struct POINT *)calloc( m,sizeof( POINT ) );
return pstuP;
}
// 显示,没传递参数。
//使用全局变量。
void display()
{
int i;
GLfloat v1[2],v2[2],v3[2];
glClear(GL_COLOR_BUFFER_BIT);
glColor3f(1.0,1.0,0.0);
glLineWidth(4.0);
glPolygonMode(GL_FRONT_AND_BACK,GL_LINE);
v3[0]=pstuVertex[0].x;
v3[1]=pstuVertex[0].y;
for(i=1;i<=m;i++)
{
v1[0]=pstuVertex[i].x;
v1[1]=pstuVertex[i].y;
if(i==m)
{
v2[0]=pstuVertex[1].x;
v2[1]=pstuVertex[1].y;
}
else
{
v2[0]=pstuVertex[i+1].x;
v2[1]=pstuVertex[i+1].y;
}
glBegin(GL_POLYGON);
glEdgeFlag(GL_FALSE);
glVertex2fv(v3);
glEdgeFlag(GL_TRUE);
glVertex2fv(v1);
glEdgeFlag(GL_FALSE);
glVertex2fv(v2);
glEnd();
}
glFlush();
}
void main(int argc,char ** argv)
{
glutInit(&argc,argv);
glutInitWindowSize(800,800);
glutCreateWindow("多边形渐进画圆");
// 输入圆心坐标和半径
printf("圆心X坐标:");
scanf("%f",&(stuO.x));
printf("/n");
printf("圆心Y坐标:");
scanf( "%f",&(stuO.y));
printf("/n");
printf("圆半径:");
scanf("%f",&r);
printf("/n");
printf("细分次数:");
scanf("%d",&m);
pstuVertex=init_array( m );//初始化保存细分后顶点缓冲区
get_vertex( pstuVertex, &stuO,m ,r);
glutDisplayFunc(display);
glutMainLoop();
free(pstuVertex);
}