Difference between revisions of "Texturing a Sphere"

From OpenGL Wiki
Jump to navigation Jump to search
m (categorizing.)
Line 67: Line 67:
   //.........and delete it when your program closes
   //.........and delete it when your program closes
[[Category:Rendering Techniques]]

Revision as of 05:36, 20 September 2009

Let's assume you want to create something that looks like the planet earth. You want to apply a map of the earth to a sphere.
There are 2 ways to texture a sphere. Either by applying a cubemap or either by applying a 2D texture. For best result, use a cubemap. The problem with applying a 2D texture is that when you wrap a 2D texture onto a sphere, the top and bottom area of the sphere, the texture looks squeezed.

Cubemapping a Sphere

Load a cubemap as shown here http://www.opengl.org/wiki/index.php/Common_Mistakes#Creating_a_Cubemap_Texture
Let's assume that we'll be using shaders. If you haven't learned shaders yet, now is the time.
This code is in GLSL. The vertex shader :

 uniform mat4 ProjectionModelviewMatrix;
 varying vec3 TexCoord0;
 void main()
    gl_Position = ProjectionModelviewMatrix * gl_Vertex;
    TexCoord0 = gl_Normal;

The fragment shader. Notice that the normal has been copied to TexCoord0 and this will be used to sample the cubemap.

 uniform samplerCube Texture0;
 varying vec3 TexCoord0;
 void main()
    vec4 texel = textureCube(Texture0, TexCoord0);
    gl_FragColor = texel;

2D Texture Mapping a Sphere

Either you need to write your own code to create a sphere and you compute the texcoords yourself or you use another library like GLU or glhlib.

 GLUquadricObj *sphere=NULL;
 sphere = gluNewQuadric();
 gluQuadricTexture(sphere, TRUE);
 gluQuadricNormals(sphere, GLU_SMOOTH);
 //Making a display list
 mysphereID = 1;
 glNewList(mysphereID, GL_COMPILE);
 gluSphere(sphere, 1.0, 20, 20);
 //and whenever you want to render, call glCallList(mysphereID)
 //to kill the display list, glDeleteLists(mysphereID, 1);

If you want to use glhlib http://www.geocities.com/vmelkon/glhlibrary.html
The header file glhlib.h explains how to use :

 glhSphereObject2 Sphere;
 memset(&Sphere, 0, sizeof(glhSphereObject2));
 //HOW TO RENDER (You might want to use VBO, I'm just using VA here):
 glBindTexture(GL_TEXTURE_2D, TextureID);
 glVertexPointer(3, GL_FLOAT, sizeof(GLHVertex_VNT), Sphere.pVertex);
 uint mypointer=(uint)Sphere.pVertex;
 glNormalPointer(GL_FLOAT, sizeof(GLHVertex_VNT), (uint *)mypointer);
 glTexCoordPointer(2, GL_FLOAT, sizeof(GLHVertex_VNT), (uint *)mypointer);
 glDrawRangeElements(GL_TRIANGLES, Sphere.Start_DrawRangeElements, Sphere.End_DrawRangeElements, Sphere.TotalIndex, GL_UNSIGNED_SHORT, Sphere.pIndex16Bit);
 //.........and delete it when your program closes