I'm trying to make a context loader in OpenGL and I can't get SOIL to load an image.
Here is the code:
Texture2D TextureLoader::loadSprite(const char* path)
{
int width, height;
GLuint texture = SOIL_load_OGL_texture(path, SOIL_LOAD_RGBA, SOIL_CREATE_NEW_ID, SOIL_FLAG_INVERT_Y);
if (texture == 0)
{
Texture2D failedTexture;
return failedTexture;
}
glBindTexture(GL_TEXTURE_2D, texture);
glGetTexLevelParameteriv(GL_TEXTURE_2D, 0, GL_TEXTURE_WIDTH, &width);
glGetTexLevelParameteriv(GL_TEXTURE_2D, 0, GL_TEXTURE_HEIGHT, &height);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glBindTexture(GL_TEXTURE_2D, 0);
Texture2D texture2d(texture, width, height);
return texture2d;
}
It always fails at the texture == 0 check. The image file is in the same directory as the executable that is generated when the project is built. I've tried both PNG and JPG and it won't work with either.
Despite what you seem to assume, SOIL_load_OGL_texture
will almost certainly not be checking the directory of the executable. Relative paths are relative to the current working directory of the process. Based on your description, I assume that you're using the Visual Studio IDE. By default, Visual Studio will use the directory of the project file as the working directory when running the program. You can change that setting in the project properties > Debugging > Working Directory. I would suggest to change this to whatever directory you plan your finished application to be running in.
If you do want to specify the path to your picture relative to the path of the executable, then I'd suggest to use an absolute path instead. Unfortunately, there's no way to reliably find the path to your executable in standard C++. On Windows, you can use GetModuleFileName()
. Check out this question for more on this topic. Once you have the absolute path of the executable, extract the path to the directory and append your filename. If you can use C++17, std::filesystem
can help you with working with paths…