Search code examples
c++openglgraphicsrenderingassimp

OpenGL texture not rendered properly on model


In my opengl application, texture is not rendered correctly on the model.

Here is a screenshot of the result:

Here is what the bunny should look like: expected result

Here is the code to load the texture.

stbi_set_flip_vertically_on_load(1); 
m_LocalBuffer = stbi_load(path.c_str(), &m_Width, &m_Height, &m_BPP, 0); 

GLCall(glGenTextures(1, &m_RendererID));
GLCall(glBindTexture(GL_TEXTURE_2D, m_RendererID));
GLCall(glGenerateMipmap(GL_TEXTURE_2D));
GLenum format = GL_RGBA;

//..switching on m_BPP to set format, omitted here

GLCall(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR));
GLCall(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR));
GLCall(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE));
GLCall(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE));

GLCall(glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, m_Width, m_Height, 0, format, GL_UNSIGNED_BYTE, m_LocalBuffer));

GLCall(glBindTexture(GL_TEXTURE_2D, 0));

if (m_LocalBuffer) {
    stbi_image_free(m_LocalBuffer);
}

Here is the texture file I'm using Texture File

I downloaded the asset from https://blenderartists.org/t/uv-unwrapped-stanford-bunny-happy-spring-equinox/1101297 (the 3.3Mb link)

Here is the code where I read in the texCoords

for (size_t i = 0; i < mesh->mNumVertices; i++) {
    //..read in positions and normals

    if (mesh->mTextureCoords[0]) {
        vertex.TexCoords.x = mesh->mTextureCoords[0][i].x;
        vertex.TexCoords.y = mesh->mTextureCoords[0][i].y;
    }        
} 

I'm loading the model as an obj file using assimp. I just read the texture coord from the result and pass it to the shader. (GLCall is just a debug macro I have in the renderer)

What could potentially be the cause for this? Let me know if more info is needed. Thanks a lot!


Solution

  • The image seems to be flipped vertically (around the x-axis). To compensated that, you've to flip the image manually, after loading it. Or if you've flipped the image then you've to omit that. Whether the image has to be flipped or not, depends on the image format.