Sign in to follow this  
TooLSHeD

OpenGL Texture mapping problem.

Recommended Posts

Hi I've followed NeHe's lesson 31, but using SDL. The model loads and displays fine except for the texture, it's just white. I've gone through my code a million times and can't seem to find anything. Can anyone please just look at my code and see if you find anything? Thanks. Code is taken from NeHe's lesson 31 and gpwiki. Content of load_model_data(...):
 // Filesize in bytes.
    long fileSize;

    ifstream inputFile(filename, ios::in | ios::binary);
    if(inputFile.fail())
    {
        return(false);
    }

    // Get the file size.
    inputFile.seekg(0, ios::end);
    fileSize = inputFile.tellg();
    inputFile.seekg(0, ios::beg);

    // Read the file content into a temp buffer.
    byte *pBuffer = new byte[fileSize];
    inputFile.read(reinterpret_cast<char*>(pBuffer), fileSize);
    inputFile.close();

    // Create a pointer to point to a location in the buffer.
    const byte *pPtr = pBuffer;
    MS3DHeader *pHeader = (MS3DHeader*)pPtr;        // Get the header information.
    pPtr += sizeof(MS3DHeader);                 // Move along.

    if(strncmp(pHeader->m_ID, "MS3D000000", 10) != 0)
    {
        return(false);      // Not a valid Milkshape 3D file.
    }

    if(pHeader->m_version < 3 || pHeader->m_version > 4)
    {
        return(false);      // Wrong version.
    }

    int nVertices = *(word*)pPtr;
    m_numVertices = nVertices;
    m_pVertices = new Vertex[nVertices];
    pPtr += sizeof(word);

    //printf("%i\n", pHeader->m_version);
    printf("nVertices = %i\n", m_numVertices);

    for(int i = 0; i < nVertices; i++)
    {
        MS3DVertex *pVertex = (MS3DVertex*)pPtr;
        m_pVertices[i].m_boneID = pVertex->m_boneID;
        memcpy(m_pVertices[i].m_location, pVertex->m_vertex, sizeof(float)*3);
        pPtr += sizeof(MS3DVertex);
    }
    
    int nTriangles = *(word*)pPtr;
    m_numTriangles = nTriangles;
    m_pTriangles = new Triangle[nTriangles];
    pPtr += sizeof(word);

    for(int i = 0; i < nTriangles; i++)
    {
        MS3DTriangle *pTriangle = (MS3DTriangle*)pPtr;
        int vertexIndices[3] = {pTriangle->m_vertexIndices[0], pTriangle->m_vertexIndices[1], pTriangle->m_vertexIndices[2]};
        float t[3] = {1.0f - pTriangle->m_t[0], 1.0f - pTriangle->m_t[1], 1.0f - pTriangle->m_t[2]};
        memcpy(m_pTriangles[i].m_vertexNormals, pTriangle->m_vertexNormals, sizeof(float)*3*3);
        memcpy(m_pTriangles[i].m_s, pTriangle->m_s, sizeof(float)*3);
        memcpy(m_pTriangles[i].m_t, t, sizeof(float)*3);
        memcpy(m_pTriangles[i].m_vertexIndices, vertexIndices, sizeof(int)*3);
        pPtr += sizeof(MS3DTriangle);
    }

    int nGroups = *(word*)pPtr;
    m_numMeshes = nGroups;
    m_pMeshes = new Mesh[nGroups];
    pPtr += sizeof(word);

    for(int i = 0; i < nGroups; i++)
    {
        pPtr += sizeof(byte);           // Flags.
        pPtr += 32;                     // Name.

        word nTriangles = *(word*)pPtr;
        pPtr += sizeof(word);
        int *pTriangleIndices = new int[nTriangles];
        for(int j = 0; j < nTriangles; j++)
        {
            pTriangleIndices[j] = *(word*)pPtr;
            pPtr += sizeof(word);
        }

        char materialIndex = *(char*)pPtr;
        pPtr += sizeof(char);

        m_pMeshes[i].m_materialIndex = materialIndex;
        m_pMeshes[i].m_numTriangles = nTriangles;
        m_pMeshes[i].m_pTriangleIndices = pTriangleIndices;
    }

    int nMaterials = *(word*)pPtr;
    m_numMaterials = nMaterials;
    m_pMaterials = new Material[nMaterials];
    pPtr += sizeof(word);

    for(int i = 0; i < nMaterials; i++)
    {
        MS3DMaterial *pMaterial = (MS3DMaterial*)pPtr;
        memcpy(m_pMaterials[i].m_ambient, pMaterial->m_ambient, sizeof(float)*4);
        memcpy(m_pMaterials[i].m_diffuse, pMaterial->m_diffuse, sizeof(float)*4);
        memcpy(m_pMaterials[i].m_specular, pMaterial->m_specular, sizeof(float)*4);
        memcpy(m_pMaterials[i].m_emissive, pMaterial->m_emissive, sizeof(float)*4);
        m_pMaterials[i].m_shininess = pMaterial->m_shininess;
        m_pMaterials[i].m_pTextureFilename = new char[strlen(pMaterial->m_texture + 1)];
        strcpy(m_pMaterials[i].m_pTextureFilename, pMaterial->m_texture);
        pPtr += sizeof(MS3DMaterial);

        // printf("%s %s",m_pMaterials[i].m_pTextureFilename, "\n");
    }

    reload_textures();

    delete[] pBuffer;

    return(true);

