光柵圖形學(三)——梁友棟-Barskey剪裁算法
一、問題轉換
- 直線的參數方程
其中。對於直線上的一點,若它在窗口內則有
- 條件方程轉換
綜合上述方程,可以歸納爲。
(1) 下限組
(2) 上限組
則此時若直線落在窗口內應滿足
二、算法過程
(1)輸入直線的兩端點座標:和,以及窗口的四條邊界座標:。
(2)若,則。此時進一步判斷是否滿足或,若滿足,該直線不在窗口內,算法轉(7)。否則,滿足且,算法轉(6)。
(3)若,則。此時進一步判斷是否滿足或,若滿足,該直線不在窗口內,算法轉(7)。否則,滿足且,算法轉(6)。
(4)若上述都不滿足,則有。此時計算下限組和上限組,算法轉(5)。
(5)求得和後,若,則直線在窗口外,算法轉(7)。若,算法轉(6)。
(6)利用直線的掃描轉換算法繪製在窗口內的直線段。
(7)算法結束。
三、Liang-Barskey算法-示例
四、代碼實現(python)
import matplotlib.pyplot as plt
def plot_line(x1,x2,y1,y2,wxl,wxr,wyb,wyt):
plt.plot([x1,x2], [y1,y2], 'g')
plt.scatter([x1,x2], [y1,y2], color='b')
#裁剪
p1 = -(x2 - x1)
q1 = x1 - wxl
p2 = x2 - x1
q2 = wxr - x1
p3 = -(y2 - y1)
q3 = y1 - wyb
p4 = y2 - y1
q4 = wyt - y1
ymax = max(y1,y2)
ymin = min(y1,y2)
if p1 == 0 and p2 == 0: # 算法過程2
if q1 > 0 and q2 > 0:
if ymin >= wyb and ymax <= wyt: # 兩端點都在窗口內
plt.plot([x1,x2], [ymin,ymax], 'm')
elif ymin < wyb and ymax <= wyt:
plt.plot([x1,x2], [wyb,ymax], 'm') # 一個端點在窗口內
elif ymin >= wyb and ymax > wyt:
plt.plot([x1,x2], [ymin,wty], 'm') # 一個端點在窗口內
else:
plt.plot([x1,x2], [wyb,wyt], 'm') # 端點都不在窗口內
elif p3 == 0 and p4 == 0: # 算法過程3
if q3 > 0 and q4 > 0:
if x1 >= wxl and x2 <= wxr: # 兩端點都在窗口內
plt.plot([x1,x2], [y1,y2], 'm')
elif x1 < wxl and x2 <= wxr:
plt.plot([wxl,x2], [y1,y2], 'm') # 一個端點在窗口內
elif wxl >= x1 and x2 > wxr:
plt.plot([x1,wxr], [y1,y2], 'm') # 一個端點在窗口內
else:
plt.plot([wxl,wxr], [y1,y2], 'm') # 端點都不在窗口內
else: # 算法過程45
ul = 0
ur = 1
for e in [[p1,q1],[p2,q2],[p3,q3],[p4,q4]]:
if e[0] < 0:
ul = max(ul,e[1]/e[0])
else:
ur = min(ur,e[1]/e[0])
# 判斷線代落在窗口內與否
if ul < ur:
plt.plot([x1+ul*p2,x1+ur*p2],[y1+ul*p4,y1+ur*p4],'m')
def plot_window(wxl,wxr,wyb,wyt):
# 要連接的兩個點的座標
x = [[wxl,wxr],[wxr,wxr],[wxr,wxl],[wxl,wxl]]
y = [[wyb,wyb],[wyb,wyt],[wyt,wyt],[wyt,wyb]]
for i in range(len(x)):
plt.plot(x[i], y[i], color='r')
if __name__ == '__main__':
# 設置座標軸區間
plt.axis([0,100,0,100])
# 顯示窗口函數
plot_window(20,60,20,60)
# 顯示直線函數
plot_line(10,70,8,50,20,60,20,60)
plot_line(50,90,40,5,20,60,20,60)
plot_line(30,30,6,55,20,60,20,60)
plot_line(2,15,6,95,20,60,20,60)
plot_line(5,80,90,30,20,60,20,60)
plot_line(8,60,70,70,20,60,20,60)
plot_line(23,40,50,50,20,60,20,60)
plot_line(5,68,45,30,20,60,20,60)
plt.title("Liang-Barskey Algorithm")
plt.show()
- 結果圖
若有任何錯誤還望指正,參考博客:https://blog.csdn.net/soulmeetliang/article/details/79185603