我正在尝试为OpenGL 3.3
. 该项目是用 C++ 编写的。我遇到的问题是,尽管加载了立方体贴图纹理并绑定了采样器,但我得到了黑色像素,如图所示(立方体内部有法线):
来自采样器的颜色
这是我对采样器所做的事情的问题,因为当我使用顶点坐标作为颜色时,它工作得很好: 来自位置的颜色
我已经搜索过类似的问题,但没有一个答案真的对我有用。
以下是代码中有趣的部分:
顶点着色器
#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;
}
片段着色器
#version 330 core
in vec3 TexCoords;
out vec4 color;
uniform samplerCube skybox;
void main()
{
color = texture(skybox, TexCoords);
}
CubeTexture 类
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);
}
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);