To main page | 3dengine.org

OpenGL and Cython


Important! You should have Mingw32 installed, see here.

Why?

I've seen 100 times increase in speed of GL code in Cython, vs raw PyOpenGL and all I needed to do is write Cython header for OpenGL functions, which alternatively can be found at PySoy's site (see below).

How

File: test.pyx
# Cython's openGL definitions (can be replaced with PySoy's)
cdef extern from "gl/gl.h":
    ctypedef int           GLint
    ctypedef unsigned int  GLenum
    int GL_POINTS
    cdef void glBegin(GLenum mode)
    cdef void glEnd()
    cdef void glVertex3f(GLfloat x, GLfloat y, GLfloat z)
# End of Cython's openGL definitions

cdef int i
cdef float x
glBegin(GL_POINTS)
for i in range(10000):
    x = i/1000
    glVertex3i(x,x,-x)
glEnd()
Try running the code above in Python (commenting out cdef's) and in Cython - you'll be amazed at Cython's GL speed (it's raw C).

Search google for "cdef void glVertex3i" (with quotes) and ye shall find PySoy's definitions for all functions.

File: setup.py
from distutils.core import setup 
from distutils.extension import Extension
from Pyrex.Distutils import build_ext
setup(
    name = "TestModule",
    ext_modules=[
        Extension("test", ["test.pyx"], libraries = ['opengl32'])
    ],
    cmdclass = {'build_ext': build_ext}
)
The key thing here is addition of libraries = ['opengl32']. Note that "libopengl32.a" should be in your "C:\MinGW\lib" path, and "gl.h" in "C:\MinGW\include\GL" (they are installed by default with Mingw32).

File: build.bat
python setup.py build_ext

Importing math

cdef extern from "math.h":
    float cosf(float theta)
    float sinf(float theta)
    float acosf(float theta)