计算机图形学实验C++代码
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
一、bresenham算法画直线
#include
#include
#include
void draw_pixel(int ix,int iy)
{
glBegin(GL_POINTS);
glVertex2i(ix,iy);
glEnd();
}
void Bresenham(int x1,int y1,int xEnd,int yEnd) {
int dx=abs(xEnd-x1),dy=abs(yEnd-y1);
int p=2*dy-dx;
int twoDy=2*dy,twoDyMinusDx=2*dy-2*dx;
int x,y;
if (x1>xEnd)
{
x=xEnd;y=yEnd;
xEnd=x1;
}
else
{
x=x1;
y=y1;
}
draw_pixel(x,y);
while(x { x++; if(p<0) p+=twoDy; else { y++; p+=twoDyMinusDx; draw_pixel(x,y); } } } void display() { glClear(GL_COLOR_BUFFER_BIT); Bresenham(0,0,400,400); glFlush(); } void myinit() { glClearColor(0.8,1.0,1.0,1.0); glColor3f(0.0,0.0,1.0); glPointSize(1.0); glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluOrtho2D(0.0,500.0,0.0,500.0); } void main(int argc,char **argv ) { glutInit(&argc,argv); glutInitDisplayMode(GLUT_SINGLE|GLUT_RGB); glutInitWindowSize(500,500); glutInitWindowPosition(200.0,200.0); glutCreateWindow("CG_test_Bresenham_Line example"); glutDisplayFunc(display); myinit(); glutMainLoop(); } 二、中点法绘制椭圆 #include #include #include inline int round(const float a){return int (a+0.5);} void setPixel(GLint xCoord,GLint yCoord) { glBegin(GL_POINTS); glVertex2i(xCoord,yCoord); glEnd(); } void ellipseMidpoint(int xCenter,int yCenter,int Rx,int Ry) { int Rx2=Rx*Rx; int Ry2=Ry*Ry; int twoRx2=2*Rx2; int twoRy2=2*Ry2; int p; int x=0; int y=Ry; int px=0; int py=twoRx2*y; void ellipsePlotPoints(int,int,int,int); ellipsePlotPoints(xCenter,yCenter,x,y); p=round(Ry2-(Rx2*Ry)+(0.25*Rx2)); while(px x++; px+=twoRy2; if(p<0) p+=Ry2+px; else{ y--; py-=twoRx2; p+=Ry2+px-py; } ellipsePlotPoints(xCenter,yCenter,x,y); } p=round(Ry2*(x+0.5)*(x+0.5)+Rx2*(y-1)*(y-1)-Rx2*Ry2); while(y>0){ y--; py-=twoRx2; if(p>0) p+=Rx2-py; else{ x++; px+=twoRy2; p+=Rx2-py+px; } ellipsePlotPoints(xCenter,yCenter,x,y); } } void ellipsePlotPoints(int xCenter,int yCenter,int x,int y) { setPixel(xCenter+x,yCenter+y); setPixel(xCenter-x,yCenter+y); setPixel(xCenter+x,yCenter-y); setPixel(xCenter-x,yCenter-y); } void display() { glClear(GL_COLOR_BUFFER_BIT); ellipseMidpoint(200,200,50,30); glFlush(); } void myinit() { glClearColor(0.8,1.0,1.0,1.0); glColor3f(0.0,0.0,1.0); glPointSize(1.0);