我正在尝试学习如何在 OpenGL 中使用纹理。我没有安装 freeimage,所以我必须使用 for 循环创建位图。
我要做的是简单地采用所有红点的纹理,并将其映射到正方形内:
#import <OpenGL/OpenGL.h>
#import <GLUT/GLUT.h>
#import <stdlib.h>
#import <string.h>
#import <math.h>
GLuint texture;
GLfloat (*pixels) [3];
void init()
{
// Inizializzazione
glEnable(GL_DEPTH_TEST);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(45, 1, 1, 1000);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
gluLookAt(0, 0, -100, 0, 0, 0, 0, 1, 0);
// Inizializzazione della texture
glGenTextures(1, &texture);
pixels= malloc(256*256*sizeof(GLfloat[3]));
for(GLuint i=0; i<256*256;i++)
{
pixels[i][0]=1.0;
pixels[i][1]= pixels[i][2]= 0.0;
}
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, 256, 256, 0, GL_RGB, GL_FLOAT, pixels);
}
void display()
{
glClearColor(0, 0, 0, 0);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glEnable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, texture);
glPushMatrix();
glBegin(GL_QUADS);
glVertex3f(0, 0, 0);
glTexCoord2f(0.0, 0.0);
glVertex3f(10, 0, 0);
glTexCoord2f(0.0, 1.0);
glVertex3f(10, 10, 0);
glTexCoord2f(1.0, 1.0);
glVertex3f(0, 10, 0);
glTexCoord2f(0.0, 1.0);
glEnd();
glPopMatrix();
glDisable(GL_TEXTURE_2D);
glutSwapBuffers();
}
int main(int argc, char** argv)
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_RGB | GLUT_DEPTH | GLUT_DOUBLE);
glutInitWindowPosition(100, 100);
glutInitWindowSize(600, 600);
glutCreateWindow(argv[0]);
glutDisplayFunc(display);
init();
glutMainLoop();
free(pixels);
return 0;
}
问题是所有像素都是红色的,但我得到一个白色方块而不是红色方块: