[Author Prev][Author Next][Thread Prev][Thread Next][Author Index][Thread Index]

Re: [pygame] getting setup to use PyOpenGL for 2D



Matt Bailey wrote:

Speaking of which....anyone got a barebones sample of how to get an OpenGL-ready object from an image file using pygame.image? I'm using PIL right now but only because the only examples I could find used it.

OpenGL is C based state machine (and not object orientated), so I'm not exactly sure what you mean.... I'm guessing you want to convert your file into a texture for use by OpenGL, and have provided a stripped down version of what I use to do this. This example assumes your image's size is a power of 2; you could probably also strip all the glTexParameteri() calls and just accept defaults.


import pygame from OpenGL.GL import *

surf          = pygame.image.load( filePath )
imageStr      = pygame.image.tostring( surf, 'RGBA', 0 )
width, height = surface.get_size()
textureId     = glGenTextures()

glBindTexture( GL_TEXTURE_2D, textureId )
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT )
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT )
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST )
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST )
glTexImage2D( GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, imageStr )



This sets up the image as a texture inside of OpenGL. As needed you can use this by telling OpenGL to set it's current texture:


glBindTexture( GL_TEXTURE_2D, textureId )

Alternately you can free the associated resources:

glDeleteTextures( textureId )


-Jasper