Twometer
Twometer

Reputation: 1721

LWJGL Screwed textures

I'm currently working on a game with java & lwjgl and in my main menu I try to draw a background image. For some reason, whatever texture loading and drawing technique i use, the image gets screwed up completely.

This is what happens:

And this is what it's supposed to look like:

Link

This is my code for loading the texture:

  private int loadTexture(String imgName) {
    try {
        BufferedImage img = ImageIO.read(JarStreamLoader.load(imgName));
        ByteBuffer buffer = BufferUtils.createByteBuffer(img.getWidth() * img.getHeight() * 3);
        for (int x = 0; x < img.getWidth(); x++) {
            for (int y = 0; y < img.getHeight(); y++) {
                Color color = new Color(img.getRGB(x, y));
                buffer.put((byte) color.getRed());
                buffer.put((byte) color.getGreen());
                buffer.put((byte) color.getBlue());
            }
        }
        buffer.flip();
        int textureId = glGenTextures();
        glBindTexture(GL_TEXTURE_2D, textureId);
        glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, img.getWidth(), img.getHeight(), 0, GL_RGB, GL_UNSIGNED_BYTE, buffer);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
        return textureId;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

And that's my rendering code:

public static void drawRect(int x, int y, int width, int height, Color color) {
    glColor4f(color.getRed() / 255, color.getGreen() / 255, color.getBlue() / 255, 1.0F);
    glBegin(GL_QUADS);

    glTexCoord2f(0.0f, 0.0f);
    glVertex2d(x, y);

    glTexCoord2f(0.0f, 1.0F);
    glVertex2d(x, y + height);

    glTexCoord2f(1.0F, 1.0F);
    glVertex2d(x + width, y + height);

    glTexCoord2f(1.0F, 0.0f);
    glVertex2d(x + width, y);

    glEnd();
}

Any Ideas?

Upvotes: 1

Views: 65

Answers (1)

vallentin
vallentin

Reputation: 26217

You're adding the pixels in the wrong order. You need to do it in this order:

for (int y = 0; y < img.getHeight(); y++)
    for (int x = 0; x < img.getWidth(); x++)

Note that OpenGL's origin is at the bottom left corner, so you might have to flip the image on the y-axis as well:

Color color = new Color(img.getRGB(x, img.getHeight() - y - 1));

Upvotes: 1

Related Questions