Download as txt, pdf, or txt
Download as txt, pdf, or txt
You are on page 1of 3

#include<stdio.

h>
#include<glut.h>

int xmin = 50, ymin = 50, xmax = 150, ymax = 150; //Clipping Window
int vpx = 200, vpy = 200, vpw = 500, vph = 500; //Viewport Coordinates
int x0, y0, x1, y1; //Original Line
int xc0, yc0, xc1, yc1; //Clipped Line
int reject = 0;
int RIGHT = 8, LEFT = 2, TOP = 4, BOTTOM = 1;

int checkb(int x, int y)


{
int code = 0;
if (y > ymax) code |= TOP;
if (y < ymin) code |= BOTTOM;
if (x > xmax) code |= RIGHT;
if (x < xmin) code |= LEFT;

return code;
}

void compute(int* x, int* y)


{
int code, tx, ty;
tx = *x;
ty = *y;

code = checkb(tx, ty);

while (code != 0)
{
if (checkb(xc0, yc0) & checkb(xc1, yc1))
{
reject = 1; //Both end points are outside same border
return;
}
if (code & TOP)
{
tx = xc0 + (xc1 - xc0) * (ymax - yc0) / (yc1 - yc0);
ty = ymax;
}
if (code & BOTTOM)
{
tx = xc0 + (xc1 - xc0) * (ymin - yc0) / (yc1 - yc0);
ty = ymin;
}
if (code & RIGHT)
{
ty = yc0 + (yc1 - yc0) * (xmax - xc0) / (xc1 - xc0);
tx = xmax;
}
if (code & LEFT)
{
ty = yc0 + (yc1 - yc0) * (xmin - xc0) / (xc1 - xc0);
tx = xmin;
}
*x = tx;
*y = ty;
code = checkb(tx, ty);
}
}

void cohen()
{
if (checkb(xc0, yc0) & checkb(xc1, yc1))
{
reject = 1; //Both end points are outside same border
}
else
{
compute(&xc0, &yc0);
compute(&xc1, &yc1);
}

glViewport(vpx, vpy, vpw, vph); //Viewport to draw clipped line & Window

glColor3f(1, 0, 0);
glBegin(GL_LINE_LOOP);
glVertex2f(xmin, ymin);
glVertex2f(xmax, ymin);
glVertex2f(xmax, ymax);
glVertex2f(xmin, ymax);
glEnd();

if (!reject)
{
glColor3f(0, 0, 1);
glBegin(GL_LINES);
glVertex2f(xc0, yc0);
glVertex2f(xc1, yc1);
glEnd();
}
}

void display()
{
x0 = 15; y0 = 220;
x1 = 75; y1 = 125; //Line Coordinates

xc0 = x0; yc0 = y0;


xc1 = x1; yc1 = y1; //Copy Line Coordinates to Clipped Line Coordinates

glClear(GL_COLOR_BUFFER_BIT);

glViewport(0, 0, 500, 500); //Initial viewport is entire screen


glColor3f(0, 0, 1);
glBegin(GL_LINE_LOOP);
glVertex2f(xmin, ymin);
glVertex2f(xmax, ymin);
glVertex2f(xmax, ymax);
glVertex2f(xmin, ymax);
glEnd();

glColor3f(1, 0, 0);
glBegin(GL_LINES);
glVertex2f(x0, y0);
glVertex2f(x1, y1);
glEnd();
cohen();

glFlush();
}

void init()
{
glClearColor(1, 1, 1, 0);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(0, 500, 0, 500);
}

void main(int argc, char** argv)


{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
glutInitWindowPosition(0, 0);
glutInitWindowSize(500, 500);
glutCreateWindow("CS Line Clipping");
init();
glutDisplayFunc(display);
glutMainLoop();
}

You might also like