开发者

Trying to texture a sphere using shaders in OpenGL

开发者 https://www.devze.com 2023-03-11 02:43 出处:网络
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

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号