Trying to texture a sphere using shaders in OpenGL
I am learning OpenGL from the book OpenGL SuperBible. I am trying to render a sphere created using the function gltMakeSphere(). I bind a texture and run useProgram(). The shaders work with a triangle using a GLBatch, but the sphere just has a green colour to it.
Here is the code:
void RenderScene(void)
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
modelViewMatrix.PushMatrix();
modelViewMatrix.Translate(0,0,-5.0f);
GLint locMVP = glGetUniformLocation(testShader, "mvpMatrix");
glBindTexture(GL_TEXTURE_2D, texture1ID);
glUniformMatrix4fv(locMVP, 1, GL_FALSE,
transformPipeline.GetModelViewProjectionMatrix());
glUseProgram(testShader);
testBatch.Draw();
sphereObject.Draw();
glutSwapBuffers();
glutPostRedisplay();
modelViewMatrix.PopMatrix();
}
Vertex Shader
#version 130
in vec4 vVertex;
in vec2 vTexCoords;
smooth out vec2 vVaryingTexCoords;
void main(void)
{
vVaryingTexCoords开发者_如何学运维 = vTexCoords;
gl_Position = vVertex;
}
Fragment Shader
#version 130
uniform sampler2D colorMap;
out vec4 vFragColor;
smooth in vec2 vVaryingTexCoords;
void main(void)
{
vFragColor = texture(colorMap, vVaryingTexCoords.st);
}
The only think I can think of is that you didn't set texture coordinates corectlly in here :
sphereObject.Draw();
Try rendering the sphere with less precision (less polygons) and see if you get a texture
One way to verify that your texture coordinates are correct (or at least varying per pixel instead of a constant color across the entire sphere) is to change your fragment shader to output the texture coordinate as a color.
#version 130
uniform sampler2D colorMap;
out vec4 vFragColor
smooth in vec2 vVaryingTexCoords;
void main(void)
{
vFragColor = vec4(vVaryingTexCoords, 0.0f, 1.0f);
}
If your sphere is drawn with a constant color with this shader then something is wrong with your texture coordinates.
Also, make sure you call any glUniform* functions AFTER calling glUseProgram as they affect the current program.
精彩评论