我有一个使用OpenGL绘制立方体的程序,我想给立方体添加纹理。我正在学习this教程,我的纹理加载代码几乎是从那里复制的。每当我调用load_texture()
时,之后的任何OpenGL调用似乎都失败了,没有任何错误被抛出。是否有任何已知的问题可能导致枕头和OpenGL在一起工作时行为异常?我能找到的大多数教程都使用枕头,所以我认为必须有一个变通办法。
下面是我的纹理加载代码:
from OpenGL.GL import *
import gl_debugging as debug
from PIL import Image
# loads a texture from an image file into VRAM
def load_texture(texture_path):
# open the image file and convert to necessary formats
print("loading image", texture_path)
image = Image.open(texture_path)
convert = image.convert("RGBA")
image_data = image.transpose(Image.FLIP_TOP_BOTTOM ).tobytes()
w = image.width
h = image.height
image.close()
# create the texture in VRAM
texture = glGenTextures(1)
glBindTexture(GL_TEXTURE_2D, texture)
# configure some texture settings
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT) # when you try to reference points beyond the edge of the texture, how should it behave?
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT) # in this case, repeat the texture data
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR) # when you zoom in, how should the new pixels be calculated?
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR) # when you zoom out, how should the existing pixels be combined?
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_BASE_LEVEL, 0);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, 0);
# load texture onto the GPU
glTexImage2D(
GL_TEXTURE_2D, # where to load texture data
0, # mipmap level
GL_RGBA8, # format to store data in
w, # image dimensions
h, #
0, # border thickness
GL_RGBA, # format data is provided in
GL_UNSIGNED_BYTE, # type to read data as
image_data) # data to load as texture
debug.check_gl_error()
# generate smaller versions of the texture to save time when its zoomed out
glGenerateMipmap(GL_TEXTURE_2D)
# clean up afterwards
glBindTexture(GL_TEXTURE_2D, 0)
return texture
1条答案
按热度按时间1qczuiv01#
这段代码有一个问题,你需要从转换后的图像(
convert
)中获取字节,而不是从加载的图像(image
)中获取:image_data = image.transpose(Image.FLIP_TOP_BOTTOM).tobytes()
修改后,代码运行良好,我测试了它。