问题
I am hoping to implement a shader on a 2D OpenGL application. My plan is to render a scene to a framebuffer object, and then render that framebuffer object to the screen using a shader.
Here is the scene, which I have drawn to a framebuffer object, and then to the screen from there. Using the arrow keys makes the moon move around (I am quite proud of it!)
However, when I try to render the framebuffer object to the screen using my shader program, I get this:
It is very sad. This fragment shader is one which I got from a tutorial, and I'm sure the problem has to be with the Uniform Variables.
Here is the Fragment Shader:
#version 330
in vec2 texCoord;
out vec4 outputColor;
uniform sampler2D gSampler;
void main()
{
outputColor = texture2D(gSampler, texCoord);
}
Here is how I set up the Uniform Variables:
gSampler = glGetUniformLocation(mProgramID, "gSampler");
glUniform1i(gSampler, GL_TEXTURE0);
Here is how I render the Framebuffer (fbo_texture) to the screen, using my shader program (mProgramID)
glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0 );
glUseProgram(mProgramID);
glColor3f(1.0, 1.0, 1.0);
glEnable(GL_TEXTURE_2D);
glActiveTexture(GL_TEXTURE0 + 0);
glBindTexture(GL_TEXTURE_2D, fbo_texture);
glBegin(GL_QUADS);x1= 0.0;x2= 400.0;y1= 0.0;y2 = 400.0;
glTexCoord2f(0.0f, 1.0f); glVertex2f(x1, y1);
glTexCoord2f(0.0f, 0.0f); glVertex2f(x1, y2);
glTexCoord2f(1.0f, 0.0f); glVertex2f(x2, y2);
glTexCoord2f(1.0f, 1.0f); glVertex2f(x2, y1);
glEnd();glDisable(GL_TEXTURE_2D);
SDL_GL_SwapBuffers();
So my question is- What is the link between a texture and a sampler? Do I need to render a textured quad, if the shader is already sampling the texture? Why not just render a blank quad if the shader is texturizing it?
EDIT: Here is the vertex shader:
void main()
{
gl_TexCoord[0] = gl_MultiTexCoord0;
gl_Position = ftransform();
}
回答1:
There's indeed a problem with how you set the uniform value for the sampler:
gSampler = glGetUniformLocation(mProgramID, "gSampler");
glUniform1i(gSampler, GL_TEXTURE0);
The value you need to set for the uniform is the index of the texture unit, not the corresponding enum value. Since you are using texture unit 0 in this case, you need to replace the glUniform1i()
call by:
glUniform1i(gSampler, 0);
来源:https://stackoverflow.com/questions/24131541/opengl-glsl-binding-sampler-for-fragment-shader