2013-02-16 68 views
2

我试过NeHE教程中的代码。 (http://nehe.gamedev.net/tutorial/texture_mapping/12038/) 我下载了linux版本的代码。 (http://codepad.org/ApAyiNuV) 它编译的代码没有问题,但是当我尝试运行我得到这个错误:我为什么会得到这个错误,我怎么能解决这个问题OpenGL中的纹理映射意外错误

Width of NeHe.bmp: 140204912410880 
Height of NeHe.bmp: 140204912410880 
Error allocating memory for color-corrected image data 

(我用gcc)

回答

1

您链接的代码中的主要问题与OpenGL无关,也不涉及加载图像。问题是,内容从文件加载的方式不可靠。这里是

// read the width 
if ((i = fread(&image->sizeX, 4, 1, file)) != 1) { 
printf("Error reading width from %s.\n", filename); 
return 0; 
} 

的问题,即sizeof(Image::sizeX)不是neccesarily 4 “字符”:拿这个举例来说。这种类型是unsigned long这是至少 4但它可以更长。在现代系统中很可能是8。这意味着,8个“字符”中的4个在读取之前就已经存在,这是通常关心的非零垃圾。

另外整个永久性问题没有解决。实现健壮的二进制加载的唯一方法是通过从明确定义的表达式中分配明确地设置所有位。在现场的情况下Image::sizeX你可以把它写成

char buf[4]; 
// read the width 
if ((i = fread(buf, 4, 1, file)) != 1) { 
printf("Error reading width from %s.\n", filename); 
return 0; 
} 
image->sizeX = 
    ((unsigned long)buf[0]) | 
    (((unsigned long)buf[1])<<8) | 
    (((unsigned long)buf[2])<<16)| 
    (((unsigned long)buf[3])<<24); 

写作这种方式是一个强大的和plattform独立的方式来读取二进制数据唯一方式。写作乏味吗?是的。这就是为什么你会写一些辅助函数来将它抽象出来。

+0

虽然这将通过使用第三方库来解决。无论如何,'+ 1'是真正的问题。 – 2013-02-16 20:15:36

+0

@BartekBanachewicz:确实使用经过良好测试的第三方库是推荐的方法。但指出实际问题是值得的。至于什么图书馆使用,意见不同。同样,在开发软件时,你会比以后遇到一种情况,那就是你必须自己编写一个二进制文件解析器,例如,如果你必须处理一些内部文件格式,而没有其他人使用。 – datenwolf 2013-02-16 21:06:52

3

Important: This way of loading textures is deprecated and does not work anymore with current versions of Visual Studio. The theory of this tutorial is still valid though. An update of the code which is responsible for loading the texture can be found here: http://nehe.gamedev.net/tutorial/lesson_06_texturing_update/47002/

我相信你使用的linux代码也是相当古老的。尝试切换到SOIL或其他图片加载库。更新后的代码也应该在linux上运行。