Very basic OpenGL texture creation code:
int width, height;
BYTE * data;
FILE * file;
// open texture data
file = fopen( filename, "rb" );
if ( file == NULL ) return 0;
// allocate buffer
width = 256;
height = 256;
data =(BYTE*) malloc( width * height * 3 );
// read texture data
fread( data, width * height * 3, 1, file );
fclose( file );
glGenTextures( 1, &texture );
glBindTexture( GL_TEXTURE_2D, texture );
//gluBuild2DMipmaps( GL_TEXTURE_2D, 3, width, height, GL_RGB, GL_UNSIGNED_BYTE, data );
glTexImage2D( GL_TEXTURE_2D,0, GL_RGB, width, height,0, GL_RGB, GL_UNSIGNED_BYTE, data );
free( data );
return texture;
and rendering:
glEnable( GL_TEXTURE_2D );
glBindTexture( GL_TEXTURE_2D, texture );
glPushMatrix();
glRotatef( theta, 0.0f, 0.0f, 1.0f );
glBegin( GL_QUADS );
glTexCoord2d(0.0,0.0); glVertex2d(-1.0,-1.0);
glTexCoord2d(1.0,0.0); glVertex2d(+1.0,-1.0);
glTexCoord2d(1.0,1.0); glVertex2d(+1.0,+1.0);
glTexCoord2d(0.0,1.0); glVertex2d(-1.0,+1.0);
glEnd();
glPopMatrix();
SwapBuffers( hDC );
Wen using glTexImage2D
, nothing draws but with gluBuild2DMipmaps
works I saw result with gDebugger the texture created correctly. What is the problem?
When you use
glTexImage2D (...)
in your code you do not build a mipmap complete texture. It only creates storage and supplies data for texture LOD 0. If you are usingGL_..._MIPMAP_...
as your minification filter you need to have LODs (levels-of-detail) for every quarter-resolution step.For example, a texture with dimensions 32x32 requires log2 32 = 5 extra mipmap LODs, as described below:
gluBuild2DMipmaps (...)
does a couple of things:It properly sets the number of LODs in your texture
gluBuild2DMipmaps (...)
: log2 (max (Resx, Resy)) + 1 (min = 0, max = ...).This produces a mipmap complete texture, that can be used with a mipmap minification filter.
Miscellaneous things to note:
The default minification filter in OpenGL is:
GL_NEAREST_MIPMAP_LINEAR
, so you need a mipmap complete texture unless you change it toGL_LINEAR
orGL_NEAREST
.LOD indices in OpenGL work somewhat counter-intuitively. Lower numbers represent higher resolution images, and this is why using a negative LOD bias is sometimes referred to as "texture sharpening."
The geometric series: 1 + 1/4 + 1/16 + 1/64 + ... + 1/N converges to 4/3; mipmaps require ~33% extra storage.