Sign in to follow this  
TooLSHeD

OpenGL Texture mapping problem.

Recommended Posts

TooLSHeD    122
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
szecs    2990
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
TooLSHeD    122
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
rethan    149
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
TooLSHeD    122
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
szecs    2990
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
TooLSHeD    122
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  

  • Similar Content

    • By Kjell Andersson
      I'm trying to get some legacy OpenGL code to run with a shader pipeline,
      The legacy code uses glVertexPointer(), glColorPointer(), glNormalPointer() and glTexCoordPointer() to supply the vertex information.
      I know that it should be using setVertexAttribPointer() etc to clearly define the layout but that is not an option right now since the legacy code can't be modified to that extent.
      I've got a version 330 vertex shader to somewhat work:
      #version 330 uniform mat4 osg_ModelViewProjectionMatrix; uniform mat4 osg_ModelViewMatrix; layout(location = 0) in vec4 Vertex; layout(location = 2) in vec4 Normal; // Velocity layout(location = 3) in vec3 TexCoord; // TODO: is this the right layout location? out VertexData { vec4 color; vec3 velocity; float size; } VertexOut; void main(void) { vec4 p0 = Vertex; vec4 p1 = Vertex + vec4(Normal.x, Normal.y, Normal.z, 0.0f); vec3 velocity = (osg_ModelViewProjectionMatrix * p1 - osg_ModelViewProjectionMatrix * p0).xyz; VertexOut.velocity = velocity; VertexOut.size = TexCoord.y; gl_Position = osg_ModelViewMatrix * Vertex; } What works is the Vertex and Normal information that the legacy C++ OpenGL code seem to provide in layout location 0 and 2. This is fine.
      What I'm not getting to work is the TexCoord information that is supplied by a glTexCoordPointer() call in C++.
      Question:
      What layout location is the old standard pipeline using for glTexCoordPointer()? Or is this undefined?
       
      Side note: I'm trying to get an OpenSceneGraph 3.4.0 particle system to use custom vertex, geometry and fragment shaders for rendering the particles.
    • By markshaw001
      Hi i am new to this forum  i wanted to ask for help from all of you i want to generate real time terrain using a 32 bit heightmap i am good at c++ and have started learning Opengl as i am very interested in making landscapes in opengl i have looked around the internet for help about this topic but i am not getting the hang of the concepts and what they are doing can some here suggests me some good resources for making terrain engine please for example like tutorials,books etc so that i can understand the whole concept of terrain generation.
       
    • By KarimIO
      Hey guys. I'm trying to get my application to work on my Nvidia GTX 970 desktop. It currently works on my Intel HD 3000 laptop, but on the desktop, every bind textures specifically from framebuffers, I get half a second of lag. This is done 4 times as I have three RGBA textures and one depth 32F buffer. I tried to use debugging software for the first time - RenderDoc only shows SwapBuffers() and no OGL calls, while Nvidia Nsight crashes upon execution, so neither are helpful. Without binding it runs regularly. This does not happen with non-framebuffer binds.
      GLFramebuffer::GLFramebuffer(FramebufferCreateInfo createInfo) { glGenFramebuffers(1, &fbo); glBindFramebuffer(GL_FRAMEBUFFER, fbo); textures = new GLuint[createInfo.numColorTargets]; glGenTextures(createInfo.numColorTargets, textures); GLenum *DrawBuffers = new GLenum[createInfo.numColorTargets]; for (uint32_t i = 0; i < createInfo.numColorTargets; i++) { glBindTexture(GL_TEXTURE_2D, textures[i]); GLint internalFormat; GLenum format; TranslateFormats(createInfo.colorFormats[i], format, internalFormat); // returns GL_RGBA and GL_RGBA glTexImage2D(GL_TEXTURE_2D, 0, internalFormat, createInfo.width, createInfo.height, 0, format, GL_FLOAT, 0); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); DrawBuffers[i] = GL_COLOR_ATTACHMENT0 + i; glBindTexture(GL_TEXTURE_2D, 0); glFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 + i, textures[i], 0); } if (createInfo.depthFormat != FORMAT_DEPTH_NONE) { GLenum depthFormat; switch (createInfo.depthFormat) { case FORMAT_DEPTH_16: depthFormat = GL_DEPTH_COMPONENT16; break; case FORMAT_DEPTH_24: depthFormat = GL_DEPTH_COMPONENT24; break; case FORMAT_DEPTH_32: depthFormat = GL_DEPTH_COMPONENT32; break; case FORMAT_DEPTH_24_STENCIL_8: depthFormat = GL_DEPTH24_STENCIL8; break; case FORMAT_DEPTH_32_STENCIL_8: depthFormat = GL_DEPTH32F_STENCIL8; break; } glGenTextures(1, &depthrenderbuffer); glBindTexture(GL_TEXTURE_2D, depthrenderbuffer); glTexImage2D(GL_TEXTURE_2D, 0, depthFormat, createInfo.width, createInfo.height, 0, GL_DEPTH_COMPONENT, GL_FLOAT, 0); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glBindTexture(GL_TEXTURE_2D, 0); glFramebufferTexture(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, depthrenderbuffer, 0); } if (createInfo.numColorTargets > 0) glDrawBuffers(createInfo.numColorTargets, DrawBuffers); else glDrawBuffer(GL_NONE); if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) std::cout << "Framebuffer Incomplete\n"; glBindFramebuffer(GL_FRAMEBUFFER, 0); width = createInfo.width; height = createInfo.height; } // ... // FBO Creation FramebufferCreateInfo gbufferCI; gbufferCI.colorFormats = gbufferCFs.data(); gbufferCI.depthFormat = FORMAT_DEPTH_32; gbufferCI.numColorTargets = gbufferCFs.size(); gbufferCI.width = engine.settings.resolutionX; gbufferCI.height = engine.settings.resolutionY; gbufferCI.renderPass = nullptr; gbuffer = graphicsWrapper->CreateFramebuffer(gbufferCI); // Bind glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fbo); // Draw here... // Bind to textures glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, textures[0]); glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, textures[1]); glActiveTexture(GL_TEXTURE2); glBindTexture(GL_TEXTURE_2D, textures[2]); glActiveTexture(GL_TEXTURE3); glBindTexture(GL_TEXTURE_2D, depthrenderbuffer); Here is an extract of my code. I can't think of anything else to include. I've really been butting my head into a wall trying to think of a reason but I can think of none and all my research yields nothing. Thanks in advance!
    • By Adrianensis
      Hi everyone, I've shared my 2D Game Engine source code. It's the result of 4 years working on it (and I still continue improving features ) and I want to share with the community. You can see some videos on youtube and some demo gifs on my twitter account.
      This Engine has been developed as End-of-Degree Project and it is coded in Javascript, WebGL and GLSL. The engine is written from scratch.
      This is not a professional engine but it's for learning purposes, so anyone can review the code an learn basis about graphics, physics or game engine architecture. Source code on this GitHub repository.
      I'm available for a good conversation about Game Engine / Graphics Programming
    • By C0dR
      I would like to introduce the first version of my physically based camera rendering library, written in C++, called PhysiCam.
      Physicam is an open source OpenGL C++ library, which provides physically based camera rendering and parameters. It is based on OpenGL and designed to be used as either static library or dynamic library and can be integrated in existing applications.
       
      The following features are implemented:
      Physically based sensor and focal length calculation Autoexposure Manual exposure Lense distortion Bloom (influenced by ISO, Shutter Speed, Sensor type etc.) Bokeh (influenced by Aperture, Sensor type and focal length) Tonemapping  
      You can find the repository at https://github.com/0x2A/physicam
       
      I would be happy about feedback, suggestions or contributions.

  • Popular Now