在pyOpenGL中绘制简单的正方形
我正在自学OpenGL,使用的是pyopengl,现在遇到一个问题,想要渲染一个简单的以原点为中心的2D正方形。每当我把数组的值设置为大于或等于1时,形状就会占满整个屏幕,感觉就像我只在看坐标轴的一个小部分。我试着参考NeHe的教程,改成pyopengl的版本,但我找不到我哪里出错了。
from OpenGL.GL import *
from OpenGL.GLU import *
from OpenGL.GLUT import *
def display():
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
glBegin(GL_QUADS)
glVertex3f(2,-2,0)
glVertex3f(2,2,0)
glVertex3f(-2,2,0)
glVertex3f(-2,-2,0)
glEnd()
glutSwapBuffers()
if __name__ == '__main__':
glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE | GLUT_DEPTH)
glutInitWindowSize(640,480)
glutCreateWindow("Hello World :'D")
glutDisplayFunc(display)
glutIdleFunc(display)
glutMainLoop()
2 个回答
3
你需要设置投影矩阵和视口。Python让我们可以用一点函数式编程的方法来更合理地完成这件事:
from OpenGL.GL import *
from OpenGL.GLU import *
from OpenGL.GLUT import *
def display(w, h):
aspect = float(w)/float(h)
glViewport(0, 0, w, h)
glMatrixMode(GL_PROJECTION)
glLoadIdentity()
glOrtho(-aspect * 5, aspect * 5, -5, 5, -1, 1)
glMatrixMode(GL_MODELVIEW);
glLoadIdentity()
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
glBegin(GL_QUADS)
glVertex3f(2,-2,0)
glVertex3f(2,2,0)
glVertex3f(-2,2,0)
glVertex3f(-2,-2,0)
glEnd()
glutSwapBuffers()
def reshape(w, h):
glutDisplayFunc(lambda: display(w, h))
glutPostRedisplay();
if __name__ == '__main__':
glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE | GLUT_DEPTH)
glutInitWindowSize(640,480)
glutCreateWindow("Hello World :'D")
glutReshapeFunc(reshape)
glutIdleFunc(glutPostRedisplay)
glutMainLoop()
0
试着设置一个非默认的投影矩阵:
def display():
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
glMatrixMode(GL_PROJECTION)
glLoadIdentity()
glOrtho( 0, 640, 0, 480, -10, 10)
glMatrixMode(GL_MODELVIEW)
glLoadIdentity()
...