LWJGL纹理渲染为单色
在过去的一个小时左右,我一直在试图修复一个bug,使得我尝试渲染的纹理只是单一的颜色。 奇怪的是,这种加载纹理的方法在我没有像这样的问题之前对我来说工作得很好。 下面是我如何加载纹理(来自BufferedImage):
public static int loadTexture(BufferedImage image)
{
glEnable(GL_TEXTURE_2D);
TextureImpl.unbind();
try
{
int[ ] pixels = new int[image.getWidth() * image.getHeight()];
image.getRGB(0, 0, image.getWidth(), image.getHeight(), pixels, 0,
image.getWidth());
ByteBuffer buffer = BufferUtils.createByteBuffer(image.getWidth()
* image.getHeight() * BYTES_PER_PIXEL);
for (int y = 0; y < image.getHeight(); y++)
{
for (int x = 0; x < image.getWidth(); x++)
{
int pixel = pixels[y * image.getWidth() + x];
buffer.put((byte) ((pixel >> 16) & 0xFF));
buffer.put((byte) ((pixel >> 8) & 0xFF)); // Green component
buffer.put((byte) (pixel & 0xFF));
buffer.put((byte) ((pixel >> 24) & 0xFF));
}
}
buffer.flip();
int textureID = glGenTextures();
glBindTexture(GL_TEXTURE_2D, textureID);
//Setup wrap mode
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S,
GL12.GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T,
GL12.GL_CLAMP_TO_EDGE);
//Setup texture scaling filtering
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
//Send texel data to OpenGL
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, image.getWidth(),
image.getHeight(), 0, GL_RGBA, GL_UNSIGNED_BYTE, buffer);
return textureID;
}
catch (Exception e)
{
e.printStackTrace();
}
glDisable(GL_TEXTURE_2D);
//Return the texture ID so we can bind it later again
return 0;
}
这就是纹理如何绘制到屏幕上:
glEnable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, blockTexture.getID());
glVertex2i(offsetX * cubeSize + x * cubeSize, y * cubeSize);
glVertex2i((offsetX * cubeSize + x * cubeSize) + cubeSize,
y * cubeSize);
glVertex2i((offsetX * cubeSize + x * cubeSize) + cubeSize,
(y * cubeSize) + cubeSize);
glVertex2i(offsetX * cubeSize + x * cubeSize,
(y * cubeSize) + cubeSize);
glTexCoord2f(0.0f, 0.0f);
glTexCoord2f(1.0f, 0.0f);
glTexCoord2f(1.0f, 1.0f);
glTexCoord2f(0.0f, 1.0f);
glDisable(GL_TEXTURE_2D);
以上代码位于显示列表中。 任何想法可能导致四边形呈现为单一颜色?
你有两个错误。
首先,你不能混合像glEnable和glVertex2i这样的函数。 glVertex2i和glTexCoord2f必须位于glBegin和gEnd之间。
其次,一旦你调用glVertex2i,顶点将具有之前指定的纹理状态。
所以我相信你的代码应该看起来像
glEnable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, blockTexture.getID());
glBegin(...); // you have to specify a primitive type
glTexCoord2f(0.0f, 0.0f);
glVertex2i(offsetX * cubeSize + x * cubeSize, y * cubeSize);
glTexCoord2f(1.0f, 0.0f);
glVertex2i((offsetX * cubeSize + x * cubeSize) + cubeSize,
y * cubeSize);
glTexCoord2f(1.0f, 1.0f);
glVertex2i((offsetX * cubeSize + x * cubeSize) + cubeSize,
(y * cubeSize) + cubeSize);
glTexCoord2f(0.0f, 1.0f);
glVertex2i(offsetX * cubeSize + x * cubeSize,
(y * cubeSize) + cubeSize);
glEnd();
glDisable(GL_TEXTURE_2D);
链接地址: http://www.djcxy.com/p/34025.html