1

I have a class for creating textures from a path but when i try to load in a texture with 3 channels (rgb) it gives me read access violation exception when running this line

glTextureSubImage2D(m_RendererID, 0, 0, 0, m_Width, m_Height, m_DataFormat, GL_UNSIGNED_BYTE, data);

I tried to change the parameters in the stbi load function but that didn't work.

When i load the image it sets the correct width, height and channel data so i don't know what i am doing wrong

The pointer to the data isn't nullptr either

OpenGLTexture2D::OpenGLTexture2D(const std::string& path)
    {
        RADIANT_PROFILE_FUNCTION();

        m_Path = path;

        stbi_set_flip_vertically_on_load(1);

        int width, height, channels;

        stbi_uc* data = stbi_load(path.c_str(), &width, &height, &channels, 0);
        RADIANT_CORE_ASSERT(data, "Failed To Load Image");

        m_Width = width;
        m_Height = height;

        if (channels == 4) {
            m_InternalFormat = GL_RGBA8;
            m_DataFormat = GL_RGBA;
        }
        else if (channels == 3) {
            m_InternalFormat = GL_RGB8;
            m_DataFormat = GL_RGB;
        }
        else {
            RADIANT_CORE_ERROR("Texture Format Not Supported, Channels: {0})", channels);   
        }

        glCreateTextures(GL_TEXTURE_2D, 1, &m_RendererID);
        glTextureStorage2D(m_RendererID, 1, m_InternalFormat, m_Width, m_Height);

        glTextureParameteri(m_RendererID, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
        glTextureParameteri(m_RendererID, GL_TEXTURE_MAG_FILTER, GL_NEAREST);

        glTextureSubImage2D(m_RendererID, 0, 0, 0, m_Width, m_Height, m_DataFormat, GL_UNSIGNED_BYTE, data);

        stbi_image_free(data);
    }
RadiantMin3
  • 103
  • 1
  • 8

1 Answers1

1

When an RGB image is loaded to a texture object, GL_UNPACK_ALIGNMENT needs to be set to 1.
By default GL_UNPACK_ALIGNMENT is 4, so each line of an image is assumed to be aligned to 4 bytes. The pixels in the buffer have a size of 3 bytes and are tightly packed, this would cause a misalignment:

glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
glTextureSubImage2D(m_RendererID, 0, 0, 0, m_Width, m_Height, m_DataFormat, GL_UNSIGNED_BYTE, data);
Rabbid76
  • 202,892
  • 27
  • 131
  • 174