1
過去一個小時左右我一直在試圖修復一個bug,使得我嘗試渲染的紋理只是單一的顏色。奇怪的是,這種加載紋理的方法在我沒有像這樣的問題之前對我來說工作得很好。下面是如何載入紋理(從一個BufferedImage):LWJGL紋理渲染爲單色
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);
上面的代碼是一個顯示列表中。 任何想法可能會導致四邊形呈現爲單一顏色?
是啊,我忘了指定這些功能是在glBegin和glEnd之間......我縮短了代碼,使其多一點的可讀性題。但glTexCoord定位固定它!現在我只是覺得沒有意識到......感謝您的幫助! – Quaggles