Cohen Sutherland Line Clipping


#include<stdio.h>
#include<GL/glut.h>
#define outcode int
double xmin = 100, ymin = 100, xmax = 200, ymax = 200; // clipping window
double x0, y0, x1, y1;
const int RIGHT=8;
const int LEFT=2;
const int TOP=4;
const int BOTTOM=1;
outcode ComputeOutCode(double x, double y);

void CohenSutherland(double x0, double y0, double x1, double y1)
{
outcode outcode0, outcode1, outcodeOut;
bool accept=false, done=false;
outcode0=ComputeOutCode(x0,y0);
outcode1=ComputeOutCode(x1,y1);
do
{
if(!(outcode0|outcode1))
{
accept=true; // Line is completely visible
done=true;
}
else if(outcode0&outcode1)
done=true; // Line is completely invisible
else // Line is partially visible
{
double x, y;
outcodeOut=outcode0?outcode0:outcode1;
if(outcodeOut&TOP)
{
x=x0+(x1-x0)*(ymax-y0)/(y1-y0);
y=ymax;
}
else if(outcodeOut&BOTTOM)
{
x=x0+(x1-x0)*(ymin-y0)/(y1-y0);
y=ymin;
}
else if(outcodeOut&RIGHT)
{
y=y0+(y1-y0)*(xmax-x0)/(x1-x0);
x=xmax;
}
else
{
y=y0+(y1-y0)*(xmin-x0)/(x1-x0);
x=xmin;
}
if(outcodeOut==outcode0)
{
x0=x;
y0=y;
outcode0=ComputeOutCode(x0,y0);
}
else
{
x1=x;
y1=y;
outcode1=ComputeOutCode(x1,y1);
}
}
}while(!done);
if(accept)
{
glColor3f(1.0,0.0,0.0); // Draw clipped line in red colour
glBegin(GL_LINES);
glVertex2d(x0,y0);
glVertex2d(x1,y1);
glEnd();
}
}
outcode ComputeOutCode(double x, double y)
{
outcode code=0; // Assign region code
if(y>ymax)
code=TOP;
else if(y<ymin)
code=BOTTOM;
if(x>xmax)
code=RIGHT;
else if(x<xmin)
code=LEFT;
return code;
}
void display()
{
glClear(GL_COLOR_BUFFER_BIT);
glColor3f(1.0,1.0,1.0);
glBegin(GL_LINES); // Draw initial line
glVertex2d(x0,y0);
glVertex2d(x1,y1);
glEnd();
glColor3f(1.0,1.0,0.0);
glBegin(GL_LINE_LOOP); // Draw clipping window
glVertex2f(xmin, ymin);
glVertex2f(xmax, ymin);
glVertex2f(xmax, ymax);
glVertex2f(xmin, ymax);
glEnd();
CohenSutherland(x0,y0,x1,y1);
glFlush();
}
void myinit()
{
glClearColor(0.0,0.0,0.0,1.0);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(0.0,300.0,0.0,300.0);
}
int main(int argc, char** argv)
{
printf("Enter the end points of the line: ");
scanf("%lf%lf%lf%lf", &x0,&y0,&x1,&y1);
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_SINGLE|GLUT_RGB);
glutInitWindowSize(500,500);
glutInitWindowPosition(0,0);
glutCreateWindow("Cohen-Sutherland Line Clipping");
glutDisplayFunc(display);
myinit();
glutMainLoop();
return 0;
}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s