LWJGL Texture is flipped upside down when displayed

 ̄綄美尐妖づ 提交于 2019-12-02 12:26:43

Most image formats store the data top to bottom. Unless you reshuffle the data while loading the image, this is also the sequence in memory after reading the image.

When you create an OpenGL texture from the loaded image, this memory order is maintained unless you explicitly change the order. So the order in texture memory is still top to bottom.

OpenGL does not really have an image/texture orientation. But when you use texture coordinates, they address the texture in the order it's stored in memory. This means for the two extreme values of the t-coordinate:

  • t = 0.0 corresponds to the start of the image in memory, which is the top edge of the image.
  • t = 1.0 corresponds to the end of the image in memory, which is the bottom edge of the image.

Now, looking at your draw calls:

GL11.glTexCoord2f(0, 0);
GL11.glVertex2f(0, 0);

GL11.glTexCoord2f(1, 0);
GL11.glVertex2f(256, 0);

GL11.glTexCoord2f(1, 1);
GL11.glVertex2f(256, 256);

GL11.glTexCoord2f(0, 1);
GL11.glVertex2f(0, 256);

In the default OpenGL coordinate system, the y-coordinate goes bottom to top. So the first two vertices are the bottom vertices of the quad (since they have the smaller y-coordinate), the remaining two are the top two vertices.

Since you used t = 0.0 for the first two vertices, which are at the bottom of the quad, and t = 0.0 corresponds to the top of the image, the top of the image is at the bottom of the quad. Vice versa, you use t = 1.0 for the second two vertices, which are at the top of the quad, and t = 1.0 corresponds to the bottom of the image. Therefore, your image appears upside down.

By far the easiest way to fix this is to change the texture coordinates. Use t = 1.0 for the bottom two vertices, and t = 0.0 for the top two vertices, and the image orientation now matches the orientation of the quad on the screen:

GL11.glTexCoord2f(0.0f, 1.0f);
GL11.glVertex2f(0.0f, 0.0f);

GL11.glTexCoord2f(1.0f, 1.0f);
GL11.glVertex2f(256.0f, 0.0f);

GL11.glTexCoord2f(1.0f, 0.0f);
GL11.glVertex2f(256.0f, 256.0f);

GL11.glTexCoord2f(0.0f, 0.0f);
GL11.glVertex2f(0.0f, 256.0f);

Another option is that you flip the image while reading it in, for example by changing the order of your for loop from:

for (int y = 0; y < image.getHeight(); y++) {

to:

for (int y = image.getHeight() - 1; y >= 0; y--) {

But it's very common to have images in top-down order in memory, and you often don't have control over it if you're using system libraries/frameworks for reading them. So using the texture coordinates to render them in the desired direction is a frequently used approach, and IMHO preferable over shuffling the data around.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!