[英]OpenGL / LWJGL texture loads, but texture won't render on quad
我開始在 Java 中使用 LWJGL/OpenGL 來創建 2D 游戲,但是我很難渲染一個簡單的 32x32 四邊形(正方形)有紋理。 我已經創建了一個紋理加載系統並遵循了正確的紋理說明,但紋理不會顯示。 我的代碼如下:
devBlock64.bind();
glEnable(GL_TEXTURE_2D);
GL11.glBegin(GL11.GL_QUADS);
GL11.glTexCoord2f(0, 0);
GL11.glVertex2f(0, 0);
GL11.glTexCoord2f(0, 1);
GL11.glVertex2f(32, 0);
GL11.glTexCoord2f(1, 1);
GL11.glVertex2f(32, 32);
GL11.glTexCoord2f(1, 0);
GL11.glVertex2f(0, 32);
GL11.glEnd();
glDisable(GL_TEXTURE_2D);
以上是每次調用“render”時的代碼。 “devBlock64”只是一個加載了 64x64 紋理的 Texture 對象(但在這種情況下它是 32x32,因為我將它保存為錯誤的大小)
此外,這是我在加載紋理並生成其紋理 ID 后調用的選項和函數:
this.bind();
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, buffer);
圖像加載正確,但不會顯示。 this.bind();
調用我的函數,它只是這樣做: glBindTexture(GL_TEXTURE_2D, id):
而且,如果有人好奇,我的游戲循環,其他一切都是根據 OpenGL 設置窗口的教程完成的:
public void loop() {
// Binds GLFW with OpenGL
GL.createCapabilities();
glOrtho(0f, 800, 600, 0f, 0f, 1f);
glClearColor(1.0f, 1f, 1f, 1f);
//glLoadIdentity();
world.loadTextures();
while(!hasWindowRequestedClose()) {
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
world.onUpdate();
world.render();
glfwSwapBuffers(handle);
glfwPollEvents();
}
destroy();
}
嘿,我已經檢查了你的代碼,一切似乎都很好。 我有幾個建議。
你用的是哪個opengl版本? glBegin()
和glEnd()
從較新的版本(3.2 以后)中刪除。 相反,您需要將頂點數據上傳到頂點緩沖區對象。 然后使用 glVertexAttribPointer 告訴 openGL 數據是如何布局的。
更好的方法是使用着色器並將紋理綁定到着色器。
這是我加載紋理的代碼。
public static int loadTexture(String path) {
int[] pixels = null;
int width = 0;
int height = 0;
try {
InputStream resourceBuff = Loader.class.getResourceAsStream(path);
BufferedImage image = ImageIO.read(resourceBuff);
width = image.getWidth();
height = image.getHeight();
pixels = new int[width * height];
image.getRGB(0, 0, width, height, pixels, 0, width);
} catch (IOException e) {
e.printStackTrace();
}
int[] data = new int[width * height];
for (int i = 0; i < width * height; i++) {
int a = (pixels[i] & 0xff000000) >> 24;
int r = (pixels[i] & 0xff0000) >> 16;
int g = (pixels[i] & 0xff00) >> 8;
int b = (pixels[i] & 0xff);
data[i] = a << 24 | b << 16 | g << 8 | r;
}
int result = glGenTextures();
glBindTexture(GL_TEXTURE_2D, result);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE,
storeDataInIntBuffer((data)));
glBindTexture(GL_TEXTURE_2D, 0);
return result;
}
希望這會幫助你。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.