Trying to Graph a Simple Square in pyOpenGL

a 夏天 提交于 2019-12-10 20:49:02

问题


I'm trying to teach myself OpenGL using pyopengl and I'm struck on trying to render a simple 2D square centered at the origin. Whenever I set an array value greater than or equal to 1, the shape takes up the entire screen as if I am only viewing a small section of the axis. I have tried to base it off the NeHe tutorials rewritten in pyopengl but I can't find what I'm doing wrong.

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()

回答1:


Try setting a non-default projection matrix:

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()

    ...



回答2:


You need to set the projection matrix and the viewport. Python allows us to use a little bit functional programming to do it the sane way:

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()


来源:https://stackoverflow.com/questions/6378297/trying-to-graph-a-simple-square-in-pyopengl

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!