content of loadTexture(...):
    GLuint texture = 0;
    SDL_Surface *surface;         // SDL_Surface to temporarily hold the data.
    GLenum texture_format;
    GLint nColours;

    // OpenGL can only work with textures which both dimenstions
    // are a power of 2. So check.
    surface = NULL;
    printf("Goint to load the image...\n");
    surface = SDL_LoadBMP(filename);
    if(surface != NULL)
    {
        if((surface->w & (surface->w - 1)) != 0)
        {
            printf("Warning: image width is not a power of 2");
        }

        if((surface->h & (surface->h - 1)) != 0)
        {
            printf("Warning: image height is not a power of 2");
        }

        printf("bleh %i %i \n", surface->w, surface->h);

        // Get the nuber of channels in the SDL surface.
        nColours = surface->format->BytesPerPixel;
        if(nColours == 4)                         // Contains an alpha channel.
        {
            if(surface->format->Rmask == 0x000000ff)
            {
                texture_format = GL_RGBA;
            }
            else
            {
                texture_format = GL_BGRA;
            }
        }
        else if(nColours == 3)
        {
            if(surface->format->Rmask == 0x000000ff)
            {
                texture_format == GL_RGB;
            }
            else
            {
                texture_format == GL_BGR;
            }
        }
        else
        {
            printf("Warning: The image isn't true colour.");
        }

        // Let OpenGL generate a texture object handle for us.
        glGenTextures(1, &texture);

        // Bind the texture object.
        glBindTexture(GL_TEXTURE_2D, texture);

        // Transfer the image data from the SDL surface to the texture.
        glTexImage2D(GL_TEXTURE_2D, 0, nColours, surface->w, surface->h, 0,
                     texture_format, GL_UNSIGNED_BYTE, surface->pixels);

                // Set the texture's stretching properties.
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    }
    else
    {
        printf("SDL could not load the image.");
    }

    // Free the surface if it was successfully created.
    if(surface)
    {
        SDL_FreeSurface(surface);
    }

    return(texture);

