Vous êtes sur la page 1sur 5

COMPUTER GRAPHICS

CS 307
COHEN-SUTHERLAND LINE CLIPPING
ALGORITHM
ASSESSMENT 3

W.M.P.G.D.M. Roshan
S/12/564

//Assesment 3
//Cohen-Sutherland Line Clipping Algorithm
#include
#include
#include
#include

<iostream>
"stdafx.h"
"GL/glut.h"
<math.h>

using namespace std;


int h = 400;
int w = 400;
int ymin , ymax , xmin , xmax , x1 , x2 , y11, y2 ;
const
const
const
const
const

int
int
int
int
int

INSIDE = 0;
LEFT = 1;
RIGHT = 2;
BOTTOM = 4;
TOP = 8;

//
//
//
//
//

0000
0001
0010
0100
1000

void init() {
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
glutCreateWindow("Cohen-Sutherland Line Clipping Algorithm");
glClearColor(0.0f, 0.0f, 0.0f, 1);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0, w, 0, h, 1, -1);
}
int getcode(int x,
int code = 0;
if (y > ymax)
if (y < ymin)
if (x < xmin)
if (x > xmax)
return code;
}

int y) {
code
code
code
code

|=
|=
|=
|=

TOP;
BOTTOM;
LEFT;
RIGHT;

void algorithm() {
int p1 = getcode(x1, y11);
int p2 = getcode(x2, y2);

double m = (double)(y2 - y11) / (x2 - x1);


//Both points inside
if (p1 == 0 && p2 == 0) {
cout << "Line is Completely Inside";
}else if ((p1 && p2) != 0) {
cout << "Line is Completely Outside";

}
else {
int x, y;
int selectPoint;
//Choose a point
if (p1 == 0)
selectPoint = p2;
else
selectPoint = p1;
//Line clips top
if (selectPoint & TOP) {
x = x1 + (ymax - y11) / m;
y = ymax;
}
else if (selectPoint & BOTTOM) { //Line clips Bottom
x = x1 + (ymin - y11) / m;
y = ymin;
}
else if (selectPoint & LEFT) {
//Line clips left
x = xmin;
y = y11 + (int)( (xmin - x1)*m);
}
else if (selectPoint & RIGHT) { //Line clips right
x = xmax;
y = y11 + (int)(m*(xmax - x1));
}
if (selectPoint == p1) {
x1 = x;
y11 = y;

}
else {
x2 = x;
y2 = y;
}

glColor3f(1.0f, 0.0f, 1.0f);


glBegin(GL_LINES);
glVertex2i(x1, y11);
glVertex2i(x2, y2);
glEnd();
}
void drawLines() {
algorithm();
glColor3f(1.0f, 1.0f, 1.0f);
glBegin(GL_LINES);

glVertex2i(xmin, ymin);
glVertex2i(xmin, ymax);
glEnd();
glBegin(GL_LINES);
glVertex2i(xmax, ymax);
glVertex2i(xmax, ymin);
glEnd();
glBegin(GL_LINES);
glVertex2i(xmin, ymax);
glVertex2i(xmax, ymax);
glEnd();
glBegin(GL_LINES);
glVertex2i(xmin, ymin);
glVertex2i(xmax, ymin);
glEnd();
glutSwapBuffers();

}
void setValue() {

cout << "Enter the


cin >> xmin>>ymin;
cout << "Enter the
400) :\t";
cin >> xmax>>ymax;
cout << "Enter the
cin >> x1>>y11;
cout << "Enter the
cin >> x2>>y2;
}

value of X min and Y min (Range 0-400) :\t";


value of X max and Y max (Range ymin or x minvalue of X1 and Y1 (Range 0-400) :\t";
value of X2 and Y2 (Range 0-400) :\t";

void display() {
glClear(GL_COLOR_BUFFER_BIT);
glutSwapBuffers();
drawLines();
}
int main(int argc, char **argv) {
glutInit(&argc, argv);
glutInitWindowPosition(0, 0);
glutInitWindowSize(w, h);
setValue();
init();
glutDisplayFunc(display);
glutMainLoop();
return 0;
}

Vous aimerez peut-être aussi