c++ - 将 png 作为纹理加载并将其绑定(bind)到球体

标签 c++ opengl

我找不到任何关于如何加载 PNG 文件并将其用作纹理以将其绑定(bind)到球体的教程。有没有库函数可以做到这一点? 我将如何将它绑定(bind)到一个球体? 我已经试过了,但没有用,没有错误,但纹理没有加载到球体上。 我在 glutMainLoop() 之前用特定文件调用 LoadTexture

这是我加载文件的代码:

GLuint LoadTexture( const char * filename, int width, int height )
    {
GLuint texture;
unsigned char * data;
FILE * file;

//The following code will read in our PNG file
file = fopen( filename, "rb" );
if ( file == NULL ) return 0;
data = (unsigned char *)malloc( width * height * 3 );
fread( data, width * height * 3, 1, file );
fclose( file );

glGenTextures( 1, &texture ); //generate the texture with 

glBindTexture( GL_TEXTURE_2D, texture ); //bind the texture

glTexEnvf( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, 
GL_MODULATE ); //set texture environment parameters



//even better quality, but this will do for now.
glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER,
 GL_LINEAR );
glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER,
 GL_LINEAR );

//Here we are setting the parameter to repeat the texture 
//to the edge of our shape. 
glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, 
 GL_REPEAT );
glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, 
 GL_REPEAT );

//Generate the texture
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0,
 GL_RGB, GL_UNSIGNED_BYTE, data);
free( data ); //free the texture
return texture; //return whether it was successfull

这是我创建球体的地方

void renderScene(void) {

// Clear Color and Depth Buffers
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

 glEnable( GL_TEXTURE_2D );
// Reset transformations
glLoadIdentity();
glBindTexture( GL_TEXTURE_2D, texture );
glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);

glPushMatrix();
glTranslatef(0.0,2.0,-6);
glRotatef(angle, 0.0f, 2.0, -6.0f);
glutSolidSphere(1,50,50);
glPopMatrix();


angle+=0.4f;
glDisable(GL_TEXTURE_2D);
glutSwapBuffers();
 }

我做对了吗?

最佳答案

您正在将压缩的 PNG 数据提供给 OpenGL。必须先解压,因为OpenGL纹理函数无法理解PNG。你可以使用一些图像库解压缩它,比如 stb_image.c

关于c++ - 将 png 作为纹理加载并将其绑定(bind)到球体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13310770/

相关文章:

c++ - std::chrono::milliseconds 的 vector

c - OpenGL纹理生成

opengl - 使用 OpenGL 的可编辑纹理

opengl - 片段着色器眼空间未缩放深度坐标

c++ - OpenGL:多个重叠视口(viewport)闪烁

java - 按给定四元数旋转单位 vector

c++ - 将 gperftools 与排序一起使用时分析计时器已过期

c++ - 操作系统和编译器如何通信以启动程序编译

c++ - 将几个依赖的 C++ makefile 项目移植到 MSVC 中

c++ - 为什么我的线速度返回为 0,即使我的重力似乎已设置