I've uploaded a simple example of how to use OpenGL with PyGame. It's a listing from my forthcoming book, Beginning Game Development with Python and PyGame, and demonstrates how to initialize OpenGL, create a light and draw a simple 3D 'world'. It also shows how to use the camera matrix to create a simple 'fly-cam'.

To run it you will need PyOpenGL, which you can download from the website, or from the command line if you have Easy Install (type easy_install PyOpenGL). Use the cursor keys to look around, and the Q/A keys to move forward and back. You can also press Z and X to roll the camera.

Download simpleopengl.py

Here's a screenshot.

pyg3d

I'm impressed by the ease of using OpenGL with PyGame. It's a one liner to create an OpenGL display, and the OpenGL bindings work well. With good use of display lists or vertex arrays, performance can be on par with commercial games. To put it in perspective, you could render an entire 3D object in less time it takes to draw a simple 2D sprite. I hope people take advantage of it, because the 'casual games' market is huge right now, and Python could give developers a serious advantage in getting games to market quickly!

Update: I experimented with recording the demo using Fraps, which worked rather nicely - I may even consider buying it! I didn't realize it was recording audio though, or I may have chosen a different soundtrack (it recorded a portion of mp3 I was listening to). Hope nobody sues me. Here's the a video of the demo.
This blog post was posted to It's All Geek to Me on Monday June 4th, 2007 at 8:51PM
 

