-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCohen_Sutherland_Line_Cliping.py
127 lines (108 loc) · 2.39 KB
/
Cohen_Sutherland_Line_Cliping.py
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
from graphics import GraphWin,Rectangle,Point
INSIDE = 0
LEFT = 1
RIGHT = 2
BOTTOM = 4
TOP = 8
x_max = 600
y_max =600
x_min = 400
y_min = 400
win=GraphWin("Suderland Line CLipping",800,800)
def Bresenhams(x1,y1,x2,y2):
x=x1
y=y1
dx=abs(x2-x1)
dy=abs(y2-y1)
if x2-x1>0:s1=1
else : s1=-1
if y2-y1>0:s2=1
else :s2=-1
if dy>dx:
dx,dy=dy,dx
interchange=1
else :
interchange = 0
e_ = 2*dy - dx
for i in range(dx):
win.plot(x,y)
while e_>0 :
if interchange==1:
x+=s1
else :
y+=s2
e_-=2*dx
if interchange==1:
y+=s2
else:
x+=s1
e_+=2*dy
def computeCode(x, y):
code = INSIDE
if x < x_min:
code |= LEFT
elif x > x_max:
code |= RIGHT
if y < y_min:
code |= BOTTOM
elif y > y_max:
code |= TOP
print(code)
return code
def cohenSutherlandClip(x1, y1, x2, y2):
code1 = computeCode(x1, y1)
code2 = computeCode(x2, y2)
accept=False
while True:
if code1 == 0 and code2 == 0:
accept = True
break
elif (code1 & code2) != 0:
break
else:
x = 1.0
y = 1.0
if code1 != 0:
code_out = code1
else:
code_out = code2
if code_out & TOP:
x = x1 + (x2 - x1) * (y_max - y1) / (y2 - y1)
y = y_max
elif code_out & BOTTOM:
x = x1 + (x2 - x1) * (y_min - y1) / (y2 - y1)
y = y_min
elif code_out & RIGHT:
y = y1 + (y2 - y1) * (x_max - x1) / (x2 - x1)
x = x_max
elif code_out & LEFT:
y = y1 + (y2 - y1) * (x_min - x1) / (x2 - x1)
x = x_min
if code_out == code1:
x1 = x
y1 = y
code1 = computeCode(x1,y1)
else:
x2 = x
y2 = y
code2 = computeCode(x2, y2)
if accept :
Bresenhams(x1,y1,x2,y2)
print("(x1: %d , y1 : %d),(x2: %d , y2 : %d)"%(x1,y1,x2,y2))
else:
print("Line rejected")
if __name__=="__main__":
window=Rectangle(Point(x_max,y_max),Point(x_min,y_min))
window.draw(win)
#Bresenhams(100,300,400,700)
#Bresenhams(425,425,500,500)
Bresenhams(50,375,700,600)
win.getMouse()
win.delete("all")
window=Rectangle(Point(x_max,y_max),Point(x_min,y_min))
window.draw(win)
#cohenSutherlandClip(100,300,400,700)
#cohenSutherlandClip(425,425,500,500)
cohenSutherlandClip(50, 375, 700, 600)
win.getMouse()
win.close()