基于这个问题:OpenGL中绘制矩形纹理,讨论了在PyGame中对一个OpenGL矩形进行纹理映射~
以下是一些绘制到"屏幕外"PyGame表面的代码。在每次主循环迭代时,该表面会被转换为OpenGL纹理映射。然后将此纹理映射映射到填充屏幕的矩形上。
代码是一个相当简单的示例,也许你需要稍微优化一下。
import pygame
import sys
from OpenGL.GL import *
from pygame.locals import *
pygame.init()
pygame.display.set_mode((500, 500), OPENGL | DOUBLEBUF)
pygame.display.init()
info = pygame.display.Info()
MIDNIGHT = ( 15, 0, 100 )
BUTTER = ( 255, 245, 100 )
glViewport(0, 0, info.current_w, info.current_h)
glDepthRange(0, 1)
glMatrixMode(GL_PROJECTION)
glMatrixMode(GL_MODELVIEW)
glLoadIdentity()
glShadeModel(GL_SMOOTH)
glClearColor(0.0, 0.0, 0.0, 0.0)
glClearDepth(1.0)
glDisable(GL_DEPTH_TEST)
glDisable(GL_LIGHTING)
glDepthFunc(GL_LEQUAL)
glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST)
glEnable(GL_BLEND)
texID = glGenTextures(1)
def surfaceToTexture( pygame_surface ):
global texID
rgb_surface = pygame.image.tostring( pygame_surface, 'RGB')
glBindTexture(GL_TEXTURE_2D, texID)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP)
surface_rect = pygame_surface.get_rect()
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, surface_rect.width, surface_rect.height, 0, GL_RGB, GL_UNSIGNED_BYTE, rgb_surface)
glGenerateMipmap(GL_TEXTURE_2D)
glBindTexture(GL_TEXTURE_2D, 0)
clock = pygame.time.Clock()
offscreen_surface = pygame.Surface((info.current_w, info.current_h))
text_font = pygame.font.Font( None, 30 )
done = False
while not done:
for event in pygame.event.get():
if event.type == QUIT:
done = True
offscreen_surface.fill( MIDNIGHT )
words = text_font.render( "β-Moé-Moé count: "+str( pygame.time.get_ticks() ), True, BUTTER )
offscreen_surface.blit( words, (50, 250) )
glClear(GL_COLOR_BUFFER_BIT)
glLoadIdentity()
glDisable(GL_LIGHTING)
glEnable(GL_TEXTURE_2D)
surfaceToTexture( offscreen_surface )
glBindTexture(GL_TEXTURE_2D, texID)
glBegin(GL_QUADS)
glTexCoord2f(0, 0); glVertex2f(-1, 1)
glTexCoord2f(0, 1); glVertex2f(-1, -1)
glTexCoord2f(1, 1); glVertex2f(1, -1)
glTexCoord2f(1, 0); glVertex2f(1, 1)
glEnd()
pygame.display.flip()
clock.tick(60)
pygame.quit()