This is the third post in a series of OpenGL “tutorials” explaining how to get a triangle on your screen using as few lines of code, in as many languages, and on as many platforms as possible.

In Python, your go to source for OpenGL setup is definitely PyOpenGL.  A simple straightforward wrapper around the C calls gives us virtually the same program we wrote for C.  Just copy the procedure calls into Python syntax, drop those pesky semicolons, and GLUT away!

from OpenGL.GLUT import *
from OpenGL.GLU import *
from OpenGL.GL import *
import sys

# To make this program work, you need the following library:
#       http://pyopengl.sourceforge.net/

def main():

    glutInit(sys.argv)
    glutInitDisplayMode(GLUT_RGBA | GLUT_DEPTH | GLUT_DOUBLE)
    glutInitWindowSize(500,500)
    glutInitWindowPosition(0,0)
    glutCreateWindow("Hello, GL!")

    glutDisplayFunc(draw)

    glutMainLoop()
    return

def draw():
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)

    glColor3f(1.0,1.0,1.0)
    glBegin(GL_TRIANGLES)
    glVertex3f(-0.5,-0.5,1.0)
    glVertex3f(-0.5,0.5,1.0)
    glVertex3f(0.5,-0.5,1.0)
    glEnd()

    glutSwapBuffers()
    return

if __name__ == "__main__":
    main()

What I like about Python + PyOpenGL:  It’s the same as C!  But, now we have automatic memory management and an even nicer syntax.  This program doesn’t really show off the difference in languages much, but some of the idioms employed actually make more sense in Python, like passing the function draw() as an argument to glutDisplayFunc().  In C this was an invocation of the infrequently used function pointer feature.  In Python, we get the (thankfully) far more pedestrian function as a value interpretation.

Advertisements