2012-04-24 45 views
1

我在使用类的OpenGL GLUT项目中尝试加载纹理时遇到了问题。 下面是一些包含纹理填充的代码:纹理不会出现 - GLUT OpenGL

从模型类的子类中声明纹理模型。 TextureModel亚类的

TextureModel * title = new TextureModel("Box.obj", "title.raw");

构造方法:

TextureModel(string fName, string tName) : Model(fName), textureFile(tName) 
{ 
    material newMat = {{0.63,0.52,0.1,1.0},{0.63,0.52,0.1,1.0},{0.2,0.2,0.05,0.5},10}; 
    Material = newMat; 
    // enable texturing 
    glEnable(GL_TEXTURE_2D); 

    loadcolTexture(textureFile); 
    glGenTextures(1, &textureRef); 
    // specify the filtering method 
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); 
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); 
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); 
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); 
    // associate the image read in to the texture to be applied 
    gluBuild2DMipmaps(GL_TEXTURE_2D, 3, 256, 256, GL_RGB, GL_UNSIGNED_BYTE, image_array); 
} 

纹理加载功能在RAW文件中的数据如下:

int loadcolTexture(const string fileName) { 
ifstream inFile; 
inFile.open(fileName.c_str(), ios::binary); 

if (!inFile.good()) 
{ 
    cerr << "Can't open texture file " << fileName << endl; 
    return 1; 
} 
inFile.seekg (0, ios::end); 
int size = inFile.tellg(); 
image_array = new char [size]; 
inFile.seekg (0, ios::beg); 
inFile.read (image_array, size); 
inFile.close(); 
return 0;} 

方法绘制三角形:

virtual void drawTriangle(int f1, int f2, int f3, int t1, int t2, int t3, int n1, int n2, int n3) 
{ 
    glColor3f(1.0,1.0,1.0); 
    glBegin(GL_TRIANGLES); 
    glBindTexture(GL_TEXTURE_2D, textureRef); 
    glNormal3fv(&normals[n1].x); 
    glTexCoord2f(textures[t1].u, textures[t1].v); 
    glVertex3fv(&Model::vertices[f1].x); 

    glNormal3fv(&normals[n2].x); 
    glTexCoord2f(textures[t2].u, textures[t2].v); 
    glVertex3fv(&Model::vertices[f2].x); 

    glNormal3fv(&normals[n3].x); 
    glTexCoord2f(textures[t3].u, textures[t3].v); 
    glVertex3fv(&Model::vertices[f3].x); 
    glEnd(); 
} 

我也有照明,深度测试和双缓冲启用。

模型和照明工作正常,但纹理不显示。任何它不起作用的原因都会很好。

+1

你至少错过了'TextureModel'构造函数中'glBindTexture'的调用。 – user786653 2012-04-24 16:59:57

回答

2

要添加到评论,我在这里看到几件事情:

  1. 正如评论所说,你需要绑定一个纹理,你可以上传数据之前。一旦用glGenTextures生成纹理,在尝试加载数据或设置设置参数之前,需要将其设置为活动纹理。glTexParameteri

  2. 您正在构建mipmap但未使用它们。或者将GL_TEXTURE_MIN_FILTER设置为GL_NEAREST_MIPMAP_LINEAR以使用mipmap,或者不要首先构建它们。因为你只是在浪费纹理记忆。

  3. 如在drawTriangle中所做的那样,绑定glBegin/glEnd之间的纹理是不合法的。把它绑在glBegin之前。

  4. 开始在代码中使用glGetError。这会告诉你,如果你在做错事情之前你必须要来找出你的错误。 (如果你一直在使用它,你会在这里发现2/3的错误)。