关于多纹理(OpenGL),我做错了什么?

时间:2017-05-16 05:39:28

标签: opengl glsl textures fragment-shader

我正在编写凹凸贴图演示,因此我需要一个图像纹理和一个应加载到片段着色器中的普通纹理。

这是我的OpenGL代码的纹理部分:

glActiveTexture(GL_TEXTURE0);
GLuint textureID;
glGenTextures(1, &textureID);
glBindTexture(GL_TEXTURE_2D, textureID);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, 1024, 1024, 0, GL_RGB, GL_UNSIGNED_BYTE, brick);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
GLint textureLocation = glGetUniformLocation(shader, "texture");
glUniform1i(textureLocation, 0);

glActiveTexture(GL_TEXTURE1);
GLuint normal_textureID;
glGenTextures(1, &normal_textureID);
glBindTexture(GL_TEXTURE_2D, normal_textureID);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, 1024, 1024, 0, GL_RGB, GL_UNSIGNED_BYTE, 
    brick_texture);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
GLint normalTextureLocation = glGetUniformLocation(shader, "normal_texture");
glUniform1i(normalTextureLocation, 1);

这是片段着色器:

uniform vec3 light;
uniform sampler2D texture;
uniform sampler2D normal_texture;

void main() {
    vec3 tex = texture2D(normal_texture, gl_TexCoord[0].st).rgb;
    gl_FragColor = vec4(tex, 1.0);
}

我确信brick数组包含图像纹理,brick_texture数组包含普通纹理;但似乎normal_texturetexture都是图像纹理,而不是普通纹理。关于多纹理,我做错了什么?

1 个答案:

答案 0 :(得分:2)

Since one of your uniform samplers is unreferenced, the other gets optimized out. This causes both textureLocation and normalTextureLocation to be equal and name the one sampler that is referenced. Therefore the latest you set, which is the image texture, take precedence over the normal texture. You can verify this by referencing both samplers:

void main() {
    vec3 tex0 = texture2D(texture, gl_TexCoord[0].st).rgb;
    vec3 tex1 = texture2D(normal_texture, gl_TexCoord[0].st).rgb;
    gl_FragColor = vec4(tex0.r, tex1.gb, 1.0);
}

You should see the red channel from the diffuse and green and blue channels from the normal.

In the future use Debug Output or check for errors to catch such bugs.