本人的第一个图形学程序,一开始写错了,是因为算法公式推导错了,所以大家要好好推导一下,看同学写的程序,都太过冗余,所以把自己写的拿上来,可能页还有很多不好的地方,希望大家大胆批评,我承受的起,只有那样才可以更快的进步嘛
当然主要的代码部分是 MyLine() 函数,其它都是框架程序
// ====== Computer Graphics Experiment #1 ======
// | Bresenham's Line Drawing Algorithm |
// | |
// =============================================
//
// Requirement:
// Implement a general Bresenham's Line Drawing Algorithm.
// Only use GL_POINTS drawing mode.
// Do not use OpenGL line drawing capability.
#include <windows.h>
#include <GL/glut.h>
#include <math.h>
#define PI 3.14159265359
int width, height;
// Bresenham line algorithm
void MyLine(int xs, int ys, int xe, int ye)
{
// Write your code here
int dx1 = xe - xs;
int dy1 = ye - ys;
int dx = fabs(dx1);
int dy = fabs(dy1);
int x = xs;
int y = ys;
int p;
int incX;
int incY;
if( dx1 > 0)
incX = 1;
else
incX = -1;
if( dy1 > 0)
incY = 1;
else
incY = -1;
glBegin( GL_POINTS );
if( dy < dx )//斜率小于1的情况
{
p = 2 * dy - dx;
while( x != xe)//循环画点成线
{
x += incX;
glVertex2i ( x,y );
if( p < 0 )//讨论p的正负
{
p = p + 2 * dy;
}
else
{
y += incY;
p = p + 2 * dy - 2 * dx;
}
}
}
else if( dy >= dx )//斜率大于1
{
p = 2 * dx - dy;
while( y != ye)
{
y += incY;
glVertex2i ( x,y );
if( p < 0 )
{
p = p + 2 * dx;
}
else
{
x += incX;
p = p + 2 * dx - 2 * dy;
}
}
}
glEnd();
}
// Initialization function
void init(void)
{
glClearColor (0.0, 0.0, 0.0, 0.0);
}
// Display callback function
void display(void)
{
int i, x0, y0, x, y;
double a;
glClear (GL_COLOR_BUFFER_BIT);
x0=width/2;
y0=height/2;
glColor3f(1.0, 1.0, 1.0);
// Draw lines
for (i=0; i<360; i+=15)
{
a=(double)i/180.0*PI;
x=0.45*width*cos(a);
y=0.45*height*sin(a);
if (i==0 || i==180) y=0;
if (i==90 || i==270) x=0;
MyLine(x0, y0, x0+x, y0+y);
}
glFlush();
}
// Reshape callback function
void reshape(int w, int h)
{
// Record width and height of program window
width=w;
height=h;
// Set clipping window and viewport equal to
// view area of program window
glViewport(0, 0, w, h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D (0.0, w, 0.0, h);
}
// Keyboard callback function
void keyboard(unsigned char key, int x, int y)
{
switch (key) {
case 27:
exit(0);
}
}
// Main program entrance
int main(int argc, char* argv[])
{
// Create window
glutInit(&argc, argv);
glutInitDisplayMode (GLUT_RGB);
glutInitWindowSize(500, 500);
glutCreateWindow("Lines");
// Initialization
init();
// Define callback functions
glutReshapeFunc(reshape);
glutKeyboardFunc(keyboard);
glutDisplayFunc(display);
// Main program loop. (Event loop)
glutMainLoop();
return 0;
}