2012-04-12 46 views
-1

我必須解決這個問題,以下是我做到了,的OpenGL不會綁定我的質地

在RenderEngine綁定代碼:

public int bindTexture(String location) 
{ 
    BufferedImage texture; 
    File il = new File(location); 

    if(textureMap.containsKey(location)) 
    { 
     glBindTexture(GL_TEXTURE_2D, textureMap.get(location)); 
     return textureMap.get(location); 
    } 

    try 
    { 
     texture = ImageIO.read(il); 
    } 
    catch(Exception e) 
    { 
     texture = missingTexture; 
    } 

    try 
    { 
     int i = glGenTextures(); 
     ByteBuffer buffer = BufferUtils.createByteBuffer(texture.getWidth() * texture.getHeight() * 4); 
     Decoder.decodePNGFileToBuffer(buffer, texture); 
     glBindTexture(GL_TEXTURE_2D, i); 
     glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); 
     glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); 
     glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, texture.getWidth(), texture.getHeight(), 0, GL_RGBA, GL_UNSIGNED_BYTE, buffer); 
     textureMap.put(location, i); 
     return i; 
    } 
    catch(Exception e) 
    { 
     e.printStackTrace(); 
    } 

    return 0; 
} 

而且PNG解碼器的方法:

public static void decodePNGFileToBuffer(ByteBuffer buffer, BufferedImage image) 
{ 
    int[] pixels = new int[image.getWidth() * image.getHeight()]; 
    image.getRGB(0, 0, image.getWidth(), image.getHeight(), pixels, 0, image.getWidth()); 

    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)); 
      buffer.put((byte) (pixel & 0xFF)); 
      buffer.put((byte) ((pixel >> 24) & 0xFF)); 
     } 
    } 

    buffer.flip(); 
} 

我希望這可以幫助任何有同樣問題的人 PS textureMap只是一個以字符串作爲鍵值和整數值作爲值的HashMap

回答

2

您已將命令完全錯誤。您需要:

  1. 生成具有glGenTextures紋理名稱/ ID - 使用glBindTexture
  2. 任何只有這樣,你可以用glTexImage
上傳數據ID存儲在一個變量
  • 綁定該ID

    在您的繪圖代碼中,您正在調用整個紋理加載,效率低下,每次都要重新創建一個新的紋理名稱。使用貼圖將紋理文件名映射到ID,並且只有在尚未分配ID的情況下Gen/Bind/TexImage紋理。否則,只需綁定它。

  • +0

    沒有,那沒有工作 – 2012-04-12 09:59:46

    +0

    那麼,你還需要啓用紋理。 glEnable(GL_TEXTURE_2D) - 在glBegin之前調用它 – datenwolf 2012-04-12 10:09:27