C++ OpenGL cubeSampler returns black

405 views Asked by At

I am trying to create a skybox for a project in OpenGL 3.3. The project is written in C++. The problem i have is despite loading a cube map texture and binding the sampler i get black pixels, like in the picture (the cube has normals directed inside of it): color from sampler

It is a problem with what i am doing with the sampler because when i use vertex coordinates as color it works beautifully: color from postition

I have searched for similar problems but none of the answers really worked for me.

Here are the interesting parts of the code:

Vertex shader

#version 330 core
layout (location = 0) in vec3 position;
out vec3 TexCoords;

uniform mat4 mvp;

void main()
{
    gl_Position = mvp * vec4(position, 1.0);
    TexCoords = position;
}

Fragment shader

#version 330 core
in vec3 TexCoords;
out vec4 color;

uniform samplerCube skybox;

void main()
{
    color = texture(skybox, TexCoords);
}

CubeTexture class

CubeTexture::CubeTexture(GLenum texture, std::vector<const GLchar*> faces)
{
    this->texture = texture;

    glGenTextures(1, &texture_id);
    glActiveTexture(texture);

    int width, height;
    unsigned char* image;

    glBindTexture(GL_TEXTURE_CUBE_MAP, texture_id);
    for(GLuint i = 0; i < faces.size(); i++)
    {
        image = SOIL_load_image(faces[i], &width, &height, 0, SOIL_LOAD_RGB);
        if (image == nullptr)
            throw std::runtime_error(std::string("Failed to load texture file"));
        glTexImage2D(
            GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, 0,
            GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, image
        );
    }
    glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
    glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
    glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);
    glBindTexture(GL_TEXTURE_CUBE_MAP, 0);
}

void CubeTexture::bind(GLuint shader_program_id, const char* name, unsigned int location)
{
    glActiveTexture(texture);
    glBindTexture(GL_TEXTURE_CUBE_MAP, texture_id);
    glUniform1i(glGetUniformLocation(shader_program_id, name), location);
}

Fragment of the main.cpp

// ...

std::vector<const GLchar*> faces;
faces.push_back("res/textures/skybox/right.png");
faces.push_back("res/textures/skybox/left.png");
faces.push_back("res/textures/skybox/top.png");
faces.push_back("res/textures/skybox/bottom.png");
faces.push_back("res/textures/skybox/back.png");
faces.push_back("res/textures/skybox/front.png");
CubeTexture skybox_texture(GL_TEXTURE0, faces);

// ... in the main loop ...

glUseProgram(skybox_program_id);
skybox_texture.bind(skybox_program_id, "skybox", 0);
0

There are 0 answers