27 Responses to "OpenGL sample code for PyGame"

  • June 7th, 2007, 5:02 p.m.

    This is really great, thanks!

  • June 10th, 2007, 5:28 p.m.

    Will,
    Thanks for sharing this. Great coding. It gave me a huge leg up on understanding GL in PyGame and a great start on my (non-commercial) project.
    But you didn't include any GNU license... and I'd like to give credit where it's due.
    Also, did you write the matrix44 & vector3 classes? Very elegant and infinitely useful... they should be part of the standard library.
    (BTW If you are not the author, do you know who is? Again: credit due)

    So thanks again for the great code!
    rd

  • June 12th, 2007, 10:13 p.m.

    Well,I like to say thank you this gets me closer to understandig opengl. Since my compt refuses to let me play anymore it claims it cannot open the gl,weird ha, mohaa.os was before ME i SWITCH TO,WINDOWS XP HOME EDITION.MORE POWER TO YA SOON i SHALL PLAY AGAIN.

  • Jon
    October 12th, 2007, 11:08 p.m.

    Hi, I'm getting the following error, any ideas how to fix it. Thanks.

    Traceback (most recent call last):
    File "firstopengl.py", line 231, in
    run()
    File "firstopengl.py", line 225, in run
    map.render()
    File "firstopengl.py", line 133, in render
    cube.render()
    File "firstopengl.py", line 73, in render
    glColor( self.color )
    File "build/bdist.macosx-10.3-fat/egg/OpenGL/GL/exceptional.py", line 207, in glColor
    KeyError: 1

  • October 13th, 2007, 4:50 p.m.

    Hi Jon,

    Are you running the latest version of PyOpenGL?

    Try replacing the glColor line with the following:

    glColor( *self.color )

    Will

  • Jon
    October 13th, 2007, 6:22 p.m.

    Hi Will,

    Thanks Will that's fixed it. What was the cause of the error if you don't mind me asking ?

    BTW do you know when your book will be available in the UK ?

    Cheers
    Jon

  • October 13th, 2007, 9:30 p.m.

    I'm guessing that the version of PyOpenGL I was using expands Python sequences and calls an appropriate glColor*v function in C. The version you are using must require four separate values. If I'm right you could also do glColorv(self color), which is probably more efficient.

    The book should be out everywhere on the 24th, but Amazon.co.uk are showing the wrong date!

  • May 19th, 2008, 9:41 a.m.

    I'm getting this error trying to run "firstopengl":

    Traceback (most recent call last):
    File "/home/rudin/Skrivebord/python-bok/firstopengl.py", line 184, in
    run()
    File "/home/rudin/Skrivebord/python-bok/firstopengl.py", line 169, in run
    camera_matrix.translate += movement * time_passed_seconds
    File "/usr/lib/python2.5/site-packages/gameobjects/vector3.py", line 247, in __radd__
    ox, oy, oz = lhs
    ValueError: too many values to unpack

    petzolt@online.no

  • August 22nd, 2008, 6:43 a.m.

    I’m guessing that the version of PyOpenGL I was using expands Python sequences and calls an appropriate glColor*v function in C. The version you are using must require four separate values. If I’m right you could also do glColorv(self color), which is probably more efficient.

  • Ryan
    April 26th, 2009, 4:40 a.m.

    When I run the demo under Ubuntu 8.10 it works great, but under Vista and OSX all the cubes are black. Any ideas?

  • April 26th, 2009, 2:11 p.m.

    Hi Ryan, I reproduced the black cubes issue on Ubuntu by upgrading OpenGL to the latest version (3.0.0c1) via easy_install.

    It seems that in the latest version, glColor wont accept colours as an iterable of 3 value and requires 3 distinct value. Fortunately the fix is easy, just insert an asterisk to unpack the color.

    So the start of the Cube's render method should look like this:

        def render(self):

    glColor( *self.color )
  • Adam
    April 28th, 2009, 5:14 p.m.

    I've just updated from Ubuntu 8.10 to 9.04 and it seems to have broken something. It doesn't crash, but does seem to compress all the cubes into a single flat panel. I am now using pygame to 1.8.1 and pyopengl to 3.0.0b6-3.

    Any idea what could have caused it? Other pygame opengl things seem to work fine (e.g. pygame NeHe samples).

  • Ryan
    April 29th, 2009, 1:39 a.m.

    I just had the same problem.

  • Adam
    April 29th, 2009, 3:15 p.m.

    It seems as though this is a python 2.5 vs 2.6 problem. Explicitly using “python2.5” instead of “python” seems to solve it.

  • Adam
    April 29th, 2009, 3:17 p.m.

    This may be a Python 2.6 vs Python 2.5 problem. Explicitly using “Python2.5” to execute it works fine, but “Python” (which defaults to 2.6 on Ubuntu 9.04) doesnt. Of course, it could be different libraries for different python versions too.

  • June 1st, 2009, 5:20 a.m.

    Just so you're aware, this example is broken in the last two versions of PyOpenGL for Windows (3.0.0c1 and 3.0.0). All polygons get rendered black.

  • June 1st, 2009, 9:11 a.m.

    gnatinator, See this reply [willmcgugan.com] for a solution

  • joC
    January 17th, 2010, 6:55 a.m.

    Hi Will, thanks for the book. I'm having lots of fun.

    Get this error when I try to run firstopengl.py. (Running Ubuntu 9.04):

    jo@tux:~/pygameBook/Chapter09$ python firstopengl.py

    get fences failed: -1

    param: 6, val: 0

    Traceback (most recent call last):

    File “firstopengl.py”, line 237, in <module>

    run()

    File “firstopengl.py”, line 230, in run

    map.render()

    File “firstopengl.py”, line 141, in render

    cube.render()

    File “firstopengl.py”, line 94, in render

    glVertex( vertices )

    File “/usr/lib/python2.6/dist-packages/OpenGL/GL/exceptional.py”, line 133, in glVertex

    return glVertexDispatch( args )

    ctypes.ArgumentError: argument 1: <type ‘exceptions.TypeError’>: byref() argument must be a ctypes instance, not ‘tuple’

    I've added the * to the start of the Cube render method, but get the same error, so it's not related to that.

    Any clues?

  • joC
    January 17th, 2010, 6:57 a.m.

    Well, the rendering of that error message is abysmal! Sorry about that.

    I'm sure you'll get the drift.

  • pelle
    November 16th, 2010, 10:43 p.m.

    joC, I found this page after googling for that exact error message. The solution I found (and that was pure trial and error; I have no idea what I am doing) was to change the four calls to glVertex to glVertex3dv.

    I'm using python 2.5.2

    OpenGL.__version__ ‘3.0.0b6’

  • Manuel
    March 19th, 2011, 5:30 p.m.

    Thank you very much for this useful example!

    Did you spend a thought on how to avoid upcoming deprecation issues when using glBegin and glVertex in pyOpenGL 3.1?

    I have no idea what to use else.

  • March 26th, 2011, 10:05 a.m.

    Using Ubuntu 10.10, Python 2.6.6, I get yet another odd problem. The entire “PyGame” part is coloured green, as is a wee bit of the “face”. The rest is coloured a light skin tone. Why's this?

    Screenshot: http://i54.tinypic.com/2h7p0er.jpg [i54.tinypic.com]

  • Adam
    December 11th, 2011, 4:46 p.m.

    Hi! On ubuntu 11.10 with python 2.7.2, I got the green cubes problem, as mentioned earlier. To solve it I moved the glColor( *self.color ) command between the glBegin-glEnd statements. It seems to me, that this is an OpenGl library bug.

  • Bill Nye
    March 3rd, 2012, 4:54 a.m.

    W = Move Forward
    A = Move Left
    S = Move Backward
    D = Move Right
    Q = Strafe Left
    E = Strafe Right
    Mouse = Move Camera
    ESC = Quit (the only one you got right)

    Havent you ever actually PLAYED a video game before?

  • November 10th, 2012, 4:15 p.m.

    can somebody solve this code to me?
    (i never used pyOpenGL before)
    (sorry my bad English )

  • ORyan
    February 19th, 2014, 2:52 a.m.

    The link to your demo is down. Getting 404. Is it still available?

  • February 25th, 2014, 12:36 p.m.

    @ORyan It's back up!

Leave a Comment

You can use bbcode in the comment: e.g. [b]This is bold[/b], [url]http://www.willmcgugan.com[/url], [code python]import this[/code]
Preview Posting...
Previewing comment, please wait a moment...

My Tweets

Will McGugan

My name is Will McGugan. I am an unabashed geek, an author, a hacker and a Python expert – amongst other things!

Search for Posts
Possibly related posts
Tags
Popular Tags
 
Archives
2013
 
Recent Comments
Great! All other image slideshow with kenburn effect use my processor(i5-2400) in firefox(and only in ff) on 100%. But with ...
Would be great to get this on GitHub. I could see using it in multiple places and you should get ...
Would be great to get this on GitHub. I could see using it in multiple places and you should get ...
Classic Roy
- Oriol on ChessPy
Hi how much money is the book and does it say how u publish it
 
© 2008 Will McGugan.

A technoblog blog, design by Will McGugan