我一直在用C ++编写一个新项目,使用GLFW作为OpenGL包装器,并使用stb_image.h工具加载图像。
我使用以下代码段加载图片:
this->width = width;
this->height = height;
int bpp;
unsigned char* image = stbi_load(("./res/textures/"+fileName).c_str(), &width, &height, &bpp, STBI_rgb_alpha);
if (image == nullptr) std::cerr << "Unable to load texture: " + fileName << std::endl;
glGenTextures(1, &id);
glBindTexture(GL_TEXTURE_2D, id);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
if(bpp == 3) glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, image);
else if (bpp == 4) glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, image);
stbi_image_free(image);
我通过以下方式渲染纹理:
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glEnable(GL_TEXTURE_2D);
glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
glBindTexture(GL_TEXTURE_2D, texture->id);
glBegin(GL_QUADS);
glTexCoord2i(0, 0); glVertex3i(0, 0, -5);
glTexCoord2i(0, 1); glVertex3i(0, 1, -5);
glTexCoord2i(1, 1); glVertex3i(1, 1, -5);
glTexCoord2i(1, 0); glVertex3i(1, 0, -5);
glEnd();
我正在交换缓冲区,轮询事件,并使用glfwWindowHint()设置各种颜色位
无济于事。 当我跑步时,我只收到以下结果:
答案 0 :(得分:1)
您必须在glActiveTexture(GL_TEXTURE0)
之前致电glBindTexture(GL_TEXTURE_2D, texture->id)
。因此,您的上一个代码应如下所示:
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glEnable(GL_TEXTURE_2D);
glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, texture->id);
glBegin(GL_QUADS);
glTexCoord2f(0, 0); glVertex3f(0, 0, -5);
glTexCoord2f(0, 1); glVertex3f(0, 1, -5);
glTexCoord2f(1, 1); glVertex3f(1, 1, -5);
glTexCoord2f(1, 0); glVertex3f(1, 0, -5);
glEnd();
此外,glActiveTexture(...)
与GLFW无关。它是opengl的一部分。