Content of draw():
GLboolean texEnabled = glIsEnabled(GL_TEXTURE_2D);

    for(int i = 0; i < m_numMeshes; i++)
    {
        int materialIndex = m_pMeshes[i].m_materialIndex;
        if(materialIndex >= 0)
        {
            glMaterialfv(GL_FRONT, GL_AMBIENT, m_pMaterials[materialIndex].m_ambient);
            glMaterialfv(GL_FRONT, GL_DIFFUSE, m_pMaterials[materialIndex].m_diffuse);
            glMaterialfv(GL_FRONT, GL_SPECULAR, m_pMaterials[materialIndex].m_specular);
            glMaterialfv(GL_FRONT, GL_EMISSION, m_pMaterials[materialIndex].m_emissive);
            glMaterialf(GL_FRONT, GL_SHININESS, m_pMaterials[materialIndex].m_shininess);

            if (m_pMaterials[materialIndex].m_texture > 0)
            {
                glBindTexture(GL_TEXTURE_2D, m_pMaterials[materialIndex].m_texture);
                glEnable(GL_TEXTURE_2D);
                //std::printf("%i \n", m_pMaterials[materialIndex].m_texture);
            }
            else
            {
                glDisable(GL_TEXTURE_2D);
            }
        }
        else
        {
            glDisable(GL_TEXTURE_2D);
        }
        
        glBegin(GL_TRIANGLES);
        {
            for(int j = 0; j < m_pMeshes[i].m_numTriangles; j++)
            {
                int triangleIndex = m_pMeshes[i].m_pTriangleIndices[j];
                const Triangle* pTri = &m_pTriangles[triangleIndex];

                for(int k = 0; k < 3; k++)
                {
                    int index = pTri->m_vertexIndices[k];
                    
                    glNormal3fv(pTri->m_vertexNormals[k]);
                    glTexCoord2f(pTri->m_s[k], pTri->m_t[k]);
                    glVertex3fv(m_pVertices[index].m_location);
                }
            }
        }
        glEnd();
    }

    if(texEnabled)
    {
        glEnable(GL_TEXTURE_2D);
    }
    else
    {
        glDisable(GL_TEXTURE_2D);
    }

Share this post


Link to post
Share on other sites
You are doing too much at once. There's no way (for me) to be able to follow that spaghetti of glDisable(GL_TEXTURE_2D)/glEnable(GL_TEXTURE_2D)

Could you drop that material-whatever and the disables altogether?

So at least we'll have a clue that the texture is loaded correctly or not.

BTW do you enable texturing anywhere before the draw-stuff you posted? Texturing is disabled by default.

Share this post


Link to post
Share on other sites
OK, I've commented out the glDisable's and the material functions. Still no change. I think I'll quickly write a small program to check if the image loading function works properly.

I call glEnable(GL_TEXTURE_2D) once when initializing OpenGL.

Share this post


Link to post
Share on other sites
Yeah, maybe call glGetError() after the call to glTexImage2D()

Also, I'd bind after enabling texturing in draw():

glEnable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, m_pMaterials[materialIndex].m_texture);

Share this post


Link to post
Share on other sites
OK, I've figured it out. The problem is with this bit of code.


nColours = surface->format->BytesPerPixel;
if(nColours == 4) // Contains an alpha channel.
{
if(surface->format->Rmask == 0x000000ff)
{
texture_format = GL_RGBA;
printf("GL_RGBA");
}
else
{
texture_format = GL_BGRA;
printf("GL_BGRA");
}
}
else if(nColours == 3)
{
if(surface->format->Rmask == 0x000000ff)
{
texture_format == GL_RGB;
printf("GL_RGB");
}
else
{
texture_format == GL_BGR;
printf("GL_BGR");
}
}
else
{
printf("Warning: The image isn't true colour.");
}



The image colour format is RGB, for some reason it chooses GL_BGR...
When I hard code GL_RGB right before glTexImage2D() the texture displays, but it looks blue, like the red component isn't showing.

Share this post


Link to post
Share on other sites
It's not what you think.

format is always shown as RGB in Windows, but it's doesn't mean that the memory layout is rgb. It's more likely to be bgr.

I hope that makes sense.

So whatever the image returns as format, use that as internal format when creating the texture object. But that seems fine in your original code.

This seems suspicious:
if(surface->format->Rmask == 0x000000ff)

I think it's should be either
if(surface->format->Rmask & 0x000000ff == 0x000000ff)

