-
Notifications
You must be signed in to change notification settings - Fork 120
/
PROG5.cpp
137 lines (130 loc) · 2.67 KB
/
PROG5.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
#include<stdio.h>
#include<GL/glut.h>
#define true 1;
#define false 0;
#define bool int;
double x,y;
int xmin=50,xmax=100,ymin=50,ymax=100;
const int RIGHT=8,LEFT=2,TOP=4,BOTTOM=1;
int outcode0,outcode1,outcodeout,done,accept;
int computeoutcode(double x,double y)
{
int code=0;
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 LineClip(double x0,double y0,double x1,double y1)
{
int accept=false;
int done=false;
outcode0=computeoutcode(x0,y0);
outcode1=computeoutcode(x1,y1);
do{
if(!(outcode0|outcode1))
{
accept=true;
done=true;
}
else if(outcode0&outcode1)
{
done=true;
}
else
{
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)
{
glPushMatrix();
glTranslatef(100,100,0);
glColor3f(1.0,0.0,0.0);
glBegin(GL_LINE_LOOP);
glVertex2i(50,50);
glVertex2i(100,50);
glVertex2i(100,100);
glVertex2i(50,100);
glEnd();
glColor3f(1.0,0.0,1.0);
glBegin(GL_LINES);
glVertex2i(x0,y0);
glVertex2i(x1,y1);
glEnd();
glPopMatrix();
glFlush();
}
}
void display()
{
glClearColor(1,1,1,1);
glClear(GL_COLOR_BUFFER_BIT);
glColor3f(1.0,0.0,0.0);
glBegin(GL_LINE_LOOP);
glVertex2i(50,50);
glVertex2i(100,50);
glVertex2i(100,100);
glVertex2i(50,100);
glEnd();
glColor3f(1.0,0.0,1.0);
glBegin(GL_LINES);
glVertex2i(60,20);
glVertex2i(80,120);
glVertex2i(80,20);
glVertex2i(60,120);
glEnd();
LineClip(60,20,80,120);
LineClip(80,20,60,120);
glFlush();
}
void init()
{
glMatrixMode(GL_PROJECTION);
gluOrtho2D(0,300,0,300);
glMatrixMode(GL_MODELVIEW);
}
int main(int argc,char** argv)
{
glutInit(&argc,argv);
glutInitDisplayMode(GLUT_SINGLE|GLUT_RGB);
glutInitWindowPosition(0,0);
glutInitWindowSize(500,500);
glutCreateWindow("Cohen Sutherland line and drawing algorithm");
init();
glutDisplayFunc(display);
glutMainLoop();
}