glEnable(GL_TEXTURE_2D)
. 默认情况下禁用纹理。
#include <SDL/SDL.h>
#include <GL/glew.h>
#include <GL/gl.h>
#include <GL/glu.h>
#include <wchar.h>
#include <math.h>
#include <SDL/SDL_image.h>
#undef main
static int scrWidth = 800;
static int scrHeight = 600;
int main(int argc, char** argv){
SDL_Init(SDL_INIT_VIDEO);
SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 8);
SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 8);
SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 8);
SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 16);
SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
SDL_GL_SetAttribute(SDL_GL_SWAP_CONTROL, 0);
if (SDL_SetVideoMode(scrWidth, scrHeight, 32, SDL_OPENGL) == 0){
fprintf(stderr, "couldn't set mode %dx%d!\n", 640, 480);
SDL_Quit();
return -1;
}
glewInit();
IMG_Init(IMG_INIT_PNG|IMG_INIT_JPG);
SDL_ShowCursor(SDL_DISABLE);
glClearColor(0.2f, 0.2f, 0.2f, 0.2f);
glClearDepth(1.0f);
glEnable(GL_DEPTH_TEST);
glEnable(GL_TEXTURE_2D);
GLuint texId = 0;
glGenTextures(1, &texId);
glBindTexture(GL_TEXTURE_2D, texId);
SDL_Surface* tex = IMG_Load("1.png");
int texW = tex->w, texH = tex->h;
SDL_LockSurface(tex);
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
int bytesPerPixel = tex->format->BytesPerPixel;
GLenum texFormat = GL_INVALID_ENUM, pixelFormat = GL_INVALID_ENUM;
switch(bytesPerPixel){
case(3):
texFormat = GL_RGB;
pixelFormat = texFormat;
break;
case(4):
texFormat = GL_RGBA;
pixelFormat = texFormat;
break;
default:
fprintf(stderr, "invalid texture format: %d bytes per pixel", bytesPerPixel);
SDL_FreeSurface(tex);
SDL_Quit();
return -1;
break;
}
int expectedPitch = bytesPerPixel*tex->w;
if (tex->pitch != expectedPitch){
fprintf(stderr, "invalid surface pitch %d instead of %d", tex->pitch, expectedPitch);
SDL_FreeSurface(tex);
SDL_Quit();
return -1;
}
glTexImage2D(GL_TEXTURE_2D, 0, texFormat, texW, texH, 0, pixelFormat, GL_UNSIGNED_BYTE, tex->pixels);
GLenum err = glGetError();
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
SDL_UnlockSurface(tex);
SDL_FreeSurface(tex);
glBindTexture(GL_TEXTURE_2D, texId);
bool running = true;
while (running){
SDL_Event event;
if (SDL_PollEvent(&event)){
switch(event.type){
case SDL_QUIT:
running = false;
break;
};
}
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(0, scrWidth, scrHeight, 0);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
glBindTexture(GL_TEXTURE_2D, texId);
glBegin(GL_TRIANGLE_FAN);
glTexCoord2f(0, 0);
glVertex2f(0, 0);
glTexCoord2f(1, 0);
glVertex2f((float)texW, 0);
glTexCoord2f(1, 1);
glVertex2f((float)texW, (float)texH);
glTexCoord2f(0, 1);
glVertex2f(0, (float)texH);
glEnd();
glDisable(GL_DEPTH_TEST);
glFlush();
SDL_GL_SwapBuffers();
}
glDeleteTextures(1, &texId);
IMG_Quit();
SDL_Quit();
return 0;
}