我正在使用Cocoa开发我的第一个OpenGL应用程序(我之前在iPhone上使用过OpenGL ES),但是我在从图像文件中加载纹理时遇到了一些问题。以下是我的纹理加载代码:
@interface MyOpenGLView : NSOpenGLView
{
GLenum texFormat[ 1 ]; // Format of texture (GL_RGB, GL_RGBA)
NSSize texSize[ 1 ]; // Width and height
GLuint textures[1]; // Storage for one texture
}
- (BOOL) loadBitmap:(NSString *)filename intoIndex:(int)texIndex
{
BOOL success = FALSE;
NSBitmapImageRep *theImage;
int bitsPPixel, bytesPRow;
unsigned char *theImageData;
NSData* imgData = [NSData dataWithContentsOfFile:filename options:NSUncachedRead error:nil];
theImage = [NSBitmapImageRep imageRepWithData:imgData];
if( theImage != nil )
{
bitsPPixel = [theImage bitsPerPixel];
bytesPRow = [theImage bytesPerRow];
if( bitsPPixel == 24 ) // No alpha channel
texFormat[texIndex] = GL_RGB;
else if( bitsPPixel == 32 ) // There is an alpha channel
texFormat[texIndex] = GL_RGBA;
texSize[texIndex].width = [theImage pixelsWide];
texSize[texIndex].height = [theImage pixelsHigh];
if( theImageData != NULL )
{
NSLog(@"Good so far...");
success = TRUE;
// Create the texture
glGenTextures(1, &textures[texIndex]);
NSLog(@"tex: %i", textures[texIndex]);
NSLog(@"%i", glIsTexture(textures[texIndex]));
glPixelStorei(GL_UNPACK_ROW_LENGTH, [theImage pixelsWide]);
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
// Typical texture generation using data from the bitmap
glBindTexture(GL_TEXTURE_2D, textures[texIndex]);
NSLog(@"%i", glIsTexture(textures[texIndex]));
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, texSize[texIndex].width, texSize[texIndex].height, 0, texFormat[texIndex], GL_UNSIGNED_BYTE, [theImage bitmapData]);
NSLog(@"%i", glIsTexture(textures[texIndex]));
}
}
return success;
}
看起来 glGenTextures() 函数实际上并没有创建纹理,因为 textures[0] 的值仍为 0。此外,记录 glIsTexture(textures[texIndex]) 总是返回 false。
有什么建议吗?
谢谢, Kyle
GLuint textures[1]
(我更新了我的帖子以包括头文件定义)。在调用glBindTexture()
之后,我还检查了glIsTexture()
,它仍然返回false。它也没有在glBegin()
和glEnd()
之间调用,它是在计时器启动之前的初始化方法中调用的。该纹理是一个256x256的PNG文件。 - Kyle