Python 配 OpenGL,聽起來就頗有意思。第一步是取得 PyOpenGL 套件:
https://pypi.python.org/pypi/PyOpenGL/3.0.2
Windows 下安裝很單純,安裝程式會自動找到你的 Python 目錄,一路下一步即可。
from OpenGL.GL import *
from OpenGL.GLU import *
from OpenGL.GLUT import *
def Draw():
glClear(GL_COLOR_BUFFER_BIT)
glRotatef(0.5, 0, 1, 0)
glutWireTeapot(0.5)
glFlush()
glutInit()
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGBA)
glutInitWindowSize(400, 400)
glutCreateWindow("test")
glutDisplayFunc(Draw)
glutIdleFunc(Draw)
glutMainLoop()
可以看到 Python 裡同樣能用 glut 建視窗,語法服從 Python 風格,但整體結構與 C 語言的 glut 幾乎一致。既然如此,先前用 C 寫的時鐘程式應該也能移植——結果還真的成功了。
一、全域變數。Update 與 Draw 都要用到 h、m、s,在 Update 中賦值前必須先 global h, m, s 宣告,否則會變成區域變數。
二、三角函數。記得 import math,呼叫時寫 math.cos、math.sin。
三、資料型別。Python 不用事先宣告型別,需要浮點運算時若初值是整數會出錯,要補上小數點,例如 count = 60.0。
四、縮排。Python 用縮排標示程式區塊,C 語言裡習慣在 glBegin() 後把定點語句縮排,搬到 Python 反而會出問題。
from OpenGL.GL import *
from OpenGL.GLU import *
from OpenGL.GLUT import *
import math
import time
h = 0
m = 0
s = 0
def Draw():
PI = 3.1415926
R = 0.5
TR = R - 0.05
glClear(GL_COLOR_BUFFER_BIT)
glLineWidth(5)
glBegin(GL_LINE_LOOP)
for i in range(100):
glVertex2f(R*math.cos(2*PI/100*i), R*math.sin(2*PI/100*i))
glEnd()
glLineWidth(2)
for i in range(100):
glBegin(GL_LINES)
glVertex2f(TR*math.sin(2*PI/12*i), TR*math.cos(2*PI/12*i))
glVertex2f(R*math.sin(2*PI/12*i), R*math.cos(2*PI/12*i))
glEnd()
glLineWidth(1)
h_Length = 0.2
m_Length = 0.3
s_Length = 0.4
count = 60.0
s_Angle = s/count
count *= 60
m_Angle = (m*60+s)/count
count *= 12
h_Angle = (h*60*60+m*60+s)/count
glLineWidth(1)
glBegin(GL_LINES)
glVertex2f(0.0, 0.0)
glVertex2f(s_Length*math.sin(2*PI*s_Angle), s_Length*math.cos(2*PI*s_Angle))
glEnd()
glLineWidth(5)
glBegin(GL_LINES)
glVertex2f(0.0, 0.0)
glVertex2f(h_Length*math.sin(2*PI*h_Angle), h_Length*math.cos(2*PI*h_Angle))
glEnd()
glLineWidth(3)
glBegin(GL_LINES)
glVertex2f(0.0, 0.0)
glVertex2f(m_Length*math.sin(2*PI*m_Angle), m_Length*math.cos(2*PI*m_Angle))
glEnd()
glLineWidth(1)
glBegin(GL_POLYGON)
for i in range(100):
glVertex2f(0.03*math.cos(2*PI/100*i), 0.03*math.sin(2*PI/100*i));
glEnd()
glFlush()
def Update():
global h, m, s
t = time.localtime(time.time())
h = int(time.strftime('%H', t))
m = int(time.strftime('%M', t))
s = int(time.strftime('%S', t))
glutPostRedisplay()
glutInit()
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGBA)
glutInitWindowSize(400, 400)
glutCreateWindow("My clock")
glutDisplayFunc(Draw)
glutIdleFunc(Update)
glutMainLoop()
這裡有個容易忽略的細節:glutIdleFunc 掛的是 Update 而不是 Draw,Update 取完時間後呼叫 glutPostRedisplay() 才會觸發重繪,這樣才不會同一幀被畫很多次。