or
if(surface->format->Rmask & 0x000000ff )
more likely the latter (I'm pretty sure)

Share this post


Link to post
Share on other sites
Hi, thanks, but it's more stupid than that.

When assigning the texture_format variable I used == instead of =, so the variable had junk in it. That's why I got the invalid enumerant error.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this  

  • Partner Spotlight

  • Forum Statistics

    • Total Topics
      627636
    • Total Posts
      2978331
  • Similar Content

    • By xhcao
      Before using void glBindImageTexture(    GLuint unit, GLuint texture, GLint level, GLboolean layered, GLint layer, GLenum access, GLenum format), does need to make sure that texture is completeness. 
    • By cebugdev
      hi guys, 
      are there any books, link online or any other resources that discusses on how to build special effects such as magic, lightning, etc. in OpenGL? i mean, yeah most of them are using particles but im looking for resources specifically on how to manipulate the particles to look like an effect that can be use for games,. i did fire particle before, and I want to learn how to do the other 'magic' as well.
      Like are there one book or link(cant find in google) that atleast featured how to make different particle effects in OpenGL (or DirectX)? If there is no one stop shop for it, maybe ill just look for some tips on how to make a particle engine that is flexible enough to enable me to design different effects/magic 
      let me know if you guys have recommendations.
      Thank you in advance!
    • By dud3
      How do we rotate the camera around x axis 360 degrees, without having the strange effect as in my video below? 
      Mine behaves exactly the same way spherical coordinates would, I'm using euler angles.
      Tried googling, but couldn't find a proper answer, guessing I don't know what exactly to google for, googled 'rotate 360 around x axis', got no proper answers.
       
      References:
      Code: https://pastebin.com/Hcshj3FQ
      The video shows the difference between blender and my rotation:
       
    • By Defend
      I've had a Google around for this but haven't yet found some solid advice. There is a lot of "it depends", but I'm not sure on what.
      My question is what's a good rule of thumb to follow when it comes to creating/using VBOs & VAOs? As in, when should I use multiple or when should I not? My understanding so far is that if I need a new VBO, then I need a new VAO. So when it comes to rendering multiple objects I can either:
      * make lots of VAO/VBO pairs and flip through them to render different objects, or
      * make one big VBO and jump around its memory to render different objects. 
      I also understand that if I need to render objects with different vertex attributes, then a new VAO is necessary in this case.
      If that "it depends" really is quite variable, what's best for a beginner with OpenGL, assuming that better approaches can be learnt later with better understanding?
       
    • By test opty
      Hello all,
       
      On my Windows 7 x64 machine I wrote the code below on VS 2017 and ran it.
      #include <glad/glad.h>  #include <GLFW/glfw3.h> #include <std_lib_facilities_4.h> using namespace std; void framebuffer_size_callback(GLFWwindow* window , int width, int height) {     glViewport(0, 0, width, height); } //****************************** void processInput(GLFWwindow* window) {     if (glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS)         glfwSetWindowShouldClose(window, true); } //********************************* int main() {     glfwInit();     glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);     glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);     glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);     //glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);     GLFWwindow* window = glfwCreateWindow(800, 600, "LearnOpenGL", nullptr, nullptr);     if (window == nullptr)     {         cout << "Failed to create GLFW window" << endl;         glfwTerminate();         return -1;     }     glfwMakeContextCurrent(window);     if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress))     {         cout << "Failed to initialize GLAD" << endl;         return -1;     }     glViewport(0, 0, 600, 480);     glfwSetFramebufferSizeCallback(window, framebuffer_size_callback);     glClearColor(0.2f, 0.3f, 0.3f, 1.0f);     glClear(GL_COLOR_BUFFER_BIT);     while (!glfwWindowShouldClose(window))     {         processInput(window);         glfwSwapBuffers(window);         glfwPollEvents();     }     glfwTerminate();     return 0; }  
      The result should be a fixed dark green-blueish color as the end of here. But the color of my window turns from black to green-blueish repeatedly in high speed! I thought it might be a problem with my Graphics card driver but I've updated it and it's: NVIDIA GeForce GTX 750 Ti.
      What is the problem and how to solve it please?
  • Popular Now