2015-04-21 78 views
1

我正在製作一個LWJGL遊戲,並且通過使用openGL,我相信我的最佳選擇是使用紋理並使用四邊形渲染它們。但是,我似乎只能找到有關從整個圖像只有一個紋理的圖像加載紋理的信息。我想要做的是讀取整個spritesheet並能夠將其分離成不同的紋理。有沒有一個簡單的方法來做到這一點?LWJGL:從多個貼圖獲取紋理

回答

1

您可以從圖像載入圖像。 .png文件到BufferedImage

public static BufferedImage loadImage(String location) 
{ 
    try { 
     BufferedImage image = ImageIO.read(new File(location)); 
     return image; 
    } catch (IOException e) { 
     System.out.println("Could not load texture: " + location); 
    } 
    return null; 
} 

現在你可以調用getSubimage(int x, int y, int w, int h)上造成BufferedImage,讓您的分離式的一部分。你現在只需要創建一個BufferedImage的紋理。此代碼應該做的工作:

public static int loadTexture(BufferedImage image){ 
    if (image == null) { 
     return 0; 
    } 

    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); //4 for RGBA, 3 for RGB 

    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));  // Red component 
      buffer.put((byte) ((pixel >> 8) & 0xFF));  // Green component 
      buffer.put((byte) (pixel & 0xFF));    // Blue component 
      buffer.put((byte) ((pixel >> 24) & 0xFF)); // Alpha component. Only for RGBA 
     } 
    } 

    buffer.flip(); //FOR THE LOVE OF GOD DO NOT FORGET THIS 

    // You now have a ByteBuffer filled with the color data of each pixel. 
    // Now just create a texture ID and bind it. Then you can load it using 
    // whatever OpenGL method you want, for example: 

    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_NEAREST); 
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); 

    //Send texel data to OpenGL 
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, image.getWidth(), image.getHeight(), 0, GL_RGBA, GL_UNSIGNED_BYTE, buffer); //GL_RGBA8 was GL_RGB8A 

    return textureID; 
} 

你現在能夠返回textureIDglBindTexture(GL_TEXTURE_2D, textureID);綁定,如果你需要的質感。 這樣你只需要將BufferedImage分成所需的部分。

我推薦閱讀:LWJGL Textures and Strings