A Loading and Rendering 3D Models with OpenGL and PyGame

 

Beyond chapter 3, when we start writing programs that transform and animate graphics, I begin to use OpenGL and PyGame instead of Matplotlib.  This appendix gives an overview of how to set up a game loop in PyGame and render 3D models in successive frames.  The culmination is an implementation of a draw_model function, which renders a single image of a 3D model like the teapot we use in chapter 4. 

The goal of draw_model is to encapsulate the library-specific work, so you don’t have to spend a lot of time wrestling with OpenGL.  But, if you want to understand how the function works, feel free to follow along with this appendix, and play with the code yourself.  Let’s start with our octahedron from chapter 3 and recreate it with PyOpenGL and PyGame.

A.1   Recreating the octahedron from Chapter 3

The first step to get working with the PyOpenGL and PyGame libraries is to install them.  I recommend using pip, as follows:

> pip install PyGame
 > pip install PyOpenGL

The first thing I’ll show you is how to use these libraries to recreate work we’ve already done: rendering a simple 3D object. 

In a new Python file called octahedron.py, we start with a bunch of imports.  The first few come from the two new libraries, and the rest should be familiar from chapter 3.  In particular, we’ll continue to use all of the 3D vector arithmetic functions we’ve already built, organized in the file vectors.py in the source code.

A.2   Changing our perspective

A.3   Loading and rendering the Utah teapot

A.4   Exercises

sitemap